|
| 1 | +import sys |
| 2 | +import argparse |
| 3 | +#This adds the parent directory to the path which includes hw5 |
| 4 | +sys.path.append("../") |
| 5 | +import hw5.hw5 |
| 6 | +import sqlite3 |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +import matplotlib.dates as mdates |
| 9 | +import datetime |
| 10 | + |
| 11 | +#argument parsing setup |
| 12 | +parser = argparse.ArgumentParser(description='intrade election data') |
| 13 | +parser.add_argument('-c',dest='candidate',help='Candidates name default:Obama',default='Obama') |
| 14 | +parser.add_argument('-d',dest='date',help='Date in yyyy-mm-dd format default:2012-03-14',default='2012-03-14') |
| 15 | +parser.add_argument('-r',dest='race',help='race id 1: Republican Nomination 2:Presidential Election 3:Republican VP default:2',default=2) |
| 16 | +parser.add_argument('-p',action='store_true',dest='plot',help='plot results') |
| 17 | +parser.add_argument('-i',action='store_true',dest='init',help='initialize database') |
| 18 | +results = parser.parse_args() |
| 19 | + |
| 20 | +#initializes the database if requested |
| 21 | +if results.init: |
| 22 | + hw5.hw5.initdb() |
| 23 | + |
| 24 | +# select the iformation for the candidate of interest |
| 25 | +connection = sqlite3.connect("elections.db") |
| 26 | +cursor = connection.cursor() |
| 27 | +sql_cmd = """SELECT predictions.date, predictions.price from predictions left join candidates on |
| 28 | + candidates.candidate_id = predictions.candidate_id where predictions.race_id=""" + str(results.race) + """ and |
| 29 | + candidates.name like \"%""" + str(results.candidate) + """%\" ORDER BY predictions.date ASC""" |
| 30 | +cursor.execute(sql_cmd) |
| 31 | +result = cursor.fetchall() |
| 32 | +dprice = [] |
| 33 | +ddates = [] |
| 34 | +total = [] |
| 35 | +finaldates = [] |
| 36 | +for item in result: |
| 37 | + dprice.append(item[1]) |
| 38 | + ddates.append(item[0]) |
| 39 | + #print item[0] |
| 40 | + if item[0] in results.date: |
| 41 | + price = item[1] |
| 42 | + print "Candidate: ", results.candidate, " Date: ", item[0], " probability: ", item[1], "%" |
| 43 | +#sum the probabilities for all shared dates |
| 44 | +if results.plot: |
| 45 | + for index, date in enumerate(ddates): |
| 46 | + total.append(dprice[index]) |
| 47 | + finaldates.append(datetime.datetime.strptime(date,"%Y-%m-%d")) |
| 48 | + #plot the result |
| 49 | + fig = plt.figure() |
| 50 | + ax = fig.add_subplot(111) |
| 51 | + ax.plot(finaldates,total) |
| 52 | + yearsFmt = mdates.DateFormatter('%m-%d-%Y') |
| 53 | + ax.xaxis.set_major_formatter(yearsFmt) |
| 54 | + fig.autofmt_xdate() |
| 55 | + plt.hold(True) |
| 56 | + plt.plot(datetime.datetime.strptime(results.date,"%Y-%m-%d"),price,'ro') |
| 57 | + plt.xlabel("Date") |
| 58 | + plt.ylabel("Probability of winning (%)") |
| 59 | + plt.show() |
0 commit comments