Skip to content

Commit

Permalink
Merge pull request #2 from armstjc/0.0.2-The-Betting-Update
Browse files Browse the repository at this point in the history
0.0.2: The "Betting" Update.
  • Loading branch information
armstjc authored Sep 28, 2023
2 parents 6af9b03 + be3f33e commit 9d1f2c2
Show file tree
Hide file tree
Showing 20 changed files with 306 additions and 120 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,5 @@ cython_debug/
#.idea/

# test files
test.py
test.py
test.json
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# CHANGELOG: cfbd_json_py

## 0.0.2: The "Betting" Update.

- Removed the option to cache data. This may be implemented in a future version.
- Implemented `cfbd_json_py.betting.get_cfbd_betting_lines()`, a function that allows a user to get betting lines for a season, a week, and/or for a specific team for the regular season, or postseason.
- Changed `cfbd_json_py.utls.get_cfbd_api_token()`` to log, not print out the fact that the CFBD API key the function is trying to find is not present in the current Python environment.
- Updated the package version to `0.0.2`.

## 0.0.1: The "First Steps" Update

- Implemented the core structure of the python package.
Expand Down
3 changes: 3 additions & 0 deletions cfbd_json_py/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Loaders
# from cfbd_json_py.loaders import *
from cfbd_json_py.betting import *
from cfbd_json_py.coaches import *
from cfbd_json_py.conferences import *
Expand All @@ -8,6 +10,7 @@
from cfbd_json_py.players import *
from cfbd_json_py.plays import *
from cfbd_json_py.rankings import *
from cfbd_json_py.ratings import *
from cfbd_json_py.recruiting import *
from cfbd_json_py.stats import *
from cfbd_json_py.teams import *
Expand Down
270 changes: 245 additions & 25 deletions cfbd_json_py/betting.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@

import time
import warnings
from datetime import datetime

import pandas as pd
import requests
from tqdm import tqdm

from cfbd_json_py.utls import get_cfbd_api_token


def get_cfbd_betting_lines(
year: int,
season: int,
api_key: str = None,
api_key_dir: str = None,
game_id: int = None,
week: int = None,
season_type: str = "regular",
season_type: str = "regular", # "regular" or "postseason"
team: str = None,
home_team: str = None,
away_team: str = None,
conference_abv: str = None,
cache_data: bool = False,
cache_dir: str = None,
# cache_data: bool = False,
# cache_dir: str = None,
return_as_dict: bool = False):
"""
Retrives betting information from the CFBD API for a given season,
Expand All @@ -23,11 +31,11 @@ def get_cfbd_betting_lines(
Parameters
----------
`year` (int, mandatory):
`season` (int, mandatory):
The season you want to retrive betting information from.
`api_key` (str, optional):
Optional argument.
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
Expand Down Expand Up @@ -84,40 +92,252 @@ def get_cfbd_betting_lines(
set `conference_abv` to the abbreviation
of the conference you want betting informaiton from.
`cache_data` (bool, semi-optional):
Semi-optional argument.
By default, `cache_data` will be set to `False`.
If `cache_data` is set to `True`,
this function will cache any data downloaded from the CFBD API.
If there is a previously cached request,
this function will attempt to load the previously cached data,
instead of making an API request in most cases.
`cache_dir` (str, optional):
Optional argument.
If `cache_data` is set to `True`, and `cache_dir` is not null,
this function will try to cache any data downloaded to this custom directory,
instead of caching the data in the user's home directory.
`return_as_dict` (bool, semi-optional):
Semi-optional argument.
If you want this function to return the data as a dictionary,
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 = "tigersAreAwsome" # placeholder for your CFBD API Key.
if cfbd_key != "tigersAreAwsome":
print("Using the user's API key declared in this script for this example.\n\n")
# Gets all betting info for the 2020 CFB season
print(get_cfbd_betting_lines(api_key=cfbd_key, season=2020))
time.sleep(5)
print("")
# Gets all betting info for the 2020 CFB season, in week 2.
print(get_cfbd_betting_lines(api_key=cfbd_key, season=2020, week=2))
time.sleep(5)
print("")
# Gets all betting info for the 2020 CFB season, in the postseason (bowls, playoffs, etc.)
print(get_cfbd_betting_lines(api_key=cfbd_key, season=2020, season_type="postseason"))
time.sleep(5)
print("")
# Gets all betting info for Cincinnati Bearcats Football games the 2020 CFB season
print(get_cfbd_betting_lines(api_key=cfbd_key, season=2020, team="Cincinnati"))
time.sleep(5)
print("")
# Gets all betting info for Ohio Bobcats home games the 2020 CFB season
print(get_cfbd_betting_lines(api_key=cfbd_key, season=2020, home_team="Ohio"))
time.sleep(5)
print("")
# Gets all betting info for Ohio State Buckeyes away games the 2020 CFB season
print(get_cfbd_betting_lines(api_key=cfbd_key,
season=2020, away_team="Ohio State"))
# Gets all betting info for Atlantic Coast Conference (ACC) games the 2020 CFB season
print(get_cfbd_betting_lines(api_key=cfbd_key, year=2020, conference_abv="ACC"))
time.sleep(5)
print("")
# You can also tell this function to just return the API call as a Dictionary (read: JSON) object.
print(get_cfbd_betting_lines(api_key=cfbd_key, year=2020, return_as_dict=True))
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 suposedly loaded into this python environment for this example.\n\n")
# Gets all betting info for the 2020 CFB season
print(get_cfbd_betting_lines(season=2020))
time.sleep(5)
print("")
# Gets all betting info for the 2020 CFB season, in week 2.
print(get_cfbd_betting_lines(season=2020, week=2))
time.sleep(5)
print("")
# Gets all betting info for the 2020 CFB season, in the postseason (bowls, playoffs, etc.)
print(get_cfbd_betting_lines(season=2020, season_type="postseason"))
time.sleep(5)
print("")
# Gets all betting info for Cincinnati Bearcats Football games the 2020 CFB season
print(get_cfbd_betting_lines(season=2020, team="Cincinnati"))
time.sleep(5)
print("")
# Gets all betting info for Ohio Bobcats home games the 2020 CFB season
print(get_cfbd_betting_lines(season=2020, home_team="Ohio"))
time.sleep(5)
print("")
# Gets all betting info for Ohio State Buckeyes away games the 2020 CFB season
print(get_cfbd_betting_lines(season=2020, away_team="Ohio State"))
time.sleep(5)
print("")
# Gets all betting info for Ohio State Buckeyes away games the 2020 CFB season
print(get_cfbd_betting_lines(season=2020, away_team="Ohio State"))
time.sleep(5)
print("")
# Gets all betting info for Atlantic Coast Conference (ACC) games the 2020 CFB season
print(get_cfbd_betting_lines(api_key=cfbd_key, year=2020, conference_abv="ACC"))
time.sleep(5)
print("")
# You can also tell this function to just return the API call as a Dictionary (read: JSON) object.
print(get_cfbd_betting_lines(api_key=cfbd_key, year=2020, return_as_dict=True))
```
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.
"""

# now = datetime.now()
betting_df = pd.DataFrame()
row_df = pd.DataFrame()
url = "https://api.collegefootballdata.com/lines?"

# Input validation
########################################################################################################################################################################################################
if game_id != None and season != None:
warnings.warn(
"If you are getting betting information for a single game, only set `game_id` to the game ID, and leave `season` as `NULL`.")

if season_type == "regular" or season_type == "postseason":
url += f"seasonType={season_type}"
else:
raise ValueError(
"`season_type` must be set to either \"regular\" or \"postseason\".")

if (game_id == None) and (season == None) and (week != None):
raise ValueError(
"When setting a value for `week`, `season` cannot be null.")

# if cache_data == True and ((team != None) or (home_team != None) or (away_team != None) or (conference_abv != None)):
# logging.warning(
# "When caching data is enabled for this function, the following inputs are ignored when making the API call:\n-`team`\n-`home_team`\n-`away_team`\n-`conference_abv`")

if api_key != None:
real_api_key = api_key
del api_key
else:
real_api_key = get_cfbd_api_token(api_key_dir=api_key_dir)

raise NotImplementedError(
'This function has yet to be implemented by this version.'
)
if api_key == "tigersAreAwsome":
raise ValueError(
"You actually need to change `cfbd_key` to your CFBD API key.")
elif "Bearer " in real_api_key:
pass
elif "Bearer" in real_api_key:
real_api_key = real_api_key.replace('Bearer', 'Bearer ')
else:
real_api_key = "Bearer " + real_api_key

# URL builder
########################################################################################################################################################################################################

if game_id != None:
url += f"&gameId={game_id}"

if season != None:
url += f"&year={season}"

if week != None:
url += f"&week={week}"

if team != None:
url += f"&team={team}"

if home_team != None:
url += f"&home={home_team}"

if away_team != None:
url += f"&away={away_team}"

if conference_abv != None:
url += f"&conference={conference_abv}"

headers = {
'Authorization': f'{real_api_key}',
'accept': 'application/json'
}

response = requests.get(url, headers=headers)
time.sleep(0.1)

if response.status_code == 200:
pass
elif response.status_code == 401:
raise ConnectionRefusedError(
f'Could not connect. The connection was refused.\nHTTP Status Code 401.'
)
else:
raise ConnectionError(
f'Could not connect.\nHTTP Status code {response.status_code}'
)

json_data = response.json()

if return_as_dict == True:
return json_data

for game in tqdm(json_data):
gameId = game['id']
season = game['id']
seasonType = game['seasonType']
startDate = game['startDate']
homeTeam = game['homeTeam']
homeConference = game['homeConference']
homeScore = game['homeScore']
awayTeam = game['awayTeam']
awayConference = game['awayConference']
awayScore = game['awayScore']

for line in game['lines']:
row_df = pd.DataFrame(
{
"game_id": gameId,
"season": season,
"season_type": seasonType,
"start_date": startDate,
"home_team": homeTeam,
"home_conference": homeConference,
"home_score": homeScore,
"away_team": awayTeam,
"away_conference": awayConference,
"away_score": awayScore
},
index=[0]
)

row_df["line_provider"] = line['provider']
row_df["spread"] = line['spread']
row_df["formatted_spread"] = line['formattedSpread']
row_df["spread_open"] = line['spreadOpen']
row_df["over_under"] = line['overUnder']
row_df["over_under_open"] = line['overUnderOpen']
row_df["home_moneyline"] = line['homeMoneyline']
row_df["away_moneyline"] = line['awayMoneyline']

betting_df = pd.concat([betting_df, row_df], ignore_index=True)
del row_df

del gameId, seasonType, startDate, homeTeam, \
homeConference, homeScore, awayTeam, \
awayConference, awayScore

return betting_df
3 changes: 1 addition & 2 deletions cfbd_json_py/coaches.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ def get_cfbd_coaches_info(
year: int = None,
min_year: int = None,
max_year: int = None,
cache_data: bool = False,
cache_dir: str = None,

return_as_dict: bool = False):
"""
Expand Down
3 changes: 1 addition & 2 deletions cfbd_json_py/conferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
def get_cfbd_coaches_info(
api_key: str = None,
api_key_dir: str = None,
cache_data: bool = False,
cache_dir: str = None,

return_as_dict: bool = False):
"""
"""
Expand Down
Loading

0 comments on commit 9d1f2c2

Please sign in to comment.