-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimfapi1.html
211 lines (192 loc) · 10.2 KB
/
imfapi1.html
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
<!DOCTYPE html>
<html>
<head>
<meta id="meta" name="viewport" content="width=device-width, initial-scale=1.0" />
<title> BD Economics | IMF API Guide, Part 1 </title>
<link rel="stylesheet" href="add-ins/github.css">
<script src="add-ins/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lato:900" rel="stylesheet">
<script src="https://use.fontawesome.com/8f99c5621e.js"></script>
<meta charset="UTF-8">
<meta name="description" content="Tools for Economists">
<meta name="keywords" content="IMF API, Economics Dashboard, Trade Network, Trade Networks, Macroeconomics Dashboard, Macroeconomic Dashboard, Markets Dashboard, Market Dashboard, U.S. Economy, U.S. Economy Dashboard, US economy, US economy dashboard, US economy charts, US economy charts pdf, NetworkX trade, international trade networks, network analysis of trade, International Monetary Fund, IMF Statistics Department, IMF Application Programming Interface, International Monetary Fund Application Programming Interface, International Monetary Fund API">
<meta name="author" content="Brian Dew">
<link rel="apple-touch-icon" sizes="57x57" href="favicon/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="favicon/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="favicon/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="favicon/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="favicon/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="favicon/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="favicon/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="favicon/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="favicon/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="favicon/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="favicon/favicon-16x16.png">
<link rel="manifest" href="favicon/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="favicon/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-2J5HVG07X3"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-2J5HVG07X3');
</script>
</head>
<body>
<nav>
<ul class="ul_nav" id="menu">
<li class="nav_main"> <a href="index.html">BD Economics</a> </li>
<li><a href="about.html">About</a> </li>
<li><a href="http://briandew.wordpress.com">Blog</a> </li>
<li><a href="python.html" class="active">Tools ↓</a>
<ul class="hidden">
<li><a href="imfapi1.html">IMF API</a></li>
<li><a href="blsapi.html">BLS API</a></li>
<li><a href="cps.html">CPS Microdata</a></li>
</ul>
</li>
<li>
<a href="chartbook.html">Reports ↓</a>
<ul class="hidden">
<li><a href="MacroDash.pdf">U.S. Chartbook (PDF)</a></li>
<li><a href="unemp.html">U.S. Unemployment Map</a></li>
<li><a href="Dash/JPNDash.pdf">Japan Dashboard (PDF)</a></li>
<li><a href="plots.html">Key Indicators</a></li>
</ul>
<li class="icon"> <a href="javascript:void(0);"
style="font-size:15px;" onclick="responsiveNav()">☰</a>
</li>
</ul>
</nav>
<header>
<h3>IMF API</h3>
</header>
<section>
<article class="article_links">
<a href="imfapi1.html">
<div class="card">
<div class="card_head_blue">
<h2>Part 1</h2>
</div>
<div class="card_tail">
<p>A <strong>quick example</strong> of requesting, cleaning up, saving to csv, and then plotting a series from IFS using the API.</p>
</div>
</div>
</a>
<a href="imfapi2.html">
<div class="card_dull">
<div class="card_head_blue">
<h2>Part 2</h2>
</div>
<div class="card_tail">
<p>An example of how to find the <strong>dimensions and codes</strong> which correspond to your data of interest.</p>
</div>
</div>
</a>
<a href="imfapi3.html">
<div class="card_dull">
<div class="card_head_blue">
<h2>Part 3</h2>
</div>
<div class="card_tail">
<p>How to retrieve the <strong>metadata</strong> for your series of interest and how to make more <strong>advanced requests</strong> from the API.</p>
</div>
</div>
</a>
</article>
<article class="article_code">
<h3> IMF API with Python: An example </h3>
<p>The <a href="http://datahelp.imf.org/knowledgebase/articles/630877-data-services">IMF's API</a> allows machine access to macroeconomic data covering more than 180 countries. Using python, it is easy to retrieve data from the API's <a href="http://datahelp.imf.org/knowledgebase/articles/667681-using-json-restful-web-service"> JSON RESTful Web Service</a>.</p>
<p>The example below retrieves monthly (frequency: <code>M</code>) import price index data (indicator: <code>PMP_IX</code>) for the U.K. (reference area: <code>GB</code>), from the International Financial Statistics (<code>IFS</code>) series. The request returns the base year of the index (the year in which values are indexed to 100), the observation values, and the time period for each value, in this case the year and month. The request is generated by combining the base url of the IMF API, the <code>CompactData</code> method, and the specific code for the series and each dimension of its data. Part 2 covers how to obtain codes and dimension information.</p>
<p>In[1]:</p>
<pre><code class="python">import requests # Python 3.6
url = 'http://dataservices.imf.org/REST/SDMX_JSON.svc/'
key = 'CompactData/IFS/M.GB.PMP_IX' # adjust codes here
# Navigate to series in API-returned JSON data
data = (requests.get(f'{url}{key}').json()
['CompactData']['DataSet']['Series'])
print(data['Obs'][-1]) # Print latest observation</code></pre>
<p>Out[1]:</p>
<pre> {'@TIME_PERIOD': '2018-03', '@OBS_VALUE': '108.904109589041'}</pre>
<h3> Pandas to clean the data and save to csv </h3>
<p>Next, we'll use pandas to clean up the data obtained above, save it as a csv file, and produce a simple line plot.</p>
<p>In[2]:</p>
<pre><code class="python">import pandas as pd # pandas version 0.23
baseyr = data['@BASE_YEAR'] # Save the base year
# Create pandas dataframe from the observations
data_list = [[obs.get('@TIME_PERIOD'), obs.get('@OBS_VALUE')]
for obs in data['Obs']]
df = pd.DataFrame(data_list, columns=['date', 'value'])
df = df.set_index(pd.to_datetime(df['date']))['value'].astype('float')
# Save cleaned dataframe as a csv file
df.to_csv('UK_import_price_index.csv', header=True)</code></pre>
<h3> Simple line plot </h3>
<p>As the last step for this example, we visually inspect the results by producing a line plot.</p>
<p>In[3]:</p>
<pre><code class="python"># Title and text with recent value
title = f'U.K. Import Prices (index, {baseyr})'
recentdt = df.index[-1].strftime('%B %Y')
recentval = round(df[-1], 1)
recent = f'Most recent: {recentdt}: {recentval}'
source = 'Source: IMF IFS'
# Basic plot
plot = df.plot(title=title, colormap='Set1')
plot = plot.set_xlabel(f'{recent}; {source}')</code></pre>
<p>Out[3]:</p>
<img src="https://github.com/bdecon/bdecon.github.io/raw/master/images/UK_MP.png" alt="Pandas Plot Output" style="max-width: 100%;"/>
<h3>Variations: breaking down the request</h3>
<p>The IMF's <code>CompactData</code> method, combined with codes for the series, frequency, area, and indicator, returns a JSON structured dataset. The codes and method are explained in more detail as follows:<p>
<ul>
<li> <p> Method: <code>CompactData</code> retrieves data, <code>DataStructure</code> retrieves series information, and <code>GenericMetadata</code> returns the metadata;</p> </li>
<li> <p> Series: The broad group of indicators, in this case International Financial Statistics <code>IFS</code>;</p> </li>
<li> <p> Frequency: For example monthly <code>M</code>, quarterly <code>Q</code>, or annually <code>A</code>; </p> </li>
<li> <p> Area: The country, region, or set of countries, for example <code>GB</code> for the U.K., or <code>GB+US</code> for the U.K. and the U.S.; </p> </li>
<li> <p> Indicator: The code for the indicator of interest--IFS includes more than 2,500. In the example above, the code of interest is <code>PMP_IX</code>; and </p> </li>
<li> <p> Date Range (Optional): Use this to limit the data range returned, for example <code>?startPeriod=2010&endPeriod=2017</code> otherwise the full set of data is returned. </p> </li>
</ul>
<p>The order in which codes are combined is referred to as the dimensions of the data, in the IFS case: <code>{Method}/{Series}/{Frequency}.{Area}.{Indicator}.{Date Range}</code></p>
<p>Part 2 covers how to use the <code>DataStructure</code> method to obtain the dimensions and codes for any series in the API. Part 3 discusses metadata and more complex requests, and also includes some links to additional references. </p>
</article>
<div class="subfooter">
<a href="imfapi2.html">Next (Part 2) »</a>
</div>
</section>
<footer>
<div class="footer_left">
<p>March 11, 2018<br> by Brian Dew</p>
</div>
<div class="footer_right">
<a href="https://github.com/bdecon/">
<button class="button_sm"><i class="fa fa-github"></i></button>
</a>
<a href="https://www.linkedin.com/in/brian-dew-5788a386/">
<button class="button_sm"><i class="fa fa-linkedin"></i></button>
</a>
<a href="https://twitter.com/bd_econ">
<button class="button_sm"><i class="fa fa-twitter"></i></button>
</a>
<a href="https://briandew.wordpress.com/">
<button class="button_sm"><i class="fa fa-wordpress"></i></button>
</a>
</div>
</footer>
<script>
function responsiveNav() {
var x = document.getElementById("menu");
if (x.className === "ul_nav") {
x.className += " responsive";
} else {
x.className = "ul_nav";
}
}
</script>
</body>
</html>