Created
May 20, 2019 12:18
-
-
Save ranaroussi/638bc231db43ec78a6d79cd691af1721 to your computer and use it in GitHub Desktop.
get active futures contract
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from dateutil.parser import parse as parse_date | |
import datetime | |
import requests | |
import pandas as pd | |
def get_contracts(url): | |
html = requests.get(url, timeout=5) | |
""" CME switched to using ajax """ | |
prodDataUrl = html.text.split('component.baseUrl = "')[1].split(';')[ | |
0].replace('" + ', '').replace(' + "', '').strip('"') | |
# get data | |
url = 'https://www.cmegroup.com%s?tradeDate=%s' % ( | |
prodDataUrl, datetime.datetime.now().strftime('%m/%d/%Y')) | |
data = requests.get(url, timeout=5).json() | |
if len(data['settlements']) == 1: | |
url = 'https://www.cmegroup.com%s?tradeDate=%s' % ( | |
prodDataUrl, parse_date(data['updateTime']).strftime('%m/%d/%Y')) | |
data = requests.get(url, timeout=5).json() | |
df = pd.DataFrame(data['settlements'])[:-1][['month', 'volume']] | |
df.columns = ['expiry', 'volume'] | |
df.volume = pd.to_numeric(df.volume.str.replace(',', '')) | |
df.expiry = df.expiry.str.replace('JLY', 'JUL').apply( | |
lambda ds: parse_date(ds).strftime('%Y%m')) | |
try: | |
df = df.reset_index().drop_duplicates(keep='last') | |
except Exception: | |
df = df.reset_index().drop_duplicates(take_last=True) | |
df.columns = ['contract', 'expiry', 'volume'] | |
df['contract'] = df['contract'].shift(-1).fillna( | |
df['contract'].max()+1).astype(int) | |
return df.dropna() | |
if __name__ == "__main__": | |
url = 'http://www.cmegroup.com/trading/equity-index/us-index/e-mini-sandp500_quotes_settlements_futures.html' | |
contracts = get_contracts(url) | |
active_contract = contracts[:1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment