aboutsummaryrefslogtreecommitdiffstats
path: root/python/futures.py
blob: d0968d15404e379671e881bf356af98f5de34454 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import json
import datetime
import requests
import sys

ticker = "GE"
monthcodes = ["F", "G", "H", "J", "K", "M", "N", "Q", "U", "V", "X", "Z"]
d = datetime.date.today().day
m = datetime.date.today().month
y = datetime.date.today().year

def nextIMMDates(startdate, length = 8):
    y = startdate.year
    r = []
    for y in range(startdate.year, startdate.year + 10):
        for m in [3, 6, 9, 12]:
            wednesdays = [datetime.date(y, m, i) for i in range(15, 22) \
                              if datetime.date(y, m, i).weekday()==2]
            immdate = wednesdays[0]
            if immdate > startdate:
                r.append(immdate)
                if len(r) == 8:
                    return r


# get next 8 futures maturities
contracts = ["GE" + monthcodes[d.month-1] + str(d.year)[-1:] for d in nextIMMDates(datetime.date.today())]
if sys.version_info >= (3,3):
    ts = int(datetime.date.today().timestamp()*1000)
else:
    ts = datetime.datetime.strftime(datetime.date.today(), '%s') + '000'

uri = "http://www.cmegroup.com/CmeWS/md/MDServer/V1/Venue/G/Exchange/XCME/FOI/FUT/Product/GE?currentTime={0}&contractCDs={1}".format(ts, ",".join(contracts))
r = requests.get(uri)
quotes = json.loads(r.text)

with open("futures-{0}.csv".format(datetime.date.today()), "w") as fh:
    for q in quotes[u'marketDataInfoAsStringList'][u'message']:
        fh.write("{0}, {1}\n".format(q['ticker'], q['tradePrice']))