Visualizing Economic Data with the Bank of Korea API - Easy to Follow with Python

The Bank of Korea API makes it easy to query and visualize economic data, especially when used with Python for data analysis and advanced visualization. In this post Introducing how to use the Bank of Korea Open API and derive insights from data visualization.in more detail below.
What is the Bank of Korea Open API?
The Bank of Korea API is available at A service that makes the Bank of Korea's Economic and Statistical System (ECOS) data easily available to developers and researchers.. The API allows you to use Real-time economic datadirectly. For example, you can easily import and analyze the KRW/dollar exchange rate, KOSPI index, foreign exchange reserves, and more.
How to use the Bank of Korea API
1. sample data lookup (for testing)
Sample data is example data for simple testing without an authentication key. You can use the following URL to view sample data for 10 of the top 100 metrics. Copy the URL below and enter it into your web browser's address bar to see the following.
10 sample data lookup URLs
https://ecos.bok.or.kr/api/KeyStatisticList/sample/xml/kr/1/10
2. Get the top 100 metrics using your authentication key
To view all 100 top metrics data Issue an authentication keyYou should receive
- How the authentication key is issued: Bank of Korea ECOS websiteand click the "Apply for a verification key" to apply for an OpenAPI authentication key. After completing the application, the authentication key will be sent to your email and you can check it in the MyPage menu of the website.
- Example of authentication key usage: If you enter the verified authentication key in the "Auth Key" section of the URL below and check it through a browser, the top 100 stats will appear in xml format as shown below.
https://ecos.bok.or.kr/api/KeyStatisticList/인증키/xml/kr/1/100
Visualize economic data with Python
Now, let's use Python to fetch data from the Bank of Korea API and create a Python visualization as shown in the figure below.

Python code examples
import requests
import pandas as pd
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
Configure # Bank of Korea API URL and authentication key
url = "https://ecos.bok.or.kr/api/KeyStatisticList/MN16GNV2T0LWMVGWNQ9K/xml/kr/1/100"
Call # API and collect data
response = requests.get(url)
data = response.text
Parsing the # XML data and extracting the required data
root = ET.fromstring(data)
rows = []
for row in root.findall("row"):
indicator = row.find("KEYSTAT_NAME").text
if indicator in ["KRW/Dollar exchange rate (closing price)", "Foreign exchange reserves"]:
rows.append({
"indicator": indicator,
"value": float(row.find("DATA_VALUE").text),
"unit": row.find("UNIT_NAME").text,
"date": pd.to_datetime(row.find("CYCLE").text, errors='coerce')
})
Convert to a # dataframe
df = pd.DataFrame(rows)
Convert # Korean → English labels
df['indicator_english'] = df['indicator'].replace({
"KRW/USD Exchange Rate (Closing)": "KRW/USD Exchange Rate",
"Foreign Exchange Reserves": "Foreign Exchange Reserves"
})
Check the # dataframe
print(df)
Visualize using the # dual y-axis
fig, ax1 = plt.subplots(figsize=(10, 6))
# First y-axis: KRW/dollar exchange rate
exchange_rate_data = df[df['indicator'] == "KRW/Dollar exchange rate (closing price)"]
ax1.bar(exchange_rate_data['indicator_english'],
exchange_rate_data['value'],
color='blue', label="KRW/USD Exchange Rate")
ax1.set_xlabel("Indicator")
ax1.set_ylabel("Value (KRW)", color='blue')
ax1.tick_params(axis='y', labelcolor='blue')
# Add a label above the first y-axis bar graph
for i, value in enumerate(exchange_rate_data['value']):
ax1.text(i, value + (value * 0.02), f"{value:,.1f}", ha='center', color='blue')
# Second y-axis: Foreign exchange reserves
ax2 = ax1.twinx()
reserves_data = df[df['indicator'] == "foreign exchange reserves"]
ax2.bar(reserves_data['indicator_english'],
reserves_data['value'],
color='red', label="Foreign Exchange Reserves", alpha=0.7)
ax2.set_ylabel("Value (Thousand USD)", color='red')
ax2.tick_params(axis='y', labelcolor='red')
# Add a label above the second y-axis bar graph
for i, value in enumerate(reserves_data['value']):
ax2.text(i + 1, value + (value * 0.02), f"{value:,.0f}", ha='center', color='red')
# graph title and styling
plt.title(f"Bank of Korea Key Indicators ({df['date'].iloc[0].date()})")
plt.tight_layout()
plt.show()Organize
With the Bank of Korea API, you can easily collect economic data and implement advanced visualizations using Python. In particular, the visualization results can help you understand the flow of the economy more intuitively. Data analysis and visualization can be important tools for economic decision-making, so we encourage you to give it a try.
If you're interested in using other kinds of APIs for Python analytics, check out the Analyzing a 30-day Bitcoin Dollar chart with Python and the CryptoCompare API Check out the post!
#Python visualization code in detail
1. import the library
import requests import pandas as pd import matplotlib.pyplot as plt import xml.etree.ElementTree as ET
- requestsUsed to communicate with the API via HTTP requests.
- pandas: A powerful library for data manipulation and analysis.
- matplotlib.pyplot: A library for data visualization.
- xml.etree.ElementTree: Used to parse XML data.
2. Set the API URL
url = "https://ecos.bok.or.kr/api/KeyStatisticList/MN16GNV2T0LWMVGWNQ9K/xml/kr/1/100"Set the URL for the Bank of Korea API. This URL provides statistical data in XML format.
3. collect data
response = requests.get(url) data = response.text
requests.get(url)to make a GET request to the API and send the response to theresponsein the file.response.textto get XML data as a string.4. Parsing XML data
root = ET.fromstring(data) rows = [] for row in root.findall("row"): indicator = row.find("KEYSTAT_NAME").text if indicator in ["KRW/Dollar exchange rate (closing price)", "Foreign exchange reserves"]: rows.append({ "indicator": indicator, "value": float(row.find("DATA_VALUE").text), "unit": row.find("UNIT_NAME").text, "date": pd.to_datetime(row.find("CYCLE").text, errors='coerce') })
- Parses XML data to create an ElementTree object.
rowsto store the necessary information.- Each
<row>element, repeating the metric name (KEYSTAT_NAME), value (DATA_VALUE), units (UNIT_NAME), date (CYCLE) from the file.- Here, we extract only the "KRW/Dollar rate (closing)" and "FX reserves" and add them to the list.
5. Create a DataFrame
df = pd.DataFrame(rows)Convert the data you collect into a pandas DataFrame for easy manipulation.
6. add an English label
df['indicator_english'] = df['indicator'].replace({ "KRW/USD Exchange Rate (closing)": "KRW/USD Exchange Rate", "Foreign Exchange Reserves": "Foreign Exchange Reserves" })Add a new column to the DataFrame to convert the Korean metric names to English.
7. verify the DataFrame
print(df)Verify the data collected by outputting the contents of the DataFrame to the console.
8. Visualize with dual y-axes
fig, ax1 = plt.subplots(figsize=(10, 6))This is where you create figures and subplots.
ax1is used to plot the first dataset.First Y-axis: Plot the KRW/dollar exchange rate
exchange_rate_data = df[df['indicator'] == "KRW/Dollar exchange rate (closing)"] ax1.bar(exchange_rate_data['indicator_english'], exchange_rate_data['value'], color='blue', label="KRW/USD Exchange Rate")Create a bar chart for the KRW/USD exchange rate using blue bars.
Add a label above the first Y-axis bar graph
for i, value in enumerate(exchange_rate_data['value']): ax1.text(i, value + (value * 0.02), f"{value:,.1f}", ha='center', color='blue')This code displays the corresponding value above each bar.
value + (value * 0.02)is used to position the label slightly above the value.f"{value:,.1f}"separates the value into thousands and displays the value to the first decimal place.Second Y-axis: Plotting foreign exchange reserves
ax2 = ax1.twinx() reserves_data = df[df['indicator'] == "Foreign exchange reserves"] ax2.bar(reserves_data['indicator_english'], reserves_data['value'], color='red', label="Foreign Exchange Reserves", alpha=0.7)Here, we are using the second y-axis (
ax2) to create aax1and share the same x-axis. Draw a bar in red for foreign exchange reserves.Add a label above the second Y-axis bar graph
for i, value in enumerate(reserves_data['value']): ax2.text(i + 1, value + (value * 0.02), f"{value:,.0f}", ha='center', color='red')It also displays that value above the bar on the second y-axis.
i + 1to adjust the position of the foreign exchange reserves,value + (value * 0.02)to adjust the position of the label.Graph titles and styling
plt.title(f"Bank of Korea Key Indicators ({df['date'].iloc[0].date()})") plt.tight_layout() plt.show()Set a title for the graph, adjust the layout, and display the graph.






