Football Prediction

FREEMIUM
Door boggio | Bijgewerkt il y a 4 jours | Sports
Populariteit

9.8 / 10

Latency

1,299ms

Serviceniveau

100%

Health Check

N/A

Terug naar alle tutorials (1)

Get sorted predictions for tomorrow using Python

Dependencies

The tutorial uses requests and pytz packages that can be installed using the following command

pip install requests pytz

Imports

We first import a couple of build-in and external python libraries that we installed at step.1

from datetime import datetime, timedelta, timezone
import os

import requests
import pytz

Timezone support

The API is based on Europe/London timezone, in order to convert the dates to your local timezone we need to define some conversion functions:

api_tz = pytz.timezone("Europe/London")

local_tz = pytz.timezone("Europe/Rome")

local_tz should be your timezone

def get_current_datetime_on_api_server():
    london_time = datetime.now(tz=timezone.utc).astimezone(api_tz)
    return london_time

def to_local_datetime(start_date):
    dt = datetime.strptime(start_date, "%Y-%m-%dT%H:%M:%S")
    return api_tz.localize(dt).astimezone(local_tz)

Preparing our parameters for making a request

We need to create a environment variable where we will store our Rapid-API key
This can be done using:

  • export RAPIDAPI_KEY="my-secret-api-key" (on unix based systems)
  • setx RAPIDAPI_KEY "my-secret-api-key" on a windows machine
if __name__ == "__main__":
    # this is a datetime object with the timezone used by our api
    current_server_time = get_current_datetime_on_api_server()

    # obtaining the next day as python date object
    tomorrow = current_server_time.date() + timedelta(days=1)

    # setting our API key for auth
    headers = {
        'User-Agent': 'python_requests',
        "X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"],
    }

    session = requests.Session()
    session.headers = headers

    # setting our query params
    params = {
        "iso_date": tomorrow.isoformat(), # python date object should be transformed to ISO format (YYYY-MM-DD)
        "federation": "UEFA",
        "market": "classic"
    }

    prediction_endpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions"

Making the request and checking the results

We will call the prediction endpoint with the parameters defined above.

    response = session.get(prediction_endpoint, params=params)

    if response.ok:
        json = response.json()
        json["data"].sort(key=lambda p: p["start_date"])

We check that the response is valid, and parse the result as json.
We then sort the json response by the start_date of the fixture.

Printing some predictions to the console

We will print just some fields that are available in the prediction endpoint (delimited by tabs):

  • start_time
  • home_team
  • away team
  • prediction
  • predicted odds

Hereโ€™s a dummy example of what our output will look like:

2020-07-31 22:00:00 Home Team vs Away Team X2 @ 1.77

        for match in json["data"]:
            output = "{st}\t{ht} vs {at}\t{p} @ {odd}"

            local_start_time = to_local_datetime(match["start_date"])
            home_team = match["home_team"]
            away_team = match["away_team"]
            prediction = match["prediction"]

            if "odds" in match:
                prediction_odds = match["odds"].get(prediction, None)
            else:
                # user is not able to see odds as it's subscription plan does not support it.
                prediction_odds = None
            print(output.format(st=local_start_time, ht=home_team, at=away_team, p=prediction, odd=prediction_odds))

We also need to take care of requests that are invalid.

    else:
        print("Bad response from server, status-code: {}".format(response.status_code))
        print(response.content)

The API will generally show useful error messages to make it easier to debug issues.

Wrap-up

This is a simple example to get you started, you will find below the whole python script for convenience:

from datetime import datetime, timedelta, timezone
import os

import requests
import pytz


api_tz = pytz.timezone("Europe/London")

local_tz = pytz.timezone("Europe/Rome")


def get_current_datetime_on_api_server():
    london_time = datetime.now(tz=timezone.utc).astimezone(api_tz)
    return london_time


def to_local_datetime(start_date):
    dt = datetime.strptime(start_date, "%Y-%m-%dT%H:%M:%S")
    return api_tz.localize(dt).astimezone(local_tz)


if __name__ == "__main__":
    # this is a datetime object with the timezone used by our api
    current_server_time = get_current_datetime_on_api_server()

    # obtaining the next day as python date object
    tomorrow = current_server_time.date() + timedelta(days=1)

    # setting our API key for auth
    headers = {
        'User-Agent': 'python_requests',
        "X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"],
    }

    session = requests.Session()
    session.headers = headers

    # setting our query params
    params = {
        "iso_date": tomorrow.isoformat(), # python date object should be transformed to ISO format (YYYY-MM-DD)
        "federation": "UEFA",
        "market": "classic"
    }

    prediction_endpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions"
    response = session.get(prediction_endpoint, params=params)

    if response.ok:
        json = response.json()
        json["data"].sort(key=lambda p: p["start_date"])

        for match in json["data"]:
            # going to print tab separated start_time, home_team vs away team, prediction @ predicted odds.
            output = "{st}\t{ht} vs {at}\t{p} @ {odd}"

            local_start_time = to_local_datetime(match["start_date"])
            home_team = match["home_team"]
            away_team = match["away_team"]
            prediction = match["prediction"]

            if "odds" in match:
                prediction_odds = match["odds"].get(prediction, None)
            else:
                # user is not able to see odds as it's subscription plan does not support it.
                prediction_odds = None

            print(output.format(st=local_start_time, ht=home_team, at=away_team, p=prediction, odd=prediction_odds))
    else:
        print("Bad response from server, status-code: {}".format(response.status_code))
        print(response.content)