Python script - PredictIt API11/3/2022
I wrote a quick Python script to download the latest odds from PredictIt, and then output to an Excel file. I've pasted it below as an extract from a Jupyter notebook:
PredictIt is an online prediction website, mainly focused on Political events: www.predictit.org/ I think it's great that PredictIt allow access like this, before I realised the API exists I was using Selenium to scrape the info through Chrome, which was much slower to run, and also occasionally buggy.
In [ ]:
import pandas as pd
import time
import requests
import json
import xlsxwriter
In [ ]:
#%% predictit API download
# The input file is a csv with a list of PredictIt API pages, one row per page, such as the following:
# https://www.predictit.org/api/marketdata/markets/7198
PredictitDown = pd.read_csv(r"C:\Users\Admin\Documents\Predictit - 2022 03 11.csv")
Rows = PredictitDown [PredictitDown .columns[0]].count()
AllQuestions = []
Allnames = []
Allodds = []
for i in range(Rows):
link = PredictitDown["Market URL"][i]
response = requests.get(link)
PredictitData = json.loads(response.text)
my_list = PredictitData ['contracts']
listnames = []
listodds = []
for item in my_list:
listnames.append(item['name'])
listodds.append(item['bestBuyNoCost'])
AllQuestions.append(PredictitData['name'])
Allnames.append(listnames)
Allodds.append(listodds)
df = pd.DataFrame(AllQuestions)
df2 = pd.DataFrame(Allnames)
df3 = pd.DataFrame(Allodds)
dflist=[df,df2,df3]
Excelwriter = pd.ExcelWriter(r"C:\Users\Admin\Documents\PredictitDownloads\PredictitOutput.xlsx",engine="xlsxwriter")
for i, dataf in enumerate (dflist):
dataf.to_excel(Excelwriter, sheet_name="Sheet" + str(i+1),index=False)
#
Excelwriter.save()
|
AuthorI work as an actuary and underwriter at a global reinsurer in London. Categories
All
Archives
April 2024
|
Leave a Reply.