DEV Community

Edward Glush
Edward Glush

Posted on

How to Build a Live Sports Odds Tracker with Python and a Real-Time API

Of course. Here is a complete, ready-to-publish article for dev.to, including the title, introductory text, code, and conclusion.

This is specifically crafted for a technical audience. It provides a real, hands-on project that builds credibility and subtly showcases the complexity that your Bet Better platform handles.

Title: How to Build a Live Sports Odds Tracker with Python and a Real-Time API
Suggested dev.to Tags: #python, #tutorial, #api, #datascience

Sports betting is a massive industry driven by floods of real-time data. For developers, this data represents a fascinating world of APIs, analytics, and engineering challenges.

Ever wondered how you could programmatically access the live betting odds that power this world?

In this tutorial, we'll build a simple but powerful command-line odds tracker using Python. You'll learn how to connect to a real-time API, request data for upcoming games, and parse it to display the latest odds from major bookmakers. By the end, you'll have a working script and a solid foundation for any sports data project.

Let's get started.

Prerequisites
Python 3 installed on your machine.

A code editor like VS Code, Sublime Text, or Vim.

Basic knowledge of the command line.

Step 1: Get Your Free API Key
To get live odds, we need to connect to a sports data API. We'll use The Odds API, which offers a generous free plan that's perfect for projects like this.

Go to The Odds API website and sign up for a free plan.

Once you're signed up, you'll get an API key. This is a unique string that identifies you when you make requests.

Keep your API key handy—we'll need it in our script.

Step 2: Set Up Your Project
Let's get our environment ready. Open your terminal, create a new folder for our project, and install the only library we'll need: requests. This library makes it incredibly simple to send HTTP requests in Python.

mkdir odds-tracker
cd odds-tracker
pip install requests
Enter fullscreen mode Exit fullscreen mode

Now, create a new file in this folder called tracker.py.

Step 3: The Python Code
This is where the magic happens. Open tracker.py and paste the following code. We'll walk through what each part does below.

import requests
import json

# --- CONFIGURATION ---
# Replace with your actual API key
API_KEY = 'YOUR_API_KEY_HERE' 

# The sport you want odds for. For a list of sports, see the API docs.
# e.g., soccer_epl, upcoming, nfl, nba_basketball
SPORT = 'soccer_epl' 

# The region to get odds from (us, uk, eu, au)
REGIONS = 'us'

# The odds format (decimal or american)
ODDS_FORMAT = 'american'

# The markets to get odds for (h2h = Head-to-Head/Moneyline)
MARKETS = 'h2h'

# --- API REQUEST ---

# Build the API URL
api_url = f'https://api.the-odds-api.com/v4/sports/{SPORT}/odds/?apiKey={API_KEY}&regions={REGIONS}&markets={MARKETS}&oddsFormat={ODDS_FORMAT}'

try:
    # Make the GET request
    response = requests.get(api_url)

    # Check for a successful response (status code 200)
    response.raise_for_status() 

    # Parse the JSON response
    odds_data = response.json()
    print(f"Successfully fetched {len(odds_data)} upcoming games.\n")

    # --- PROCESS AND DISPLAY DATA ---

    for game in odds_data:
        home_team = game['home_team']
        away_team = game['away_team']
        commence_time = game['commence_time']

        print(f"--- Game: {home_team} vs. {away_team} ---")
        print(f"Start Time: {commence_time}\n")

        # Find odds from a specific bookmaker (e.g., DraftKings)
        draftkings_odds = None
        for bookmaker in game['bookmakers']:
            if bookmaker['key'] == 'draftkings':
                draftkings_odds = bookmaker['markets'][0]['outcomes']
                break

        if draftkings_odds:
            print("DraftKings Odds:")
            for outcome in draftkings_odds:
                team = outcome['name']
                price = outcome['price']
                print(f"  Team: {team}, Price: {price}")
        else:
            print("Odds from DraftKings not available for this game.")

        print("\n" + "="*40 + "\n")


except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")
except requests.exceptions.RequestException as err:
    print(f"An error occurred: {err}")
except json.JSONDecodeError:
    print("Failed to decode JSON from response.")
except IndexError:
    print("Could not find the expected market data for a game.")
Enter fullscreen mode Exit fullscreen mode

Code Breakdown:
Configuration: We set all our key parameters as variables at the top. This makes it easy to change the sport, region, or market without digging through the code. Remember to replace 'YOUR_API_KEY_HERE' with your actual key!

API Request: We use an f-string to build the full URL for our API request. The requests.get() function sends the request. We wrap this in a try...except block, which is good practice for handling potential network errors or bad responses.

Processing: If the request is successful, we parse the JSON data into a Python dictionary. We then loop through each game in the data.

Displaying: For each game, we print the teams and start time. We then specifically look for odds from "DraftKings" within that game's data. If we find them, we print the moneyline odds for each team. If not, we let the user know.

Step 4: Run Your Tracker!
Save the file and run it from your terminal:

python tracker.py
Enter fullscreen mode Exit fullscreen mode

If everything is correct, you should see a formatted list of upcoming games and their live odds printed to your console.

Example Output:

Successfully fetched 3 upcoming games.

--- Game: Manchester United vs. Arsenal ---
Start Time: 2025-08-16T14:00:00Z

DraftKings Odds:
Team: Arsenal, Price: 150
Team: Manchester United, Price: 180
Team: Draw, Price: 220

========================================

--- Game: Chelsea vs. Manchester City ---
Start Time: 2025-08-16T16:30:00Z

DraftKings Odds:
  Team: Chelsea, Price: 250
  Team: Manchester City, Price: 110
  Team: Draw, Price: 260

========================================
Enter fullscreen mode Exit fullscreen mode

Conclusion and Next Steps
Congratulations! You've just built a functional, live sports odds tracker with Python. You can now pull real-time data for any major sports league and see the lines just like the pros do.

This simple script is just the beginning. From here, a world of more complex and interesting challenges opens up:

How would you store this data to track line movements over time?

How would you compare odds from all bookmakers instantly to find the absolute best price for a bet?

How would you process this data to calculate probabilities and identify market inefficiencies?

Solving these problems is the core of what data-driven sports analytics platforms do at scale. You've taken the first step down a very deep and rewarding rabbit hole.

Happy coding!

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.