Skip to content

Instantly share code, notes, and snippets.

@tugloo1
Created January 23, 2018 16:56
Show Gist options
  • Save tugloo1/0eaedaba8e552a369e2d03cc95f4a922 to your computer and use it in GitHub Desktop.
Save tugloo1/0eaedaba8e552a369e2d03cc95f4a922 to your computer and use it in GitHub Desktop.
import requests
import pandas as pd
import matplotlib.pyplot as plt
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
def get_request_data(series_id):
r = requests.post(url=url, json={'seriesid': [series_id],
'startyear': '2008',
'endyear': '2017',
'registrationkey': get_bls_key()}).json()
return r['Results']['series'][0]['data']
# Task
coal_series = {'id': 'CEU1021210001',
'name': 'Number of Coal Employees'}
gas_series = {'id': 'CEU1021100001',
'name': 'Number of Gas Employees'}
url = 'https://api.bls.gov/publicAPI/v2/timeseries/data'
coal_data = get_request_data(coal_series['id'])
gas_data = get_request_data(gas_series['id'])
gas_data_frame = pd.DataFrame(gas_data)[::-1]
df = pd.DataFrame(coal_data)
df = df[::-1]
df['date_info'] = pd.to_datetime(df['year'] + ' ' + df['periodName'], format="%Y %B")
df['Number of Coal Employees'] = pd.to_numeric(df['value'])
df['Number of Gas Employees'] = pd.to_numeric(gas_data_frame['value'])
dates = df['date_info']
df.plot(x='date_info', subplots=True)
plt.ylabel("Number of Employees (in thousands)")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment