-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathimfapi3.html
More file actions
462 lines (431 loc) · 28.7 KB
/
imfapi3.html
File metadata and controls
462 lines (431 loc) · 28.7 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IMF API Guide, Part 3 | BD Economics</title>
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
<link rel="stylesheet" href="style.css">
<meta name="description" content="Python tutorial: WEO forecasts, commodity prices, and bulk downloads with requests.">
<meta name="keywords" content="IMF API, sdmx1, SDMX Python, requests, WEO forecasts, commodity prices, bulk download, Economics Dashboard, Macroeconomics Dashboard, International Monetary Fund, Python pandas, economic data API">
<meta name="author" content="Brian Dew">
<link rel="canonical" href="https://bd-econ.com/imfapi3.html">
<!-- Open Graph -->
<meta property="og:title" content="IMF API Guide, Part 3 | BD Economics">
<meta property="og:description" content="Python tutorial: WEO forecasts, commodity prices, and bulk downloads with requests.">
<meta property="og:url" content="https://bd-econ.com/imfapi3.html">
<meta property="og:type" content="article">
<meta property="og:image" content="https://bd-econ.com/images/01_bdlogo.png">
<!-- Twitter Card -->
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="IMF API Guide, Part 3 | BD Economics">
<meta name="twitter:description" content="Python tutorial: WEO forecasts, commodity prices, and bulk downloads with requests.">
<meta name="twitter:image" content="https://bd-econ.com/images/01_bdlogo.png">
<link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="32x32" href="favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="favicon/favicon-16x16.png">
<link rel="manifest" href="favicon/manifest.json">
<meta name="theme-color" content="#ffffff">
<script>
(function() {
const saved = localStorage.getItem('theme');
if (saved) {
document.documentElement.setAttribute('data-theme', saved);
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.setAttribute('data-theme', 'dark');
}
})();
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "TechArticle",
"headline": "IMF API Python Tutorial, Part 3",
"description": "Python tutorial: WEO forecasts, commodity prices, and bulk downloads with requests.",
"author": {
"@type": "Person",
"name": "Brian Dew"
},
"publisher": {
"@type": "Organization",
"name": "BD Economics",
"url": "https://bd-econ.com"
},
"mainEntityOfPage": "https://bd-econ.com/imfapi3.html"
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1,
"name": "Guides",
"item": "https://bd-econ.com/python.html"
},
{
"@type": "ListItem",
"position": 2,
"name": "IMF API Guide, Part 1",
"item": "https://bd-econ.com/imfapi1.html"
},
{
"@type": "ListItem",
"position": 3,
"name": "IMF API Guide, Part 3",
"item": "https://bd-econ.com/imfapi3.html"
}
]
}
</script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-PGVF5S620Y"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-PGVF5S620Y');
</script>
</head>
<body class="page-imfapi3">
<a href="#main" class="skip-link">Skip to main content</a>
<header>
<nav aria-label="Main navigation">
<ul class="site-nav" id="menu">
<li class="nav-main"> <a href="index.html"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 139 17" fill="currentColor" class="brand-logo" role="img" aria-label="BD Economics"> <g transform="translate(0,1.5) scale(2.64,2.59)"> <rect x="0" y="0" width="1" height="5"/> <rect x="0" y="4" width="4" height="1"/> <rect x="2" y="2" width="2" height="1"/> <rect x="3" y="2" width="1" height="2"/> <rect x="8" y="0" width="1" height="5"/> <rect x="5" y="4" width="4" height="1"/> <rect x="5" y="2" width="2" height="1"/> <rect x="5" y="2" width="1" height="2"/> </g> <g transform="translate(27.7,15) scale(0.01857,-0.01857)"> <path transform="translate(0,0)" d="M94 0V700H518V622H178V390H512V312H178V78H524V0Z"/> <path transform="translate(672,0)" d="M310 -14Q195 -14 129.5 59.5Q64 133 64 272V428Q64 563 129.5 638.5Q195 714 310 714Q390 714 445.0 680.0Q500 646 528.0 588.5Q556 531 556 460V448H472V460Q471 506 454.5 546.0Q438 586 402.5 611.0Q367 636 310 636Q229 636 188.5 577.0Q148 518 148 422V278Q148 176 188.5 120.0Q229 64 310 64Q367 64 403.0 89.0Q439 114 455.5 154.0Q472 194 472 240V252H556V240Q556 169 528.0 111.5Q500 54 445.0 20.0Q390 -14 310 -14Z"/> <path transform="translate(1344,0)" d="M306 -14Q191 -14 125.5 59.5Q60 133 60 272V428Q60 563 125.5 638.5Q191 714 306 714Q422 714 487.0 638.5Q552 563 552 428V272Q552 133 487.0 59.5Q422 -14 306 -14ZM306 64Q387 64 427.5 120.0Q468 176 468 278V422Q468 518 427.5 577.0Q387 636 306 636Q225 636 184.5 577.0Q144 518 144 422V278Q144 176 184.5 120.0Q225 64 306 64Z"/> <path transform="translate(2016,0)" d="M73 0V700H241L443 36H455V700H539V0H371L169 664H157V0Z"/> <path transform="translate(2688,0)" d="M306 -14Q191 -14 125.5 59.5Q60 133 60 272V428Q60 563 125.5 638.5Q191 714 306 714Q422 714 487.0 638.5Q552 563 552 428V272Q552 133 487.0 59.5Q422 -14 306 -14ZM306 64Q387 64 427.5 120.0Q468 176 468 278V422Q468 518 427.5 577.0Q387 636 306 636Q225 636 184.5 577.0Q144 518 144 422V278Q144 176 184.5 120.0Q225 64 306 64Z"/> <path transform="translate(3360,0)" d="M46 0V700H206L300 36H312L406 700H566V0H488V664H476L382 0H230L136 664H124V0Z"/> <path transform="translate(4032,0)" d="M84 0V78H264V622H84V700H528V622H348V78H528V0Z"/> <path transform="translate(4704,0)" d="M310 -14Q195 -14 129.5 59.5Q64 133 64 272V428Q64 563 129.5 638.5Q195 714 310 714Q390 714 445.0 680.0Q500 646 528.0 588.5Q556 531 556 460V448H472V460Q471 506 454.5 546.0Q438 586 402.5 611.0Q367 636 310 636Q229 636 188.5 577.0Q148 518 148 422V278Q148 176 188.5 120.0Q229 64 310 64Q367 64 403.0 89.0Q439 114 455.5 154.0Q472 194 472 240V252H556V240Q556 169 528.0 111.5Q500 54 445.0 20.0Q390 -14 310 -14Z"/> <path transform="translate(5376,0)" d="M320 -14Q230 -14 169.0 19.5Q108 53 76.5 111.0Q45 169 45 242V272H129V248Q129 157 180.0 110.5Q231 64 320 64Q398 64 437.5 99.0Q477 134 477 190V196Q477 251 436.5 280.0Q396 309 305 322Q200 337 137.5 381.5Q75 426 75 516V528Q75 583 104.5 624.5Q134 666 186.0 690.0Q238 714 306 714Q385 714 440.5 685.0Q496 656 525.5 608.5Q555 561 555 504V462H471V498Q471 544 448.0 574.5Q425 605 387.0 620.5Q349 636 305 636Q267 636 233.5 623.0Q200 610 179.5 585.5Q159 561 159 525V519Q159 461 206.0 434.5Q253 408 347 394Q457 378 509.0 330.0Q561 282 561 202V190Q561 99 499.5 42.5Q438 -14 320 -14Z"/> </g> </svg></a> </li>
<li><a href="about.html">About</a> </li>
<li><a href="https://briandew.wordpress.com" target="_blank" rel="noopener">Blog <svg class="icon icon-external" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 3h6v6M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg><span class="sr-only"> (opens in new tab)</span></a> </li>
<li><a href="python.html" class="active" aria-current="page">Guides <span class="nav-arrow">↓</span></a>
<ul class="hidden">
<li><a href="getstarted.html">Setup</a></li>
<li><a href="imfapi1.html">IMF API</a></li>
<li><a href="blsapi.html">BLS API</a></li>
<li><a href="beaapi.html">BEA API</a></li>
<li><a href="censusapi.html">Census API</a></li>
<li><a href="treasuryapi.html">Treasury API</a></li>
<li><a href="cps.html">CPS Microdata</a></li>
</ul>
</li>
<li>
<a href="reports.html">Reports <span class="nav-arrow">↓</span></a>
<ul class="hidden">
<li><a href="chartbook.html">US Chartbook</a></li>
<li><a href="indicators.html">Economic Indicators</a></li>
<li><a href="gdpm.html">Monthly GDP</a></li>
<li><a href="imfweo.html">IMF WEO</a></li>
<li><a href="calendar.html">Release Calendar</a></li>
</ul>
</li>
<li><button class="theme-toggle" onclick="toggleTheme()" aria-label="Toggle dark mode"><span id="theme-icon"><svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/></svg></span></button></li>
<li class="icon">
<button type="button" onclick="responsiveNav()" aria-label="Toggle navigation menu" aria-expanded="false">☰</button>
</li>
</ul>
</nav>
</header>
<div class="page-strip accent-blue">
<picture><source srcset="images/imfweo_strip.webp" type="image/webp"><img decoding="async" fetchpriority="high" src="images/imfweo_strip.jpg" alt="" aria-hidden="true" class="page-strip-img" width="1600" height="200"></picture>
</div>
<div class="page-title">
<h1>IMF API</h1>
</div><!-- .page-title -->
<main id="main">
<section>
<section class="card-grid">
<a href="imfapi1.html">
<div class="card card-nav card-muted accent-blue">
<div class="card-banner">
<picture><source srcset="images/imf_banner1.webp" type="image/webp"><img loading="lazy" decoding="async" src="images/imf_banner1.png" alt="IMF API tutorial Part 1" width="425" height="68"></picture>
</div>
<div class="card-header">
<h3>Part 1</h3>
</div>
<div class="card-body card-body-fill">
<p>A <strong>basic example</strong> of retrieving CPI inflation data using the sdmx1 library, converting to pandas, and plotting results.</p>
</div>
</div>
</a>
<a href="imfapi2.html">
<div class="card card-nav card-muted accent-blue">
<div class="card-banner">
<picture><source srcset="images/imf_banner.webp" type="image/webp"><img loading="lazy" decoding="async" src="images/imf_banner.png" alt="IMF API tutorial Part 2" width="293" height="68"></picture>
</div>
<div class="card-header">
<h3>Part 2</h3>
</div>
<div class="card-body card-body-fill">
<p>How to <strong>find datasets and parameters</strong> using dataflow and codelist methods, plus <strong>direct API access</strong> with requests.</p>
</div>
</div>
</a>
<a href="imfapi3.html">
<div class="card card-nav accent-blue">
<div class="card-banner">
<picture><source srcset="images/imf_banner2.webp" type="image/webp"><img loading="lazy" decoding="async" src="images/imf_banner2.png" alt="IMF API tutorial Part 3" width="350" height="68"></picture>
</div>
<div class="card-header">
<h3>Part 3</h3>
</div>
<div class="card-body card-body-fill">
<p>Practical examples: <strong>WEO forecasts, commodity prices</strong>, and <strong>bulk downloads</strong> with requests.</p>
</div>
</div>
</a>
</section>
<article class="prose">
<div class="tutorial-meta">
<span>Updated <time datetime="2026-01-11">Jan 2026</time></span>
<span class="meta-sep">·</span>
<span class="trail-badge trail-intermediate">◆ Intermediate</span>
<span class="meta-sep">·</span>
<button class="tutorial-share" title="Copy link" aria-label="Copy link"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg><span class="share-label">Link</span></button>
</div>
<h2>IMF API with Python: Practical Examples</h2>
<p>Parts 1 and 2 covered the basics of retrieving data and discovering datasets. Here we apply both—combining the discovery tools from Part 2 with practical workflows—to work through three examples: economic forecasts, commodity prices, and bulk downloads.</p>
<hr class="section-bar accent-blue">
<h3>Economic Forecasts (WEO)</h3>
<p>The World Economic Outlook (WEO) dataset contains IMF projections for over 40 indicators—GDP, inflation, unemployment, government debt, current account, and more—covering nearly every country. Data includes historical values and forecasts several years forward.</p>
<p>In[1]:</p>
<pre><code class="python">import sdmx
import pandas as pd
import matplotlib.pyplot as plt
import logging
logging.getLogger('sdmx').setLevel(logging.ERROR)
IMF_DATA = sdmx.Client('IMF_DATA')</code></pre>
<p>We can use the discovery methods from Part 2 to explore the WEO dataset and find the right indicator code. Here we look at the dataset's dimensions and search for GDP-related indicators:</p>
<p>In[2]:</p>
<pre><code class="python"># Explore WEO structure (Part 2 techniques)
f = IMF_DATA.dataflow('WEO')
dsd = list(f.structure.values())[0]
print('Dimensions:', [d.id for d in dsd.dimensions.components])
# Search for GDP growth indicators
for name, cl in f.codelist.items():
codes = sdmx.to_pandas(cl)
matches = codes[codes.str.contains('GDP.*constant', case=False)]
if not matches.empty:
print(f'\n{matches}')</code></pre>
<p>Out[2]:</p>
<pre>Dimensions: ['COUNTRY', 'SUBJECT', 'FREQUENCY', 'TIME_PERIOD']
SUBJECT
NGDP_R Gross domestic product, constant prices (National currency)
NGDP_RPCH Gross domestic product, constant prices (Percent change)
Name: ..., dtype: object</pre>
<p>The indicator we want is <code>NGDP_RPCH</code>—annual percent change in real GDP. Let's compare Thailand and Vietnam, two fast-growing Southeast Asian economies:</p>
<p>In[3]:</p>
<pre><code class="python"># Real GDP growth: Thailand vs. Vietnam
key = 'THA+VNM.NGDP_RPCH.A'
data_msg = IMF_DATA.data('WEO', key=key)
df = sdmx.to_pandas(data_msg).reset_index()
df = df.set_index(['TIME_PERIOD', 'COUNTRY'])['value'].unstack()
df.index = pd.to_datetime(df.index, format='%Y')
df = df.sort_index()
df = df.rename(columns={'THA': 'Thailand', 'VNM': 'Vietnam'})</code></pre>
<p>The DataFrame includes both historical values and IMF projections extending several years beyond the present. We can plot them with dashed lines to distinguish forecasts:</p>
<p>In[4]:</p>
<pre><code class="python">fig, ax = plt.subplots()
forecast_start = pd.Timestamp('2025')
for col in df.columns:
hist = df.loc[df.index < forecast_start, col]
proj = df.loc[df.index >= forecast_start, col]
line, = ax.plot(hist.index, hist, linewidth=1.5, label=col)
ax.plot(proj.index, proj, linewidth=1.5,
linestyle='--', color=line.get_color())
ax.axhline(0, color='gray', linewidth=0.5)
ax.set_title('Real GDP Growth (%, annual)')
ax.legend(frameon=False)
ax.set_xlabel('Source: IMF World Economic Outlook')</code></pre>
<p>Out[4]:</p>
<picture><source srcset="images/imf_gdp_growth.webp" type="image/webp"><img decoding="async" src="images/imf_gdp_growth.png" alt="Thailand vs Vietnam GDP Growth from WEO" loading="lazy" width="558" height="443"/></picture>
<p>Vietnam has sustained higher growth rates over most of this period, with both countries hit hard by COVID-19 in 2020–2021. Other popular WEO indicators include <code>PCPIPCH</code> (CPI inflation), <code>LUR</code> (unemployment rate), and <code>GGXWDG_NGDP</code> (government debt as % of GDP).</p>
<p>Note that the SDMX API only serves the <strong>latest WEO edition</strong>. The IMF publishes the WEO twice a year (April and October), but older editions are not available through the API—the dataflow is overwritten each cycle. To access archived WEO vintages (back to 2007), download them from the <a href="https://www.imf.org/en/Publications/SPROLLs/world-economic-outlook-databases">WEO Database page</a> or use a package like <a href="https://pypi.org/project/weo/">weo</a>.</p>
<h4>Distinguishing Forecasts from Actuals</h4>
<p>WEO data mixes historical values and projections, but the API does not flag which is which in the main data response. To find the boundary, request the <code>LATEST_ACTUAL_ANNUAL_DATA</code> attribute. This returns the last year of actual data for each country–indicator pair; any year after that is a forecast.</p>
<p>In[5a]:</p>
<pre><code class="python">import requests
# Request the forecast boundary attribute via SDMX JSON
url = ("https://api.imf.org/external/sdmx/3.0/data/"
"dataflow/IMF.RES/WEO/~/*"
"?attributes=LATEST_ACTUAL_ANNUAL_DATA"
"&detail=serieskeysonly")
resp = requests.get(url, headers={"Accept": "application/json"})
meta = resp.json()
# The attribute is in dimensionGroupAttributes
attrs = meta['dataSets'][0]['dimensionGroupAttributes']
# Each key is "{country_idx}:{indicator_idx}::", value is [[year]]
# Map dimension indices back to codes
dims = meta['structure']['dimensions']['observation']
countries = {str(i): c['id']
for i, c in enumerate(dims[0]['values'])}
indicators = {str(i): ind['id']
for i, ind in enumerate(dims[1]['values'])}
estimates_start = {}
for key, val in attrs.items():
parts = key.split(':')
iso = countries[parts[0]]
ind = indicators[parts[1]]
year_str = val[0][0]
# Handle fiscal year format: "FY2023/24" -> 2023
if year_str.startswith('FY'):
year = int(year_str[2:6])
else:
year = int(year_str)
estimates_start[(iso, ind)] = year
# Example: last actual year for US real GDP growth
print(f"USA NGDP_RPCH: actuals through "
f"{estimates_start[('USA', 'NGDP_RPCH')]}")</code></pre>
<p>Out[5a]:</p>
<pre>USA NGDP_RPCH: actuals through 2024</pre>
<p>With this boundary, you can split any WEO series into historical data and forecasts programmatically—no hard-coding of dates needed. About 19 countries (including India, Egypt, and Ethiopia) use fiscal years in the format <code>FY2023/24</code>; the first year is the conventional cutoff.</p>
<p>To explore how WEO forecasts have evolved across editions, see the <a href="imfweo.html">WEO Forecast Tracker</a>.</p>
<hr class="section-bar accent-blue">
<h3>Commodity Prices (PCPS)</h3>
<p>The Primary Commodity Price System (PCPS) dataset tracks world benchmark prices for over 100 commodities. Let's explore its structure and search for metals:</p>
<p>In[5]:</p>
<pre><code class="python"># Explore PCPS structure
f = IMF_DATA.dataflow('PCPS')
dsd = list(f.structure.values())[0]
print('Dimensions:', [d.id for d in dsd.dimensions.components])
# Search for aluminum and copper
for name, cl in f.codelist.items():
codes = sdmx.to_pandas(cl)
matches = codes[codes.str.contains('Aluminum|Copper', case=False)]
if not matches.empty:
print(f'\n{matches}')</code></pre>
<p>Out[5]:</p>
<pre>Dimensions: ['FREQ', 'REF_AREA', 'COMMODITY', 'UNIT_MEASURE', 'TIME_PERIOD']
COMMODITY
PALUM Aluminum, 99.5% minimum purity, LME spot price, ...
PCOPP Copper, grade A cathode, LME spot price, CIF Eur...
Name: ..., dtype: object</pre>
<p>PCPS reports global benchmark prices—the reference area is <code>W00</code> (world), so there are no country-specific prices. The key places frequency first, then reference area, commodity, and unit:</p>
<p>In[6]:</p>
<pre><code class="python"># Aluminum and copper monthly prices from 2000
key = 'M.W00.PALUM+PCOPP.USD'
data_msg = IMF_DATA.data('PCPS', key=key,
params={'startPeriod': 2000})
df = sdmx.to_pandas(data_msg).reset_index()
df = df.set_index(['TIME_PERIOD', 'COMMODITY'])['value'].unstack()
df.index = pd.to_datetime(df.index)
df = df.sort_index()
df.columns = ['Aluminum ($/mt)', 'Copper ($/mt)']</code></pre>
<p>With two metals on different scales (aluminum ~$2,500/mt, copper ~$9,000/mt), a dual-axis chart shows both clearly:</p>
<p>In[7]:</p>
<pre><code class="python">fig, ax1 = plt.subplots()
ax1.plot(df.index, df['Aluminum ($/mt)'],
color='#7f8c8d', label='Aluminum')
ax1.set_ylabel('Aluminum ($/mt)')
ax2 = ax1.twinx()
ax2.plot(df.index, df['Copper ($/mt)'],
color='#b87333', label='Copper')
ax2.set_ylabel('Copper ($/mt)')
ax1.set_title('Commodity Prices')
ax1.set_xlabel('Source: IMF Primary Commodity Prices (PCPS)')
lines = ax1.lines + ax2.lines
ax1.legend(lines, [l.get_label() for l in lines],
loc='upper left', frameon=False)</code></pre>
<p>Out[7]:</p>
<picture><source srcset="images/imf_commodities.webp" type="image/webp"><img decoding="async" src="images/imf_commodities.png" alt="Aluminum and Copper Commodity Prices" loading="lazy" width="558" height="443"/></picture>
<p>Both metals track global industrial activity, but copper's sharper swings reflect its role as a leading economic indicator. Other key commodity codes include <code>PGOLD</code> (gold), <code>POILAPSP</code> (crude oil), <code>PNGAS</code> (natural gas), and <code>PWHEAMT</code> (wheat). Use the codelist methods from Part 2 to browse the full list.</p>
<hr class="section-bar accent-blue">
<h3>Bulk Download with Requests</h3>
<p>For larger downloads—or if you prefer to skip the sdmx1 dependency—the same API accepts plain HTTP requests. Ask for CSV format and you get a pandas-ready response. As covered in Part 2, the URL follows the pattern <code>https://api.imf.org/external/sdmx/3.0/data/dataflow/{agency}/{dataflow}/{version}/{key}</code>.</p>
<p>Here we download the entire WEO dataset from 2020 onward. The wildcard <code>*</code> in the key position requests all countries and indicators:</p>
<p>In[11]:</p>
<pre><code class="python">import requests
import io
url = ("https://api.imf.org/external/sdmx/3.0/data/"
"dataflow/IMF.RES/WEO/~/*"
"?c[TIME_PERIOD]=ge:2020-01")
resp = requests.get(url, headers={"Accept": "text/csv"})
df = pd.read_csv(io.StringIO(resp.text), low_memory=False)
print(f"{len(df):,} rows, {df['COUNTRY'].nunique()} countries, "
f"{df['INDICATOR'].nunique()} indicators")</code></pre>
<p>Out[11]:</p>
<pre>86,981 rows, 208 countries, 145 indicators</pre>
<p>With the full dataset in memory, filtering is straightforward. For example, G7 real GDP growth:</p>
<p>In[12]:</p>
<pre><code class="python">g7 = ['USA', 'GBR', 'DEU', 'FRA', 'JPN', 'ITA', 'CAN']
gdp = df[df['INDICATOR'] == 'NGDP_RPCH'].copy()
gdp = gdp[gdp['COUNTRY'].isin(g7)]
gdp = gdp.set_index(['TIME_PERIOD', 'COUNTRY'])['OBS_VALUE'].unstack()
gdp.sort_index().round(1)</code></pre>
<p>Out[12]:</p>
<pre>COUNTRY CAN DEU FRA GBR ITA JPN USA
2020 -5.0 -4.1 -7.6 -10.3 -8.9 -4.2 -2.1
2021 6.0 3.9 6.8 8.6 8.9 2.7 6.2
2022 4.2 1.8 2.8 4.8 4.8 1.0 2.5
2023 1.5 -0.9 1.6 0.4 0.7 1.2 2.9
2024 1.6 -0.5 1.1 1.1 0.7 0.1 2.8
2025 1.2 0.2 0.7 1.3 0.5 1.1 2.0
2026 1.5 0.9 0.9 1.3 0.8 0.6 2.1
...</pre>
<p>This approach downloads about 8 MB and takes a few seconds. It is useful when you want many indicators or countries at once, or when you want to avoid installing sdmx1. The same pattern works for other dataflows—swap in <code>IMF.STA/CPI</code> for CPI data or <code>IMF.STA/BOP</code> for balance of payments.</p>
<hr class="section-bar accent-blue">
<h3>Key Concepts</h3>
<ul>
<li>The discovery methods from Part 2—<code>dataflow()</code>, <code>dsd.dimensions</code>, and codelist searches—are essential for working with new datasets</li>
<li>WEO provides IMF forecasts, valuable for projections and scenario analysis</li>
<li>PCPS provides world benchmark commodity prices; the reference area <code>W00</code> covers all series</li>
<li>The sdmx1 library also supports ECB, BIS, OECD, and many other SDMX providers—run <code>sdmx.list_sources()</code> to see all of them</li>
<li>For bulk downloads or to avoid dependencies, the API also accepts plain <code>requests</code> with <code>Accept: text/csv</code>—see Part 2 for the URL pattern and gotchas</li>
<li>Always call <code>.sort_index()</code> after converting the time index—SDMX responses are not guaranteed to be in chronological order</li>
</ul>
<hr class="section-bar accent-blue">
<h3>Additional Resources</h3>
<ul>
<li><a href="https://pypi.org/project/sdmx1/">sdmx1 on PyPI</a> — Installation and basic documentation</li>
<li><a href="https://sdmx1.readthedocs.io/">sdmx1 documentation</a> — Full library reference, including the list of supported providers</li>
<li><a href="https://data.imf.org/">IMF Data Portal</a> — Browse available IMF datasets interactively</li>
</ul>
</article>
<div class="subfooter" data-hub="guides" data-current="imfapi1.html" style="--accent-color: var(--color-card-blue)"></div>
</section>
</main>
<footer>
<div class="footer-sitemap">
<div>
<h4><a href="reports.html">Data</a></h4>
<ul>
<li><a href="chartbook.html">US Chartbook</a></li>
<li><a href="indicators.html">Economic Indicators</a></li>
<li><a href="gdpm.html">Monthly GDP</a></li>
<li><a href="imfweo.html">WEO Forecasts</a></li>
</ul>
</div>
<div>
<h4><a href="python.html">Guides</a></h4>
<ul>
<li><a href="getstarted.html">Setup</a></li>
<li><a href="imfapi1.html">IMF API</a></li>
<li><a href="blsapi.html">BLS API</a></li>
<li><a href="censusapi.html">Census API</a></li>
</ul>
</div>
<div>
<h4><a href="about.html">About</a></h4>
<ul>
<li><a href="about.html">About BD Economics</a></li>
<li><a href="https://briandew.wordpress.com" target="_blank" rel="noopener">Blog</a></li>
<li><a href="https://github.com/bdecon/" target="_blank" rel="noopener">GitHub</a></li>
</ul>
</div>
</div>
<div class="footer-bottom">
<div class="footer-left">
<p><time datetime="2026">2026</time>, by Brian Dew</p>
</div>
<nav class="footer-right" aria-label="Social links">
<a href="https://github.com/bdecon/" aria-label="GitHub"><svg class="icon" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg></a>
<a href="https://www.linkedin.com/in/brian-dew-5788a386/" aria-label="LinkedIn"><svg class="icon" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M0 1.146C0 .513.526 0 1.175 0h13.65C15.474 0 16 .513 16 1.146v13.708c0 .633-.526 1.146-1.175 1.146H1.175C.526 16 0 15.487 0 14.854zm4.943 12.248V6.169H2.542v7.225zm-1.2-8.212c.837 0 1.358-.554 1.358-1.248-.016-.709-.52-1.248-1.342-1.248S1.4 3.226 1.4 3.934c0 .694.521 1.248 1.327 1.248zm4.908 8.212V9.359c0-.216.016-.432.08-.586.173-.431.568-.878 1.232-.878.869 0 1.216.662 1.216 1.634v3.865h2.401V9.25c0-2.22-1.184-3.252-2.764-3.252-1.274 0-1.845.7-2.165 1.193v.025h-.016a.3.3 0 0 1 .016-.025V6.169h-2.4c.03.678 0 7.225 0 7.225z"/></svg></a>
<a href="https://twitter.com/bd_econ" aria-label="Twitter"><svg class="icon" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M5.026 15c6.038 0 9.341-5.003 9.341-9.334q.002-.211-.006-.422A6.7 6.7 0 0 0 16 3.542a6.7 6.7 0 0 1-1.889.518 3.3 3.3 0 0 0 1.447-1.817 6.5 6.5 0 0 1-2.087.793A3.286 3.286 0 0 0 7.875 6.03a9.32 9.32 0 0 1-6.767-3.429 3.29 3.29 0 0 0 1.018 4.382A3.3 3.3 0 0 1 .64 6.575v.045a3.29 3.29 0 0 0 2.632 3.218 3.2 3.2 0 0 1-.865.115 3 3 0 0 1-.614-.057 3.28 3.28 0 0 0 3.067 2.277A6.6 6.6 0 0 1 .78 13.58a6 6 0 0 1-.78-.045A9.34 9.34 0 0 0 5.026 15"/></svg></a>
<a href="https://briandew.wordpress.com/" target="_blank" rel="noopener" aria-label="WordPress Blog"><svg class="icon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.469 6.825c.84 1.537 1.318 3.3 1.318 5.175 0 3.979-2.156 7.456-5.363 9.325l3.295-9.527c.615-1.54.82-2.771.82-3.864 0-.405-.026-.78-.07-1.11m-7.981.105c.647-.03 1.232-.105 1.232-.105.582-.075.514-.93-.067-.899 0 0-1.755.135-2.88.135-1.064 0-2.85-.15-2.85-.15-.585-.03-.661.855-.075.885 0 0 .54.061 1.125.09l1.68 4.605-2.37 7.08L5.354 6.9c.649-.03 1.234-.1 1.234-.1.585-.075.516-.93-.065-.896 0 0-1.746.138-2.874.138-.2 0-.438-.008-.69-.015C4.911 3.15 8.235 1.215 12 1.215c2.809 0 5.365 1.072 7.286 2.833-.046-.003-.091-.009-.141-.009-1.06 0-1.812.923-1.812 1.914 0 .89.513 1.643 1.06 2.531.411.72.89 1.643.89 2.977 0 .915-.354 1.994-.821 3.479l-1.075 3.585-3.9-11.61.001.014zM12 22.784c-1.059 0-2.081-.153-3.048-.437l3.237-9.406 3.315 9.087c.024.053.05.101.078.149-1.12.393-2.325.609-3.582.609M1.211 12c0-1.564.336-3.05.935-4.39L7.29 21.709C3.694 19.96 1.212 16.271 1.211 12M12 0C5.385 0 0 5.385 0 12s5.385 12 12 12 12-5.385 12-12S18.615 0 12 0"/></svg></a>
</nav>
</div>
</footer>
<script src="scripts/nav.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</body>
</html>