Get sorted predictions for tomorrow

Python

Dependencies

1
pip install requests pytz
Copied!

Code

1
from datetime import datetime, timedelta, timezone
2
import os
3
4
import requests
5
import pytz
6
7
8
api_tz = pytz.timezone("Europe/London")
9
10
# Change this to your timezone
11
local_tz = pytz.timezone("Europe/Rome")
12
13
14
def get_current_datetime_on_api_server():
15
london_time = datetime.now(tz=timezone.utc).astimezone(api_tz)
16
return london_time
17
18
19
def to_local_datetime(start_date):
20
dt = datetime.strptime(start_date, "%Y-%m-%dT%H:%M:%S")
21
return api_tz.localize(dt).astimezone(local_tz)
22
23
24
if __name__ == "__main__":
25
# this is a datetime object with the timezone used by our api
26
current_server_time = get_current_datetime_on_api_server()
27
28
# obtaining the next day as python date object
29
tomorrow = current_server_time.date() + timedelta(days=1)
30
31
# setting our API key for auth
32
headers = {
33
'User-Agent': 'python_requests',
34
"X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"],
35
}
36
37
session = requests.Session()
38
session.headers = headers
39
40
# setting our query params
41
params = {
42
"iso_date": tomorrow.isoformat(), # python date object should be transformed to ISO format (YYYY-MM-DD)
43
"federation": "UEFA",
44
"market": "classic"
45
}
46
47
prediction_endpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions"
48
response = session.get(prediction_endpoint, params=params)
49
50
if response.ok:
51
json = response.json()
52
json["data"].sort(key=lambda p: p["start_date"])
53
54
for match in json["data"]:
55
# going to print tab separated start_time, home_team vs away team, prediction @ predicted odds.
56
output = "{st}\t{ht} vs {at}\t{p} @ {odd}"
57
58
local_start_time = to_local_datetime(match["start_date"])
59
home_team = match["home_team"]
60
away_team = match["away_team"]
61
prediction = match["prediction"]
62
63
if "odds" in match:
64
prediction_odds = match["odds"].get(prediction, None)
65
else:
66
# user is not able to see odds as it's subscription plan does not support it.
67
prediction_odds = None
68
69
print(output.format(st=local_start_time, ht=home_team, at=away_team, p=prediction, odd=prediction_odds))
70
else:
71
print("Bad response from server, status-code: {}".format(response.status_code))
72
print(response.content)
73
Copied!

Node JS

Dependencies

1
npm install moment-timezone axios
Copied!

Code

1
const moment = require("moment-timezone");
2
const axios = require("axios");
3
4
const API_TZ = "Europe/London";
5
const LOCAL_TZ = "Europe/Rome";
6
7
// read the current time in the API timezone
8
const now = moment.tz(API_TZ);
9
const tomorrow = now.add(1, "days");
10
11
const predictionEndpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions";
12
// setting our API key for auth
13
// this info should be kept out of public git or other versioning software
14
const authHeader = {
15
"X-RapidAPI-Key": process.env.RAPIDAPI_KEY
16
}
17
const params = {
18
iso_date: tomorrow.format("YYYY-MM-DD"), // transforming to ISO format.
19
federation: "UEFA",
20
market: "classic"
21
}
22
23
const opts = {
24
method: "GET",
25
headers: authHeader,
26
params: params
27
}
28
29
axios
30
.get(predictionEndpoint, opts)
31
.then(response => {
32
const json = response.data;
33
34
json.data.sort((a, b) => {
35
// sort ascending by start_date
36
if (a.start_date > b.start_date)
37
return 1;
38
if (a.start_date < b.start_date)
39
return -1;
40
return 0;
41
});
42
43
json.data.forEach(match => {
44
const locStartDate = moment.tz(match.start_date, API_TZ).tz(LOCAL_TZ);
45
let winOdds;
46
47
if (match.odds && match.prediction in match.odds) {
48
winOdds = (
49
match.odds[match.prediction] !== null ?
50
match.odds[match.prediction].toFixed(2)
51
: ""
52
);
53
} else {
54
// Not able to see odds as the subscription plan does not support it.
55
// or current match does not have the odds available for this prediction
56
winOdds = "n/a";
57
}
58
console.log(`${locStartDate}\t${match.home_team} vs ${match.away_team}\t${match.prediction} @ ${winOdds}`)
59
})
60
})
61
.catch(err => {
62
console.log(err.message);
63
});
Copied!

Java

Dependencies

pom.xml
1
<dependency>
2
<groupId>com.mashape.unirest</groupId>
3
<artifactId>unirest-java</artifactId>
4
<version>1.4.9</version>
5
</dependency>
Copied!

Code

1
package Example;
2
3
import com.mashape.unirest.http.*;
4
import org.json.*;
5
import java.time.*;
6
import java.time.format.DateTimeFormatter;
7
import java.util.*;
8
9
10
public class Example {
11
12
private static String API_TZ = "Europe/London";
13
private static String LOCAL_TZ = "Europe/Rome";
14
private static String predictionEndpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions";
15
16
private static String getAuthKey() {
17
return System.getenv("RAPIDAPI_KEY");
18
}
19
20
private static ZonedDateTime getApiTimestamp() {
21
return ZonedDateTime.now(ZoneId.of(API_TZ));
22
}
23
24
private void getPredictions() throws Exception {
25
String tomorrow = getApiTimestamp().plusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
26
System.out.println("Current API_TZ timestamp: " + getApiTimestamp().toString());
27
System.out.println("Tomorrow is: " + tomorrow);
28
29
HttpResponse<JsonNode> response = Unirest
30
.get(predictionEndpoint)
31
.header("X-RapidAPI-Key", getAuthKey())
32
.queryString("federation", "UEFA")
33
.queryString("market", "classic")
34
.queryString("iso_date", tomorrow)
35
.asJson();
36
37
JSONArray jsonArray = response.getBody().getObject().getJSONArray("data");
38
39
if (jsonArray == null) {
40
return;
41
}
42
43
List<JSONObject> jsonAsList = new ArrayList<JSONObject>();
44
for (int i = 0; i < jsonArray.length(); i++)
45
jsonAsList.add(jsonArray.getJSONObject(i));
46
47
jsonAsList.sort(new Comparator<JSONObject>() {
48
@Override
49
public int compare(JSONObject a, JSONObject b) {
50
String st1 = a.getString("start_date");
51
String st2 = b.getString("start_date");
52
return st1.compareTo(st2);
53
}
54
});
55
56
for (JSONObject match : jsonAsList) {
57
58
LocalDateTime dt = LocalDateTime.parse(match.getString("start_date"));
59
ZonedDateTime apiDt = ZonedDateTime.of(dt, ZoneId.of(API_TZ));
60
ZonedDateTime localDt = apiDt.withZoneSameInstant(ZoneId.of(LOCAL_TZ));
61
String homeTeam = match.getString("home_team");
62
String awayTeam = match.getString("away_team");
63
String prediction = match.getString("prediction");
64
JSONObject odds = match.optJSONObject("odds");
65
String winOdds = "n/a";
66
67
System.out.println("LocalDateTime: " + dt + " vs " + localDt);
68
if (odds != null) {
69
// set default odds to 0 in case not found.
70
double optOdds = odds.optDouble(prediction, 0.0);
71
72
// all valid odds are > 1.0, the rest are defaultValue from above
73
if (optOdds > 1.0) {
74
winOdds = String.valueOf(optOdds);
75
}
76
}
77
System.out.println(localDt.toString() + "\t" + homeTeam + " vs " + awayTeam + "\t" + prediction + " @ " + winOdds);
78
}
79
}
80
81
public static void main(String[] args) {
82
Unirest.setTimeouts(10000, 10000);
83
Example client = new Example();
84
85
try {
86
client.getPredictions();
87
} catch (Exception e) {
88
e.printStackTrace();
89
}
90
}
91
}
Copied!
Last modified 2yr ago
Copy link