cfbd_json_py.betting

  1# Creation Date: 08/30/2023 01:13 EDT
  2# Last Updated Date: 08/28/2024 11:00 PM EDT
  3# Author: Joseph Armstrong (armstrongjoseph08@gmail.com)
  4# File Name: betting.py
  5# Purpose: Houses functions pertaining to betting data within the CFBD API.
  6###############################################################################
  7
  8# import warnings
  9
 10import pandas as pd
 11import requests
 12from tqdm import tqdm
 13
 14from cfbd_json_py.utls import get_cfbd_api_token
 15
 16
 17def get_cfbd_betting_lines(
 18    season: int = None,
 19    api_key: str = None,
 20    api_key_dir: str = None,
 21    # game_id: int = None,
 22    week: int = None,
 23    season_type: str = "regular",  # "regular" or "postseason"
 24    team: str = None,
 25    home_team: str = None,
 26    away_team: str = None,
 27    conference: str = None,
 28    year: int = None,
 29    home: str = None,
 30    away: str = None,
 31    # cache_data: bool = False,
 32    # cache_dir: str = None,
 33    return_as_dict: bool = False,
 34):
 35    """
 36    Retrieves betting information from the CFBD API for a given season,
 37    or you could only get betting information for a single game.
 38
 39    Parameters
 40    ----------
 41
 42    `season` (int, mandatory):
 43        The season you want to retrieve betting information from.
 44
 45    `api_key` (str, optional):
 46        Semi-optional argument.
 47        If `api_key` is null, this function will attempt to load a CFBD API key
 48        from the python environment, or from a file on this computer.
 49        If `api_key` is not null,
 50        this function will automatically assume that the
 51        inputted `api_key` is a valid CFBD API key.
 52
 53    `api_key_dir` (str, optional):
 54        Optional argument.
 55        If `api_key` is set to am empty string, this variable is ignored.
 56        If `api_key_dir` is null, and `api_key` is null,
 57        this function will try to find
 58        a CFBD API key file in this user's home directory.
 59        If `api_key_dir` is set to a string, and `api_key` is null,
 60        this function will assume that `api_key_dir` is a directory,
 61        and will try to find a CFBD API key file in that directory.
 62
 63    `game_id` (int, optional):
 64        DEPRECATED FROM V1.
 65        If `game_id` is set to a game ID,
 66        `get_cfb_betting_lines()` will try to get
 67        all betting information for that game ID.
 68
 69    `week` (int, optional):
 70        Optional argument.
 71        If `week` is set to an integer, this function will attempt
 72        to load betting data from games in that season, and that week.
 73
 74    `season_type` (str, semi-optional):
 75        Semi-optional argument.
 76        By default, this will be set to "regular", for the CFB regular season.
 77        If you want postseason betting data, set `season_type` to "postseason".
 78        If `season_type` is set to anything but "regular" or "postseason",
 79        a `ValueError()` will be raised.
 80
 81    `team` (str, optional):
 82        Optional argument.
 83        If you only want betting information for a team,
 84        regardless if they are the home/away team,
 85        set `team` to the name of the team
 86        you want game-level betting data from.
 87
 88    `home_team` (str, optional):
 89        Optional argument.
 90        If you only want betting information for a team,
 91        where that team was the home team in this season,
 92        set `home_team` to the name of the team
 93        you want game-level betting data from.
 94
 95
 96    `away_team` (str, optional):
 97        Optional argument.
 98        If you only want betting information for a team,
 99        where that team was the away team in this season,
100        set `away_team` to the name of the team
101        you want game-level betting data from.
102
103    `conference` (str, optional):
104        Optional argument.
105        If you only want betting information from games
106        involving teams a specific conference,
107        set `conference` to the abbreviation
108        of the conference you want betting information from.
109
110    `year` (int):
111        Alternative keyword for `season`
112
113    `home` (str):
114        Alternative keyword for `home_team`
115
116    `away` (str):
117        Alternative keyword for `away_team`
118
119    `return_as_dict` (bool, semi-optional):
120        Semi-optional argument.
121        If you want this function to return
122        the data as a dictionary (read: JSON object),
123        instead of a pandas `DataFrame` object,
124        set `return_as_dict` to `True`.
125
126    Usage
127    ----------
128    ```
129    import time
130
131    from cfbd_json_py.betting import get_cfbd_betting_lines
132
133    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
134
135    if cfbd_key is not "tigersAreAwesome":
136        print(
137            "Using the user's API key declared " +
138            "in this script for this example."
139        )
140
141
142        # Get all available betting info for the 2020 CFB season, in week 2.
143        print(
144            "Get all available betting info for the 2020 CFB season, "+
145            "in week 2."
146        )
147        json_data = get_cfbd_betting_lines(
148            api_key=cfbd_key,
149            season=2020,
150            week=2
151        )
152        print(json_data)
153        time.sleep(5)
154
155        # Get all betting info for the 2020 CFB season,
156        # in the postseason (bowls, playoffs, etc.).
157        print(
158            "Get all betting info for the 2020 CFB season, " +
159            "in the postseason (bowls, playoffs, etc.)."
160        )
161        json_data = get_cfbd_betting_lines(
162            api_key=cfbd_key,
163            season=2020,
164            season_type="postseason"
165        )
166        print(json_data)
167        time.sleep(5)
168
169        # Get all betting info for the University of Cincinnati Bearcats
170        # Football games the 2020 CFB season.
171        print(
172            "Get all betting info for the University of Cincinnati " +
173            "Bearcats Football games the 2020 CFB season."
174        )
175        json_data = get_cfbd_betting_lines(
176            api_key=cfbd_key,
177            season=2020,
178            team="Cincinnati"
179        )
180        print(json_data)
181        time.sleep(5)
182
183        # Get all betting info for Ohio Bobcats home games the 2020 CFB season.
184        print(
185            "Get all betting info for Ohio Bobcats " +
186            "home games the 2020 CFB season."
187        )
188        json_data = get_cfbd_betting_lines(
189            api_key=cfbd_key,
190            season=2020,
191            home_team="Ohio"
192        )
193        print(json_data)
194        time.sleep(5)
195
196        # Get all betting info for Ohio State Buckeyes
197        # away games the 2020 CFB season.
198        print(
199            "Get all betting info for Ohio State Buckeyes " +
200            "away games the 2020 CFB season."
201        )
202        json_data = get_cfbd_betting_lines(
203            api_key=cfbd_key,
204            season=2020,
205            away_team="Ohio State"
206        )
207        print(json_data)
208        time.sleep(5)
209
210        # Get all betting info for Atlantic Coast Conference (ACC)
211        # games the 2020 CFB season.
212        print(
213            "Get all betting info for Atlantic Coast Conference (ACC) " +
214            "games the 2020 CFB season."
215        )
216        json_data = get_cfbd_betting_lines(
217            api_key=cfbd_key,
218            season=2020,
219            conference="ACC"
220        )
221        print(json_data)
222        time.sleep(5)
223
224        # Get all available betting info for the 2020 CFB season.
225        print("Get all available betting info for the 2020 CFB season.")
226        json_data = get_cfbd_betting_lines(
227            api_key=cfbd_key,
228            season=2020
229        )
230        print(json_data)
231        time.sleep(5)
232
233        # You can also tell this function to just return the API call
234        # as a Dictionary (read: JSON) object.
235        print(
236            "You can also tell this function to just return the API call " +
237            "as a Dictionary (read: JSON) object."
238        )
239        json_data = get_cfbd_betting_lines(
240            api_key=cfbd_key,
241            season=2020,
242            team="Cincinnati",
243            return_as_dict=True
244        )
245        print(json_data)
246
247    else:
248        # Alternatively, if the CFBD API key exists in this python environment,
249        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
250        # you could just call these functions directly,
251        # without setting the API key in the script.
252        print(
253            "Using the user's API key supposedly loaded " +
254            "into this python environment for this example."
255        )
256
257        # Get all available betting info for the 2020 CFB season, in week 2.
258        print(
259            "Get all available betting info for the 2020 CFB season, " +
260            "in week 2."
261        )
262        json_data = get_cfbd_betting_lines(
263            season=2020,
264            week=2
265        )
266        print(json_data)
267        time.sleep(5)
268        # Get all betting info for the 2020 CFB season,
269        # in the postseason (bowls, playoffs, etc.).
270        print(
271            "Get all betting info for the 2020 CFB season, " +
272            "in the postseason (bowls, playoffs, etc.)."
273        )
274        json_data = get_cfbd_betting_lines(
275            season=2020,
276            season_type="postseason"
277        )
278        print(json_data)
279        time.sleep(5)
280
281        # Get all betting info for University of Cincinnati
282        # Bearcats Football games the 2020 CFB season.
283        print(
284            "Get all betting info for University of Cincinnati " +
285            "Bearcats Football games the 2020 CFB season."
286        )
287        json_data = get_cfbd_betting_lines(
288            season=2020,
289            team="Cincinnati"
290        )
291        print(json_data)
292        time.sleep(5)
293
294        # Get all betting info for Ohio Bobcats home games the 2020 CFB season.
295        print(
296            "Get all betting info for Ohio Bobcats " +
297            "home games the 2020 CFB season."
298        )
299        json_data = get_cfbd_betting_lines(
300            season=2020,
301            home_team="Ohio"
302        )
303        print(json_data)
304        time.sleep(5)
305
306        # Get all betting info for Ohio State Buckeyes
307        # away games the 2020 CFB season.
308        print(
309            "Get all betting info for Ohio State Buckeyes " +
310            "away games the 2020 CFB season."
311        )
312        json_data = get_cfbd_betting_lines(
313
314            season=2020,
315            away_team="Ohio State"
316        )
317        print(json_data)
318        time.sleep(5)
319
320        # Get all betting info for Atlantic Coast Conference (ACC)
321        # games the 2020 CFB season.
322        print(
323            "Get all betting info for Atlantic Coast Conference (ACC) " +
324            "games the 2020 CFB season."
325        )
326        json_data = get_cfbd_betting_lines(
327            season=2020,
328            conference="ACC"
329        )
330        print(json_data)
331        time.sleep(5)
332
333        # Get all available betting info for the 2020 CFB season.
334        print("Get all available betting info for the 2020 CFB season.")
335        json_data = get_cfbd_betting_lines(
336            season=2020
337        )
338        print(json_data)
339        time.sleep(5)
340
341        # You can also tell this function to just return the API call
342        # as a Dictionary (read: JSON) object.
343        print(
344            "You can also tell this function to just return the API call " +
345            "as a Dictionary (read: JSON) object."
346        )
347        json_data = get_cfbd_betting_lines(
348            season=2020,
349            team="Cincinnati",
350            return_as_dict=True
351        )
352        print(json_data)
353
354    ```
355    Returns
356    ----------
357    A pandas `DataFrame` object with college football betting data,
358    or (if `return_as_dict` is set to `True`)
359    a dictionary object with college football betting data.
360    """
361
362    # now = datetime.now()
363    betting_df = pd.DataFrame()
364    row_df = pd.DataFrame()
365    url = "https://api.collegefootballdata.com/lines?"
366
367    # Input validation
368    ##########################################################################
369
370    # `year` to `season`
371    if season is not None and year is not None and (year is not season):
372        raise ValueError(
373            "When using this function, "
374            + "please specify a season in EITHER `year` or `season`."
375        )
376    if season is not None:
377        pass
378    elif year is not None:
379        season = year
380    else:
381        raise ValueError("No year/season inputted for this function.")
382
383    # `home` to `home_team`
384    if home is not None and home_team is not None and (home is not home_team):
385        raise ValueError(
386            "Inconsistent inputs for `home` and `home_team`."
387            + "\nPlease use either `home` OR `home_team` "
388            + "when calling this function"
389        )
390    elif home is not None:
391        home_team = home
392
393    # `away` to `away_team`
394    if away is not None and away_team is not None and (away is not away_team):
395        raise ValueError(
396            "Inconsistent inputs for `away` and `away_team`."
397            + "\nPlease use either `away` OR `away_team` "
398            + "when calling this function"
399        )
400    elif away is not None:
401        away_team = away
402
403    del year, home, away
404
405    # if game_id is not None and season is not None:
406    #     warnings.warn(
407    #         "If you are getting betting information for a single game, "
408    #         + "only set `game_id` to the game ID, " +
409    #         "and leave `season` as `NULL`."
410    #     )
411
412    if season_type == "regular" or season_type == "postseason":
413        url += f"seasonType={season_type}"
414    else:
415        raise ValueError(
416            '`season_type` must be set to either "regular" or "postseason".'
417        )
418
419    # if (game_id is None) and (season is None) and (week is not None):
420    #     raise ValueError(
421    #         "When setting a value for `week`, `season` cannot be null."
422    #     )
423
424    if (season is None) and (week is not None):
425        raise ValueError(
426            "When setting a value for `week`, `season` cannot be null."
427        )
428
429    if api_key is not None:
430        real_api_key = api_key
431        del api_key
432    else:
433        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
434
435    if real_api_key == "tigersAreAwesome":
436        raise ValueError(
437            "You actually need to change `cfbd_key` to your CFBD API key."
438        )
439    elif "Bearer " in real_api_key:
440        pass
441    elif "Bearer" in real_api_key:
442        real_api_key = real_api_key.replace("Bearer", "Bearer ")
443    else:
444        real_api_key = "Bearer " + real_api_key
445
446    # URL builder
447    ##########################################################################
448
449    # if game_id is not None:
450    #     url += f"&gameId={game_id}"
451
452    if season is not None:
453        url += f"&year={season}"
454
455    if week is not None:
456        url += f"&week={week}"
457
458    if team is not None:
459        url += f"&team={team}"
460
461    if home_team is not None:
462        url += f"&home={home_team}"
463
464    if away_team is not None:
465        url += f"&away={away_team}"
466
467    if conference is not None:
468        url += f"&conference={conference}"
469
470    headers = {
471        "Authorization": f"{real_api_key}", "accept": "application/json"
472    }
473
474    response = requests.get(url, headers=headers)
475
476    if response.status_code == 200:
477        pass
478    elif response.status_code == 401:
479        raise ConnectionRefusedError(
480            "Could not connect. The connection was refused.\n" +
481            "HTTP Status Code 401."
482        )
483    else:
484        raise ConnectionError(
485            f"Could not connect.\nHTTP Status code {response.status_code}"
486        )
487
488    json_data = response.json()
489
490    if return_as_dict is True:
491        return json_data
492
493    for game in tqdm(json_data):
494        gameId = game["id"]
495        season = game["id"]
496        seasonType = game["seasonType"]
497        startDate = game["startDate"]
498        homeTeam = game["homeTeam"]
499        homeConference = game["homeConference"]
500        homeScore = game["homeScore"]
501        awayTeam = game["awayTeam"]
502        awayConference = game["awayConference"]
503        awayScore = game["awayScore"]
504
505        for line in game["lines"]:
506            row_df = pd.DataFrame(
507                {
508                    "game_id": gameId,
509                    "season": season,
510                    "season_type": seasonType,
511                    "start_date": startDate,
512                    "home_team_name": homeTeam,
513                    "home_conference_name": homeConference,
514                    "home_score": homeScore,
515                    "away_team_name": awayTeam,
516                    "away_conference_name": awayConference,
517                    "away_score": awayScore,
518                },
519                index=[0],
520            )
521
522            row_df["line_provider"] = line["provider"]
523            row_df["spread"] = line["spread"]
524            row_df["formatted_spread"] = line["formattedSpread"]
525            row_df["spread_open"] = line["spreadOpen"]
526            row_df["over_under"] = line["overUnder"]
527            row_df["over_under_open"] = line["overUnderOpen"]
528            row_df["home_moneyline"] = line["homeMoneyline"]
529            row_df["away_moneyline"] = line["awayMoneyline"]
530
531            betting_df = pd.concat([betting_df, row_df], ignore_index=True)
532            del row_df
533
534        del (
535            gameId,
536            seasonType,
537            startDate,
538            homeTeam,
539            homeConference,
540            homeScore,
541            awayTeam,
542            awayConference,
543            awayScore,
544        )
545
546    return betting_df
def get_cfbd_betting_lines( season: int = None, api_key: str = None, api_key_dir: str = None, week: int = None, season_type: str = 'regular', team: str = None, home_team: str = None, away_team: str = None, conference: str = None, year: int = None, home: str = None, away: str = None, return_as_dict: bool = False):
 18def get_cfbd_betting_lines(
 19    season: int = None,
 20    api_key: str = None,
 21    api_key_dir: str = None,
 22    # game_id: int = None,
 23    week: int = None,
 24    season_type: str = "regular",  # "regular" or "postseason"
 25    team: str = None,
 26    home_team: str = None,
 27    away_team: str = None,
 28    conference: str = None,
 29    year: int = None,
 30    home: str = None,
 31    away: str = None,
 32    # cache_data: bool = False,
 33    # cache_dir: str = None,
 34    return_as_dict: bool = False,
 35):
 36    """
 37    Retrieves betting information from the CFBD API for a given season,
 38    or you could only get betting information for a single game.
 39
 40    Parameters
 41    ----------
 42
 43    `season` (int, mandatory):
 44        The season you want to retrieve betting information from.
 45
 46    `api_key` (str, optional):
 47        Semi-optional argument.
 48        If `api_key` is null, this function will attempt to load a CFBD API key
 49        from the python environment, or from a file on this computer.
 50        If `api_key` is not null,
 51        this function will automatically assume that the
 52        inputted `api_key` is a valid CFBD API key.
 53
 54    `api_key_dir` (str, optional):
 55        Optional argument.
 56        If `api_key` is set to am empty string, this variable is ignored.
 57        If `api_key_dir` is null, and `api_key` is null,
 58        this function will try to find
 59        a CFBD API key file in this user's home directory.
 60        If `api_key_dir` is set to a string, and `api_key` is null,
 61        this function will assume that `api_key_dir` is a directory,
 62        and will try to find a CFBD API key file in that directory.
 63
 64    `game_id` (int, optional):
 65        DEPRECATED FROM V1.
 66        If `game_id` is set to a game ID,
 67        `get_cfb_betting_lines()` will try to get
 68        all betting information for that game ID.
 69
 70    `week` (int, optional):
 71        Optional argument.
 72        If `week` is set to an integer, this function will attempt
 73        to load betting data from games in that season, and that week.
 74
 75    `season_type` (str, semi-optional):
 76        Semi-optional argument.
 77        By default, this will be set to "regular", for the CFB regular season.
 78        If you want postseason betting data, set `season_type` to "postseason".
 79        If `season_type` is set to anything but "regular" or "postseason",
 80        a `ValueError()` will be raised.
 81
 82    `team` (str, optional):
 83        Optional argument.
 84        If you only want betting information for a team,
 85        regardless if they are the home/away team,
 86        set `team` to the name of the team
 87        you want game-level betting data from.
 88
 89    `home_team` (str, optional):
 90        Optional argument.
 91        If you only want betting information for a team,
 92        where that team was the home team in this season,
 93        set `home_team` to the name of the team
 94        you want game-level betting data from.
 95
 96
 97    `away_team` (str, optional):
 98        Optional argument.
 99        If you only want betting information for a team,
100        where that team was the away team in this season,
101        set `away_team` to the name of the team
102        you want game-level betting data from.
103
104    `conference` (str, optional):
105        Optional argument.
106        If you only want betting information from games
107        involving teams a specific conference,
108        set `conference` to the abbreviation
109        of the conference you want betting information from.
110
111    `year` (int):
112        Alternative keyword for `season`
113
114    `home` (str):
115        Alternative keyword for `home_team`
116
117    `away` (str):
118        Alternative keyword for `away_team`
119
120    `return_as_dict` (bool, semi-optional):
121        Semi-optional argument.
122        If you want this function to return
123        the data as a dictionary (read: JSON object),
124        instead of a pandas `DataFrame` object,
125        set `return_as_dict` to `True`.
126
127    Usage
128    ----------
129    ```
130    import time
131
132    from cfbd_json_py.betting import get_cfbd_betting_lines
133
134    cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.
135
136    if cfbd_key is not "tigersAreAwesome":
137        print(
138            "Using the user's API key declared " +
139            "in this script for this example."
140        )
141
142
143        # Get all available betting info for the 2020 CFB season, in week 2.
144        print(
145            "Get all available betting info for the 2020 CFB season, "+
146            "in week 2."
147        )
148        json_data = get_cfbd_betting_lines(
149            api_key=cfbd_key,
150            season=2020,
151            week=2
152        )
153        print(json_data)
154        time.sleep(5)
155
156        # Get all betting info for the 2020 CFB season,
157        # in the postseason (bowls, playoffs, etc.).
158        print(
159            "Get all betting info for the 2020 CFB season, " +
160            "in the postseason (bowls, playoffs, etc.)."
161        )
162        json_data = get_cfbd_betting_lines(
163            api_key=cfbd_key,
164            season=2020,
165            season_type="postseason"
166        )
167        print(json_data)
168        time.sleep(5)
169
170        # Get all betting info for the University of Cincinnati Bearcats
171        # Football games the 2020 CFB season.
172        print(
173            "Get all betting info for the University of Cincinnati " +
174            "Bearcats Football games the 2020 CFB season."
175        )
176        json_data = get_cfbd_betting_lines(
177            api_key=cfbd_key,
178            season=2020,
179            team="Cincinnati"
180        )
181        print(json_data)
182        time.sleep(5)
183
184        # Get all betting info for Ohio Bobcats home games the 2020 CFB season.
185        print(
186            "Get all betting info for Ohio Bobcats " +
187            "home games the 2020 CFB season."
188        )
189        json_data = get_cfbd_betting_lines(
190            api_key=cfbd_key,
191            season=2020,
192            home_team="Ohio"
193        )
194        print(json_data)
195        time.sleep(5)
196
197        # Get all betting info for Ohio State Buckeyes
198        # away games the 2020 CFB season.
199        print(
200            "Get all betting info for Ohio State Buckeyes " +
201            "away games the 2020 CFB season."
202        )
203        json_data = get_cfbd_betting_lines(
204            api_key=cfbd_key,
205            season=2020,
206            away_team="Ohio State"
207        )
208        print(json_data)
209        time.sleep(5)
210
211        # Get all betting info for Atlantic Coast Conference (ACC)
212        # games the 2020 CFB season.
213        print(
214            "Get all betting info for Atlantic Coast Conference (ACC) " +
215            "games the 2020 CFB season."
216        )
217        json_data = get_cfbd_betting_lines(
218            api_key=cfbd_key,
219            season=2020,
220            conference="ACC"
221        )
222        print(json_data)
223        time.sleep(5)
224
225        # Get all available betting info for the 2020 CFB season.
226        print("Get all available betting info for the 2020 CFB season.")
227        json_data = get_cfbd_betting_lines(
228            api_key=cfbd_key,
229            season=2020
230        )
231        print(json_data)
232        time.sleep(5)
233
234        # You can also tell this function to just return the API call
235        # as a Dictionary (read: JSON) object.
236        print(
237            "You can also tell this function to just return the API call " +
238            "as a Dictionary (read: JSON) object."
239        )
240        json_data = get_cfbd_betting_lines(
241            api_key=cfbd_key,
242            season=2020,
243            team="Cincinnati",
244            return_as_dict=True
245        )
246        print(json_data)
247
248    else:
249        # Alternatively, if the CFBD API key exists in this python environment,
250        # or it's been set by cfbd_json_py.utls.set_cfbd_api_token(),
251        # you could just call these functions directly,
252        # without setting the API key in the script.
253        print(
254            "Using the user's API key supposedly loaded " +
255            "into this python environment for this example."
256        )
257
258        # Get all available betting info for the 2020 CFB season, in week 2.
259        print(
260            "Get all available betting info for the 2020 CFB season, " +
261            "in week 2."
262        )
263        json_data = get_cfbd_betting_lines(
264            season=2020,
265            week=2
266        )
267        print(json_data)
268        time.sleep(5)
269        # Get all betting info for the 2020 CFB season,
270        # in the postseason (bowls, playoffs, etc.).
271        print(
272            "Get all betting info for the 2020 CFB season, " +
273            "in the postseason (bowls, playoffs, etc.)."
274        )
275        json_data = get_cfbd_betting_lines(
276            season=2020,
277            season_type="postseason"
278        )
279        print(json_data)
280        time.sleep(5)
281
282        # Get all betting info for University of Cincinnati
283        # Bearcats Football games the 2020 CFB season.
284        print(
285            "Get all betting info for University of Cincinnati " +
286            "Bearcats Football games the 2020 CFB season."
287        )
288        json_data = get_cfbd_betting_lines(
289            season=2020,
290            team="Cincinnati"
291        )
292        print(json_data)
293        time.sleep(5)
294
295        # Get all betting info for Ohio Bobcats home games the 2020 CFB season.
296        print(
297            "Get all betting info for Ohio Bobcats " +
298            "home games the 2020 CFB season."
299        )
300        json_data = get_cfbd_betting_lines(
301            season=2020,
302            home_team="Ohio"
303        )
304        print(json_data)
305        time.sleep(5)
306
307        # Get all betting info for Ohio State Buckeyes
308        # away games the 2020 CFB season.
309        print(
310            "Get all betting info for Ohio State Buckeyes " +
311            "away games the 2020 CFB season."
312        )
313        json_data = get_cfbd_betting_lines(
314
315            season=2020,
316            away_team="Ohio State"
317        )
318        print(json_data)
319        time.sleep(5)
320
321        # Get all betting info for Atlantic Coast Conference (ACC)
322        # games the 2020 CFB season.
323        print(
324            "Get all betting info for Atlantic Coast Conference (ACC) " +
325            "games the 2020 CFB season."
326        )
327        json_data = get_cfbd_betting_lines(
328            season=2020,
329            conference="ACC"
330        )
331        print(json_data)
332        time.sleep(5)
333
334        # Get all available betting info for the 2020 CFB season.
335        print("Get all available betting info for the 2020 CFB season.")
336        json_data = get_cfbd_betting_lines(
337            season=2020
338        )
339        print(json_data)
340        time.sleep(5)
341
342        # You can also tell this function to just return the API call
343        # as a Dictionary (read: JSON) object.
344        print(
345            "You can also tell this function to just return the API call " +
346            "as a Dictionary (read: JSON) object."
347        )
348        json_data = get_cfbd_betting_lines(
349            season=2020,
350            team="Cincinnati",
351            return_as_dict=True
352        )
353        print(json_data)
354
355    ```
356    Returns
357    ----------
358    A pandas `DataFrame` object with college football betting data,
359    or (if `return_as_dict` is set to `True`)
360    a dictionary object with college football betting data.
361    """
362
363    # now = datetime.now()
364    betting_df = pd.DataFrame()
365    row_df = pd.DataFrame()
366    url = "https://api.collegefootballdata.com/lines?"
367
368    # Input validation
369    ##########################################################################
370
371    # `year` to `season`
372    if season is not None and year is not None and (year is not season):
373        raise ValueError(
374            "When using this function, "
375            + "please specify a season in EITHER `year` or `season`."
376        )
377    if season is not None:
378        pass
379    elif year is not None:
380        season = year
381    else:
382        raise ValueError("No year/season inputted for this function.")
383
384    # `home` to `home_team`
385    if home is not None and home_team is not None and (home is not home_team):
386        raise ValueError(
387            "Inconsistent inputs for `home` and `home_team`."
388            + "\nPlease use either `home` OR `home_team` "
389            + "when calling this function"
390        )
391    elif home is not None:
392        home_team = home
393
394    # `away` to `away_team`
395    if away is not None and away_team is not None and (away is not away_team):
396        raise ValueError(
397            "Inconsistent inputs for `away` and `away_team`."
398            + "\nPlease use either `away` OR `away_team` "
399            + "when calling this function"
400        )
401    elif away is not None:
402        away_team = away
403
404    del year, home, away
405
406    # if game_id is not None and season is not None:
407    #     warnings.warn(
408    #         "If you are getting betting information for a single game, "
409    #         + "only set `game_id` to the game ID, " +
410    #         "and leave `season` as `NULL`."
411    #     )
412
413    if season_type == "regular" or season_type == "postseason":
414        url += f"seasonType={season_type}"
415    else:
416        raise ValueError(
417            '`season_type` must be set to either "regular" or "postseason".'
418        )
419
420    # if (game_id is None) and (season is None) and (week is not None):
421    #     raise ValueError(
422    #         "When setting a value for `week`, `season` cannot be null."
423    #     )
424
425    if (season is None) and (week is not None):
426        raise ValueError(
427            "When setting a value for `week`, `season` cannot be null."
428        )
429
430    if api_key is not None:
431        real_api_key = api_key
432        del api_key
433    else:
434        real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)
435
436    if real_api_key == "tigersAreAwesome":
437        raise ValueError(
438            "You actually need to change `cfbd_key` to your CFBD API key."
439        )
440    elif "Bearer " in real_api_key:
441        pass
442    elif "Bearer" in real_api_key:
443        real_api_key = real_api_key.replace("Bearer", "Bearer ")
444    else:
445        real_api_key = "Bearer " + real_api_key
446
447    # URL builder
448    ##########################################################################
449
450    # if game_id is not None:
451    #     url += f"&gameId={game_id}"
452
453    if season is not None:
454        url += f"&year={season}"
455
456    if week is not None:
457        url += f"&week={week}"
458
459    if team is not None:
460        url += f"&team={team}"
461
462    if home_team is not None:
463        url += f"&home={home_team}"
464
465    if away_team is not None:
466        url += f"&away={away_team}"
467
468    if conference is not None:
469        url += f"&conference={conference}"
470
471    headers = {
472        "Authorization": f"{real_api_key}", "accept": "application/json"
473    }
474
475    response = requests.get(url, headers=headers)
476
477    if response.status_code == 200:
478        pass
479    elif response.status_code == 401:
480        raise ConnectionRefusedError(
481            "Could not connect. The connection was refused.\n" +
482            "HTTP Status Code 401."
483        )
484    else:
485        raise ConnectionError(
486            f"Could not connect.\nHTTP Status code {response.status_code}"
487        )
488
489    json_data = response.json()
490
491    if return_as_dict is True:
492        return json_data
493
494    for game in tqdm(json_data):
495        gameId = game["id"]
496        season = game["id"]
497        seasonType = game["seasonType"]
498        startDate = game["startDate"]
499        homeTeam = game["homeTeam"]
500        homeConference = game["homeConference"]
501        homeScore = game["homeScore"]
502        awayTeam = game["awayTeam"]
503        awayConference = game["awayConference"]
504        awayScore = game["awayScore"]
505
506        for line in game["lines"]:
507            row_df = pd.DataFrame(
508                {
509                    "game_id": gameId,
510                    "season": season,
511                    "season_type": seasonType,
512                    "start_date": startDate,
513                    "home_team_name": homeTeam,
514                    "home_conference_name": homeConference,
515                    "home_score": homeScore,
516                    "away_team_name": awayTeam,
517                    "away_conference_name": awayConference,
518                    "away_score": awayScore,
519                },
520                index=[0],
521            )
522
523            row_df["line_provider"] = line["provider"]
524            row_df["spread"] = line["spread"]
525            row_df["formatted_spread"] = line["formattedSpread"]
526            row_df["spread_open"] = line["spreadOpen"]
527            row_df["over_under"] = line["overUnder"]
528            row_df["over_under_open"] = line["overUnderOpen"]
529            row_df["home_moneyline"] = line["homeMoneyline"]
530            row_df["away_moneyline"] = line["awayMoneyline"]
531
532            betting_df = pd.concat([betting_df, row_df], ignore_index=True)
533            del row_df
534
535        del (
536            gameId,
537            seasonType,
538            startDate,
539            homeTeam,
540            homeConference,
541            homeScore,
542            awayTeam,
543            awayConference,
544            awayScore,
545        )
546
547    return betting_df

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

Parameters

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

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

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

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

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

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

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

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

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

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

year (int): Alternative keyword for season

home (str): Alternative keyword for home_team

away (str): Alternative keyword for away_team

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.betting import get_cfbd_betting_lines

cfbd_key = "tigersAreAwesome"  # placeholder for your CFBD API Key.

if cfbd_key is not "tigersAreAwesome":
    print(
        "Using the user's API key declared " +
        "in this script for this example."
    )


    # Get all available betting info for the 2020 CFB season, in week 2.
    print(
        "Get all available betting info for the 2020 CFB season, "+
        "in week 2."
    )
    json_data = get_cfbd_betting_lines(
        api_key=cfbd_key,
        season=2020,
        week=2
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for the 2020 CFB season,
    # in the postseason (bowls, playoffs, etc.).
    print(
        "Get all betting info for the 2020 CFB season, " +
        "in the postseason (bowls, playoffs, etc.)."
    )
    json_data = get_cfbd_betting_lines(
        api_key=cfbd_key,
        season=2020,
        season_type="postseason"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for the University of Cincinnati Bearcats
    # Football games the 2020 CFB season.
    print(
        "Get all betting info for the University of Cincinnati " +
        "Bearcats Football games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(
        api_key=cfbd_key,
        season=2020,
        team="Cincinnati"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for Ohio Bobcats home games the 2020 CFB season.
    print(
        "Get all betting info for Ohio Bobcats " +
        "home games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(
        api_key=cfbd_key,
        season=2020,
        home_team="Ohio"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for Ohio State Buckeyes
    # away games the 2020 CFB season.
    print(
        "Get all betting info for Ohio State Buckeyes " +
        "away games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(
        api_key=cfbd_key,
        season=2020,
        away_team="Ohio State"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for Atlantic Coast Conference (ACC)
    # games the 2020 CFB season.
    print(
        "Get all betting info for Atlantic Coast Conference (ACC) " +
        "games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(
        api_key=cfbd_key,
        season=2020,
        conference="ACC"
    )
    print(json_data)
    time.sleep(5)

    # Get all available betting info for the 2020 CFB season.
    print("Get all available betting info for the 2020 CFB season.")
    json_data = get_cfbd_betting_lines(
        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_betting_lines(
        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 all available betting info for the 2020 CFB season, in week 2.
    print(
        "Get all available betting info for the 2020 CFB season, " +
        "in week 2."
    )
    json_data = get_cfbd_betting_lines(
        season=2020,
        week=2
    )
    print(json_data)
    time.sleep(5)
    # Get all betting info for the 2020 CFB season,
    # in the postseason (bowls, playoffs, etc.).
    print(
        "Get all betting info for the 2020 CFB season, " +
        "in the postseason (bowls, playoffs, etc.)."
    )
    json_data = get_cfbd_betting_lines(
        season=2020,
        season_type="postseason"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for University of Cincinnati
    # Bearcats Football games the 2020 CFB season.
    print(
        "Get all betting info for University of Cincinnati " +
        "Bearcats Football games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(
        season=2020,
        team="Cincinnati"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for Ohio Bobcats home games the 2020 CFB season.
    print(
        "Get all betting info for Ohio Bobcats " +
        "home games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(
        season=2020,
        home_team="Ohio"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for Ohio State Buckeyes
    # away games the 2020 CFB season.
    print(
        "Get all betting info for Ohio State Buckeyes " +
        "away games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(

        season=2020,
        away_team="Ohio State"
    )
    print(json_data)
    time.sleep(5)

    # Get all betting info for Atlantic Coast Conference (ACC)
    # games the 2020 CFB season.
    print(
        "Get all betting info for Atlantic Coast Conference (ACC) " +
        "games the 2020 CFB season."
    )
    json_data = get_cfbd_betting_lines(
        season=2020,
        conference="ACC"
    )
    print(json_data)
    time.sleep(5)

    # Get all available betting info for the 2020 CFB season.
    print("Get all available betting info for the 2020 CFB season.")
    json_data = get_cfbd_betting_lines(
        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_betting_lines(
        season=2020,
        team="Cincinnati",
        return_as_dict=True
    )
    print(json_data)

Returns

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