1. 기존에 한번 다루었던 EIA API를 이용해봤는데 VBA로 했을 때보다 훨씬 빠르고 안정적이다.
당연한 이야기를...
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
40
41
42
43
44
|
import datetime
import time
from tqdm import tqdm
import pandas as pd
import eia
import numpy as np
import xlwings as xw
def retrieve_time_series(api, series_ID):
"""
Return the time series dataframe, based on API and unique Series ID
api: API that we're connected to
series_ID: string. Name of the series that we want to pull from the EIA API
"""
#Retrieve Data By Series ID
series_search = api.data_by_series(series=series_ID)
##Create a pandas dataframe from the retrieved time series
df = pd.DataFrame(series_search)
return df
"""
Execution in main block
"""
#Create EIA API using your specific API key
api_key = '개인이 신청한 API 키'
api = eia.API(api_key)
#Pull the oil WTI price data
series_ID='PET.RWTC.D'
price_df=retrieve_time_series(api, series_ID)
price_df
price_df.reset_index(level=0, inplace=True)
#Rename the columns for easier analysis
price_df.rename(columns={'index':'Date',
price_df.columns[1]:'WTI_Price'},
inplace=True)
#Format the 'Date' column
price_df['Date']=price_df['Date'].astype(str).str[:-3]
#Convert the Date column into a date object
price_df['Date']=pd.to_datetime(price_df['Date'], format='%Y %m%d')
#Subset to only include data going back to 2014
price_df=price_df[(price_df['Date']>='2014-01-01')]
|
cs |
2. EIA API 기본 포맷은 이전에 살펴본 바와 같이 위와 같고. 몇 가지 필요한 데이터를 가져와서 loop로 돌리자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
category = ['재고', '수출입', '생산수요']
category_dic = {'재고':['미원유재고',
'미원유및석유제품재고',
'미휘발유재고',
'미증류연료유재고'],
'수출입':['미원유수입',
'미원유수출'],
'생산수요':['미원유생산',
'미정제처리량',
'미증류연료유수요',
'미휘발유수요']
}
API_key = {'미원유재고':'PET.WCESTUS1.W',
'미원유및석유제품재고':'PET.WTESTUS1.W',
'미휘발유재고': 'PET.WGTSTUS1.W',
'미증류연료유재고':'PET.WDISTUS1.W',
'미원유수입':'PET.WCRIMUS2.W',
'미원유수출':'PET.WCREXUS2.W',
'미원유생산':'PET.WCRFPUS2.W',
'미정제처리량':'PET.WGIRIUS2.W',
'미증류연료유수요':'PET.WDIUPUS2.W',
'미휘발유수요':'PET.WGFUPUS2.W'}
|
cs |
위와 같이 일부 카테코리를 분리해서 API 딕셔너리를 만들면
1
2
3
4
5
6
|
for x, key in tqdm(zip(list(API_key.keys()), API_key)):
temp = globals()['df1_{}'.format(x)] = retrieve_time_series(api, API_key[x])
temp.reset_index(level=0, inplace=True)
temp.rename(columns={'index':'Date'},inplace = True)
temp['Date'] = globals()['df1_{}'.format(x)]['Date'].astype(str).str[:-3]
temp['Date']=pd.to_datetime(temp['Date'], format='%Y %m%d')
|
cs |
위 코드로 필요한 데이터를 가져올 수 있다.
다만
1
2
3
4
5
6
7
8
|
for i in tqdm(category):
time.sleep(0.1)
for x, key in tqdm(zip(list(category_dic[i]), API_key)):
temp = globals()['df_{}'.format(x)] = retrieve_time_series(api, API_key[x])
temp.reset_index(level=0, inplace=True)
temp.rename(columns={'index':'Date'},inplace = True)
temp['Date'] = globals()['df_{}'.format(x)]['Date'].astype(str).str[:-3]
temp['Date'] = pd.to_datetime(temp['Date'], format='%Y %m%d')
|
cs |
코드를 위와 같이 2중 루프로 구성했는데
그 이유는 각 카테고리 시트별로 데이터를 xlwings로 뿌려주기 위함이다.