We'd like to get the latest oil price. We can use Yahoo Finance. There are two ways: get CSV data from download.finance.yahoo.com
or use query.yahooapis.com
to do the same thing but parse it into JSON.
Here is an explanation of the f
parameter.
import requests
symbol = 'CLF17.NYM'
url = "http://download.finance.yahoo.com/d/quotes.csv"
params = {'s': symbol, 'f': 'l1'}
r = requests.get(url, params=params)
try:
print(float(r.text))
except ValueError:
print(r.text)
48.02
# If we get more data, eg f: sl1d1t1 then we can
# import csv
# data = list(csv.reader([r.text]))[0]
# data
Benchmarks that seem to work with this service:
Gas spot prices that work:
Symbols that don't work:
This does more or less the same thing, but we wrap it in another service to get at the JSON. We might do this when things start to get more complicated, like...
symbol = 'BZX16.NYM'
url = "http://download.finance.yahoo.com/d/quotes.csv"
params = {'s': symbol, 'f': 'sl1d1t1'}
r = requests.get(url, params=params)
r.text
'"BZX16.NYM",48.54,"9/7/2016","6:03pm"\n'
We'll use the url that requests
formed, above:
r.url
'http://download.finance.yahoo.com/d/quotes.csv?f=sl1d1t1&s=BZX16.NYM'
query = "select * from csv"
query += " where url='{}' and".format(r.url)
query += " columns='symbol,price,data,time'" # corresponds to f parameter
url = "https://query.yahooapis.com/v1/public/yql"
env = "http://datatables.org/alltableswithkeys.env"
params = {
'q': query,
'format': 'json',
'env': env,
}
r = requests.get(url, params=params)
j = r.json()
j
{'query': {'count': 1, 'created': '2016-09-07T22:30:39Z', 'lang': 'en-US', 'results': {'row': {'data': '9/7/2016', 'price': '48.54', 'symbol': 'BZX16.NYM', 'time': '6:03pm'}}}}
price = float(j['query']['results']['row']['price'])
price
48.54
What's the symbol? Crude futures symbols are funky, e.g.
The ticker symbols we're passing look like XXMYY.NYM, with components as follows:
XX
— commodity symbol, as above: CL, BB, etc.M
— a month code, symbolizing January to December: [F,G,H,J,K,M,N,Q,U,V,X,Z]
YY
— a two-digit year, like 13..NYM
— the Nymex symbol.import time
def get_symbol(benchmark):
# We compute a time 45 days in the future for a price
future = time.gmtime(time.time() + 45*24*60*60)
month = future.tm_mon
month_codes = ['F', 'G', 'H', 'J', 'K', 'M', 'N', 'Q', 'U', 'V', 'X', 'Z']
month = month_codes[month - 1]
year = str(future.tm_year)[-2:]
symbol = benchmark + month + year + ".NYM"
return symbol
get_symbol('WCC')
'WCCV16.NYM'