Skip to content

Instantly share code, notes, and snippets.

@tugloo1
Created January 19, 2018 04:45
Show Gist options
  • Save tugloo1/a8294fa7d7522bbcf29573b80234b5e2 to your computer and use it in GitHub Desktop.
Save tugloo1/a8294fa7d7522bbcf29573b80234b5e2 to your computer and use it in GitHub Desktop.
Bleh
import arrow
import pprint
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import requests
from matplotlib.axes import Axes
def get_bls_key():
"""
This method will get the BLS API key that is expected in api-key.txt file. That file is in the .gitignore and
each user should have their own API key
:rtype string
"""
with open('api-key.txt', 'r') as api_key_file:
api_key = api_key_file.read()
return api_key
# Task
url = 'https://api.bls.gov/publicAPI/v2/timeseries/data'
api_key = get_bls_key()
date1 = arrow.get(2008, 1, 1)
date2 = arrow.get(2017, 12, 1)
series_id_template = 'CEU{0}{1}'
coal_code = '10212100'
oil_gas_code = '10211000'
starting_json = {'startyear': str(date1.year),
'endyear': str(date2.year),
'registrationkey': api_key}
starting_json['seriesid'] = [series_id_template.format(coal_code, '01')]
coal_request_json = requests.post(url=url, json=starting_json).json()
coal_employees = []
coal_dates = []
for i, coal_data in enumerate(coal_request_json['Results']['series'][0]['data'][::-1]):
coal_dates.append(date1.shift(months=i).datetime)
coal_employees.append(float(coal_data['value']))
starting_json['seriesid'] = [series_id_template.format(oil_gas_code, '01')]
oil_gas_request_json = requests.post(url=url, json=starting_json).json()
gas_employees = []
gas_dates = []
for i, gas_data in enumerate(oil_gas_request_json['Results']['series'][0]['data'][::-1]):
gas_dates.append(date1.shift(months=i).datetime)
gas_employees.append(float(gas_data['value']))
def create_graph(axes, dates, employees_data, title):
"""
:param axes:
:param dates:
:param employees_data:
:param title:
:type axes: Axes
:return:
"""
axes.xaxis.set_major_locator(years)
axes.xaxis.set_major_formatter(yearsFmt)
axes.xaxis.set_minor_locator(months)
axes.set_xlim(date1.datetime, date2.datetime)
axes.format_xdata = mdates.DateFormatter('%Y-%m-%d')
axes.grid(True)
axes.plot(dates, employees_data)
axes.set_title(title)
axes.set_ylabel('Number of employees (in thousands)')
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
fig, (subplot1_axes, subplot2_axes) = plt.subplots(nrows=2, ncols=1)
create_graph(subplot1_axes, coal_dates, coal_employees, 'Number of Coal Employees')
create_graph(subplot2_axes, gas_dates, gas_employees, 'Number of Gas Employees')
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment