Skip to content

Instantly share code, notes, and snippets.

@robosoup robosoup/wisdom.py
Last active Nov 10, 2018

Embed
What would you like to do?
Horse Racing and the Wisdom of Crowds
import csv
import os
import urllib.request
from os import listdir
import lxml.html
DOWNLOAD_DIR = 'e:\\prices'
MAX_ODDS = 26
'''
Get a list of all csv files for UK horse racing 'to win' from Betfair.
'''
links = []
with urllib.request.urlopen('https://promo.betfair.com/betfairsp/prices') as response:
dom = lxml.html.fromstring(response.read())
for link in dom.xpath('//a/@href'):
if 'ukwin' in link:
links.append(link)
'''
Download all relevant csv files.
'''
for link in links:
name = link.rsplit('/', 1)[-1]
filename = os.path.join(DOWNLOAD_DIR, name)
url = 'https://promo.betfair.com/betfairsp/prices/' + name
try:
print(url)
with urllib.request.urlopen(url) as response:
with open(filename, mode='wb') as file:
file.write(response.read())
except urllib.request.HTTPError as inst:
print(format(inst))
'''
Define dictionaries.
'''
wins = {}
totals = {}
for i in range(2, MAX_ODDS):
wins[i] = 0
totals[i] = 0
'''
Iterate of each file on count wins.
'''
for filename in listdir(DOWNLOAD_DIR):
header = True
file_path = os.path.join(DOWNLOAD_DIR, filename)
with open(file_path, 'r', encoding='utf-8') as file:
for line in csv.DictReader(file):
if header:
header = False
else:
try:
bsp = float(line['BSP'])
win = line['WIN_LOSE'] == '1'
for i in range(2, MAX_ODDS):
if i + 0.5 >= bsp > i - 0.5:
totals[i] += 1
if win:
wins[i] += 1
except:
continue
'''
Display results.
'''
print("Odds", "Actual", "Perfect")
for i in range(2, MAX_ODDS):
print(i, "{0:.3f}".format(wins[i] / totals[i]), "{0:.3f}".format(1 / i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.