Skip to content

Instantly share code, notes, and snippets.

@theracingapi
Last active February 16, 2023 17:00
Show Gist options
  • Save theracingapi/54c49327e961e6ff84ccf0c33ab5b2f1 to your computer and use it in GitHub Desktop.
Save theracingapi/54c49327e961e6ff84ccf0c33ab5b2f1 to your computer and use it in GitHub Desktop.
Python script to create a CSV report of jockey/trainer analysis for each runner on today's UK racecards (Standard Plan)
import requests
from requests.auth import HTTPBasicAuth
from operator import itemgetter
import csv
from datetime import datetime
import asyncio
import aiohttp
# API credentials
username = "<USERNAME>"
password = "<PASSWORD>"
# Function to return list of jockey trainer analysis api call tasks
def get_jockey_trainer_analysis_tasks(session, jockey_race_rows):
# Initialise tasks as a set to remove duplicate jockey trainer analysis calls
tasks = set()
for j in jockey_race_rows:
# Optionally add params to the analysis calls, e.g params={'going': ['soft']}
# Alternatively pass no params for overall/all time analysis
tasks.add(session.get(f"https://api.theracingapi.com/v1/jockeys/{j['jockey_id']}/analysis/trainers"))
return list(tasks)
# Function to get jockey trainer analysis for each jockey race row
async def get_jockey_trainer_analysis_list(jockey_race_rows):
jockey_trainer_analysis_list = []
auth = aiohttp.BasicAuth(username, password)
async with aiohttp.ClientSession(auth=auth) as session:
tasks = get_jockey_trainer_analysis_tasks(session, jockey_race_rows)
responses = await asyncio.gather(*tasks)
for response in responses:
if "id" in await response.json():
jockey_trainer_analysis_list.append(await response.json())
return jockey_trainer_analysis_list
# Transform racecard data to create rows for each jockeys rides and provide jockey trainer analysis
async def get_jockey_trainer_report(racecards):
# Declare jockey race rows list
jockey_race_rows = []
# Create initial jockey race rows, without analysis
for race in racecards:
for runner in race["runners"]:
jockey_race_row = {}
jockey_race_row["course"] = race["course"]
jockey_race_row["off_time"] = race["off_time"]
jockey_race_row["horse"] = runner["horse"]
jockey_race_row["jockey"] = runner["jockey"]
jockey_race_row["jockey_id"] = runner["jockey_id"]
jockey_race_row["trainer"] = runner["trainer"]
jockey_race_row["trainer_id"] = runner["trainer_id"]
jockey_race_rows.append(jockey_race_row)
# Sort the rows
jockey_race_rows = sorted(jockey_race_rows, key=itemgetter("jockey", "off_time"))
# Get jockey trainer analysis list
jockey_trainer_analysis_list = await get_jockey_trainer_analysis_list(jockey_race_rows)
# Loop over jockey rows and add analysis data
for row in jockey_race_rows:
# Set empty default analysis values
row["rides"] = ""
row["win_%"] = ""
row["1_pl"] = ""
row["a/e"] = ""
# Add jockey trainer analysis fields if data can be found in jockey trainer analysis list
try:
jockey_trainer_analysis_all = next((item for item in jockey_trainer_analysis_list if item["id"] == row["jockey_id"]), None)
if jockey_trainer_analysis_all:
jockey_trainer_analysis = next((item for item in jockey_trainer_analysis_all["trainers"] if item["trainer_id"] == row["trainer_id"]), None)
if jockey_trainer_analysis:
row["rides"] = jockey_trainer_analysis["rides"]
row["win_%"] = str(int(float(jockey_trainer_analysis["win_%"]) * 100)) + "%"
row["1_pl"] = jockey_trainer_analysis["1_pl"]
row["a/e"] = jockey_trainer_analysis["a/e"]
except Exception as e:
print(e)
pass
# Create a csv file containing the jockey trainer analysis data
keys = jockey_race_rows[0].keys()
with open(f"jockey_trainer_report_{datetime.today().strftime('%Y-%m-%d')}.csv", "w", newline="") as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(jockey_race_rows)
if __name__ == '__main__':
# Get todays uk racecards
params = {
"day": "today",
"region_codes": ["gb"]
}
racecards = requests.get("https://api.theracingapi.com/v1/racecards", auth=HTTPBasicAuth(username, password), params=params).json()["racecards"]
# Get jockey trainer analysis report
asyncio.run(get_jockey_trainer_report(racecards))
@theracingapi
Copy link
Author

Sample CSV output:

Screenshot 2023-02-16 at 16 27 59

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment