-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Adds .get_sports() - Adds .get_odds() This method takes a large amount of optional parameters. Best to go through the documentation provided via the-odds-api.
- Loading branch information
Showing
15 changed files
with
813 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
.idea | ||
.ipynb_checkpoints | ||
.mypy_cache | ||
.vscode | ||
__pycache__ | ||
.pytest_cache | ||
htmlcov | ||
dist | ||
site | ||
.coverage | ||
coverage.xml | ||
.netlify | ||
test.db | ||
log.txt | ||
Pipfile.lock | ||
env3.* | ||
env | ||
docs_build | ||
venv | ||
docs.zip | ||
archive.zip | ||
|
||
# vim temporary files | ||
*~ | ||
.*.sw? | ||
|
||
*/.DS_Store |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 Corey Schaf | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
[tool.poetry] | ||
name = "the-odds" | ||
version = "1.0.1" | ||
description = "The-Odds-APi.com Client (unofficial)." | ||
authors = ["Corey Schaf <cschaf@gmail.com>"] | ||
readme = "README.md" | ||
packages = [{include = "the_odds"}] | ||
license = "MIT" | ||
homepage = "https://github.com/coreyjs/data-golf-api" | ||
repository = "https://github.com/coreyjs/data-golf-api" | ||
keywords = [ "sports", "odds", "betting", "NHL", "NFL", "sports-betting", "odds-fetching", "sports-analytics", "sports-odds", "odds-calculator", "betting-odds", "game-odds", "sports-data", "odds-api", "hockey", "football", "live-odds", "sports-metrics", "daily-fantasy", "sports-stats"] | ||
classifiers = [ | ||
"Development Status :: 4 - Beta", | ||
"Intended Audience :: Developers", | ||
"License :: OSI Approved :: MIT License", | ||
"Programming Language :: Python", | ||
"Programming Language :: Python :: 3.9", | ||
"Programming Language :: Python :: 3.10", | ||
"Programming Language :: Python :: 3.11", | ||
"Programming Language :: Python :: 3.12", | ||
"Topic :: Software Development :: Libraries", | ||
"Topic :: Software Development :: Libraries :: Python Modules" | ||
] | ||
|
||
[tool.poetry.dependencies] | ||
python = "^3.9" | ||
httpx = "^0.27.0" | ||
|
||
[tool.poetry.group.dev.dependencies] | ||
pytest="^7.1.3" | ||
pytest-mock = "*" | ||
mypy = "*" | ||
ruff = "*" | ||
black = "*" | ||
|
||
[build-system] | ||
requires = ["poetry-core"] | ||
build-backend = "poetry.core.masonry.api" | ||
|
||
[tool.ruff] | ||
exclude = [ | ||
".bzr", | ||
".direnv", | ||
".eggs", | ||
".git", | ||
".git-rewrite", | ||
".hg", | ||
".mypy_cache", | ||
".nox", | ||
".pants.d", | ||
".pytype", | ||
".ruff_cache", | ||
".svn", | ||
".tox", | ||
".venv", | ||
"__pypackages__", | ||
"_build", | ||
"buck-out", | ||
"build", | ||
"dist", | ||
"node_modules", | ||
"venv", | ||
] | ||
line-length = 121 |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import pytest | ||
|
||
from the_odds import OddsApiClient | ||
|
||
|
||
@pytest.fixture(scope="function") | ||
def odds_client() -> OddsApiClient: | ||
yield OddsApiClient(api_key="test_key") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import pytest | ||
|
||
from the_odds import OddsApiClient | ||
from the_odds.odds_client import OddsApiInvalidApiKey | ||
|
||
|
||
def test_client_responds_to_v4(): | ||
oac = OddsApiClient(api_key="test_key") | ||
assert oac.v4 is not None | ||
|
||
|
||
def test_client_will_err_on_invalid_api_key(): | ||
with pytest.raises(OddsApiInvalidApiKey): | ||
OddsApiClient(api_key=1234) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .odds_client import OddsApiClient # noqa: F401 |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
from typing import Optional, List | ||
|
||
|
||
class V4: | ||
def __init__(self, client): | ||
self._client = client | ||
|
||
def get_sports(self, all: Optional[bool] = False) -> List[dict]: | ||
|
||
params = {"all": all} | ||
return self._client.get(resource="/sports", params=params) | ||
|
||
def get_odds( | ||
self, | ||
sport: str, | ||
regions: List[str], | ||
markets: List[str], | ||
event_ids: List[str] = None, | ||
bookmakers: List[str] = None, | ||
commence_time_to: str = None, | ||
commence_time_from: str = None, | ||
include_links: bool = None, | ||
include_sids: bool = None, | ||
include_bet_limits: bool = None, | ||
date_format: str = "iso", | ||
odds_format: str = "decimal", | ||
) -> List[dict]: | ||
""" | ||
Returns a list of upcoming and live games with recent odds for a given sport, region and market. | ||
Documentation: https://the-odds-api.com/liveapi/guides/v4/#get-odds | ||
:param sport: The sport key obtained from calling the /sports endpoint. upcoming is always valid, returning | ||
any live games as well as the next 8 upcoming games across all sports. | ||
An example are the following: ['americanfootball_cfl', 'americanfootball_ncaaf', 'americanfootball_ncaaf_championship_winner', | ||
'americanfootball_nfl', 'americanfootball_nfl_super_bowl_winner', 'baseball_kbo', 'baseball_mlb', 'baseball_mlb_world_series_winner', | ||
'baseball_npb', 'basketball_euroleague', 'basketball_nba', 'basketball_nba_championship_winner', 'basketball_nba_preseason', | ||
'basketball_nbl', 'basketball_ncaab_championship_winner', 'boxing_boxing', 'cricket_international_t20', 'cricket_test_match', | ||
'golf_masters_tournament_winner', 'golf_pga_championship_winner', 'icehockey_nhl', 'icehockey_nhl_championship_winner', | ||
'icehockey_sweden_allsvenskan', 'icehockey_sweden_hockey_league', 'mma_mixed_martial_arts', 'politics_us_presidential_election_winner', | ||
'soccer_argentina_primera_division', 'soccer_australia_aleague', 'soccer_austria_bundesliga', 'soccer_belgium_first_div', | ||
'soccer_brazil_campeonato', 'soccer_brazil_serie_b', 'soccer_chile_campeonato', 'soccer_china_superleague', | ||
'soccer_conmebol_copa_libertadores', 'soccer_denmark_superliga', 'soccer_efl_champ', 'soccer_england_league1', | ||
'soccer_england_league2', 'soccer_epl', 'soccer_fifa_world_cup_winner', 'soccer_finland_veikkausliiga', | ||
'soccer_france_ligue_one', 'soccer_france_ligue_two', 'soccer_germany_bundesliga', 'soccer_germany_bundesliga2', | ||
'soccer_germany_liga3', 'soccer_greece_super_league', 'soccer_italy_serie_a', 'soccer_italy_serie_b', | ||
'soccer_japan_j_league', 'soccer_korea_kleague1', 'soccer_league_of_ireland', 'soccer_mexico_ligamx', | ||
'soccer_netherlands_eredivisie', 'soccer_norway_eliteserien', 'soccer_poland_ekstraklasa', 'soccer_portugal_primeira_liga', | ||
'soccer_spain_la_liga', 'soccer_spain_segunda_division', 'soccer_spl', 'soccer_sweden_allsvenskan', 'soccer_sweden_superettan', | ||
'soccer_switzerland_superleague', 'soccer_turkey_super_league', 'soccer_uefa_champs_league', 'soccer_usa_mls'] | ||
:param commence_time_from: Optional - filter the response to show games that commence on and after this parameter. Values are in ISO 8601 format, for example 2023-09-09T00:00:00Z. This parameter has no effect if the sport is set to 'upcoming'. | ||
:param odds_format: Optional - Determines the format of odds in the response. Valid values are decimal and | ||
american. Defaults to decimal. When set to american, small discrepancies might exist for some bookmakers due | ||
to rounding errors. | ||
:param date_format: Optional - Determines the format of timestamps in the response. Valid values are unix and iso (ISO 8601). Defaults to iso. | ||
:param include_bet_limits: Optional - if "true", the response will include the bet limit of each betting option, mainly available for betting exchanges. Valid values are "true" or "false" | ||
:param include_sids: Optional - if "true", the response will include source ids (bookmaker ids) for events, markets and outcomes if available. Valid values are "true" or "false". This field can be useful to construct your own links to handle variations in state or mobile app links. | ||
:param commence_time_to: Optional - filter the response to show games that commence on and before this parameter. Values are in ISO 8601 format, for example 2023-09-10T23:59:59Z. This parameter has no effect if the sport is set to 'upcoming'. | ||
:param bookmakers: Optional - Comma-separated list of bookmakers to be returned. If both bookmakers and regions are both specified, bookmakers takes priority. Bookmakers can be from any region. Every group of 10 bookmakers is the equivalent of 1 region. For example, specifying up to 10 bookmakers counts as 1 region. Specifying between 11 and 20 bookmakers counts as 2 regions. | ||
:param event_ids: Optional List[str] - List of game ids. Filters the response to only return games with the specified ids. | ||
:param include_links: Optional - if "true", the response will include bookmaker links to events, markets, and betslips if available. Valid values are "true" or "false" | ||
:param regions: | ||
:param markets: Optional - Determines which odds market is returned. Defaults to h2h (head to head / moneyline). | ||
Valid markets are h2h (moneyline), spreads (points handicaps), totals (over/under) and outrights (futures). | ||
Multiple markets can be specified if comma delimited. spreads and totals markets are mainly available for | ||
US sports and bookmakers at this time. Each specified market costs 1 against the usage quota, for each | ||
region.Lay odds are automatically included with h2h results for relevant betting exchanges | ||
(Betfair, Matchbook etc). These have a h2h_lay market key.For sports with outright markets (such as Golf), | ||
the market will default to outrights if not specified. Lay odds for outrights (outrights_lay) | ||
will automatically be available for relevant exchanges. | ||
:return: List[dict] | ||
""" | ||
if not markets: | ||
markets = ["h2h"] | ||
params = { | ||
"regions": ",".join(regions), | ||
"markets": ",".join(markets), | ||
"dateFormat": date_format, | ||
"oddsFormat": odds_format, | ||
} | ||
|
||
if event_ids: | ||
params["eventIds"] = ",".join(event_ids) | ||
if bookmakers: | ||
params["bookmakers"] = ",".join(bookmakers) | ||
if commence_time_to: | ||
params["commenceTimeTo"] = commence_time_to | ||
if commence_time_from: | ||
params["commenceTimeFrom"] = commence_time_from | ||
if include_links: | ||
params["includeLinks"] = include_links | ||
if include_sids: | ||
params["includeSids"] = include_sids | ||
if include_bet_limits: | ||
params["includeBetLimits"] = include_bet_limits | ||
|
||
return self._client.get(resource=f"/sports/{sport}/odds", params=params) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
from typing import Tuple | ||
|
||
from the_odds.odds_config import OddsConfig | ||
from the_odds.request_helpers import RequestHelpers | ||
|
||
import httpx | ||
import logging | ||
|
||
|
||
class OddsApiForbidden(Exception): | ||
pass | ||
|
||
|
||
class OddsApiBadRequest(Exception): | ||
pass | ||
|
||
|
||
class HttpClient: | ||
def __init__(self, config: OddsConfig) -> None: | ||
self._config = config | ||
if self._config.debug: | ||
logging.basicConfig(level=logging.INFO) | ||
|
||
def _build_request( | ||
self, | ||
resource: str, | ||
query_params: dict, | ||
) -> Tuple[str, dict]: | ||
""" | ||
Private method to build the URL for the The-Odds-API API. | ||
:param resource: | ||
:return: | ||
""" | ||
query_params["apiKey"] = self._config.api_key | ||
|
||
url = f"{self._config.v4_base_url}{resource}?" | ||
|
||
return url, query_params | ||
|
||
@RequestHelpers.prepare_request | ||
def get(self, resource: str, params: dict = None, **kwargs) -> httpx.request: | ||
""" | ||
Private method to make a get request to the Data Golf API. This wraps the lib httpx functionality. | ||
:param params: | ||
:param resource: | ||
:return: | ||
""" | ||
with httpx.Client( | ||
verify=self._config.ssl_verify, timeout=self._config.timeout | ||
) as client: | ||
url, q = self._build_request( | ||
resource=resource, | ||
query_params=params if params else {}, | ||
) | ||
r: httpx.request = client.get( | ||
url=url, | ||
params=q, | ||
**kwargs, | ||
) | ||
|
||
if r.status_code == 403: | ||
raise OddsApiForbidden("403 Forbidden: Check your API key.") | ||
|
||
if r.status_code == 400: | ||
raise OddsApiForbidden(r.content) | ||
|
||
if self._config.debug: | ||
logging.info(f"API URL: {r.url}") | ||
logging.info(kwargs["headers"]) | ||
|
||
return r.json() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# from data_golf.api.betting import Betting | ||
# from data_golf.api.prediction import Prediction | ||
# from data_golf.config import DGConfig | ||
# from data_golf.http_client import HttpClient | ||
# from data_golf.api.general import General | ||
# from data_golf.api.live_prediction import LivePrediction | ||
from the_odds.http_client import HttpClient | ||
from the_odds.odds_config import OddsConfig | ||
from the_odds.api.v4 import V4 | ||
|
||
|
||
class OddsApiInvalidApiKey(Exception): | ||
pass | ||
|
||
|
||
class OddsApiClient: | ||
def __init__( | ||
self, | ||
api_key: str, | ||
debug: bool = False, | ||
timeout: int = 15, | ||
ssl_verify: bool = True, | ||
) -> None: | ||
self._validate_api_key(api_key) | ||
|
||
self._config = OddsConfig( | ||
api_key=api_key, debug=debug, timeout=timeout, ssl_verify=ssl_verify | ||
) | ||
self._http_client = HttpClient(self._config) | ||
|
||
# Endpoints | ||
# self.general = General(self._http_client) | ||
# self.predictions = Prediction(self._http_client) | ||
# self.live_predictions = LivePrediction(self._http_client) | ||
# self.betting = Betting(self._http_client) | ||
self.v4 = V4(self._http_client) | ||
|
||
def _validate_api_key(self, api_key: str) -> None: | ||
""" | ||
Private method to validate the API key. | ||
:param api_key: | ||
:return: | ||
""" | ||
if not isinstance(api_key, str): | ||
raise OddsApiInvalidApiKey("API key must be a string.") | ||
if not api_key: | ||
raise OddsApiInvalidApiKey("API key cannot be empty.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
class OddsConfig: | ||
def __init__( | ||
self, | ||
api_key: str, | ||
debug: bool = False, | ||
timeout: int = 15, | ||
ssl_verify: bool = True, | ||
) -> None: | ||
self.api_key = api_key | ||
self.debug = debug | ||
self.timeout = timeout | ||
self.ssl_verify = ssl_verify | ||
self.v4_base_url = "https://api.the-odds-api.com/v4" |
Oops, something went wrong.