How to Automate UN Comtrade Data Extraction in Python: A Guide for Trade Analysts & Economics Students
How to Automate UN Comtrade Data Extraction in Python: A Guide for Trade Analysts & Economics Students
For international economics students, trade policy researchers, and market analysts, empirical work often begins with bilateral trade statistics. Whether analyzing trade elasticity, measuring tariff impacts, or calculating export market shares, the primary data source is almost always the United Nations Comtrade Database.
Historically, researchers have relied on the UN Comtrade web interface. However, manual downloads come with severe friction: strict query limits per session, fragmented annual CSV files, inconsistent country coding systems, and multi-header layouts that require tedious un-pivoting in Excel.
By leveraging the official UN Comtrade v1 API in Python, you can replace hours of manual spreadsheet formatting with a clean, reproducible script that pulls multi-year trade matrices directly into a Pandas DataFrame.
Prerequisites & Setup
The United Nations provides an official Python wrapper called comtradeapicall. To install it alongside Pandas, run the following in your terminal:
pip install comtradeapicall pandas
You will also need a free Primary Subscription Key from the UN Comtrade Developer Portal. Register for a free account, navigate to your profile, and copy your primary API key.
The 10-Line Extraction Script
Here is a complete, working Python script to extract annual bilateral merchandise trade flows across multiple years:
import comtradeapicall
import pandas as pd
# 1. Set your UN Comtrade API subscription key
subscription_key = "YOUR_PRIMARY_KEY_HERE"
# 2. Query 5 years of bilateral trade data
# typeCode: 'C' (Commodities) | freqCode: 'A' (Annual) | clCode: 'HS' (Harmonized System)
df = comtradeapicall.getFinalData(
subscription_key,
typeCode='C',
freqCode='A',
clCode='HS',
period='2020,2021,2022,2023,2024',
reporterCode='842', # USA (ISO 3166-1 numeric code)
partnerCode='156', # China
cmdCode='85', # HS Chapter 85 (Electrical machinery & electronics)
flowCode='M,X' # M = Imports, X = Exports
)
# 3. Filter primary trade value and export clean CSV
clean_df = df[['period', 'reporterDesc', 'partnerDesc', 'cmdCode', 'flowDesc', 'primaryValue']]
clean_df.to_csv("bilateral_trade_clean.csv", index=False)
print(f"Extracted {len(clean_df)} records successfully.")
print(clean_df.head())
Understanding the Core API Parameters
| Parameter | Description | Example Values |
|---|---|---|
| typeCode | Trade type: Commodities ('C') or Services ('S') | 'C' |
| freqCode | Frequency: Annual ('A') or Monthly ('M') | 'A' |
| clCode | Classification system (HS, SITC, or BEC) | 'HS' |
| period | Comma-separated list of target years | '2021,2022,2023,2024' |
| reporterCode | Reporting nation's UN numeric country code | '842' (USA), '156' (China) |
| cmdCode | HS commodity heading (2, 4, or 6 digits) | 'TOTAL' or '8517' |
Why Programmatic Extraction Matters
Automating your trade data pipeline solves three major operational issues:
- Eliminates Manual Un-Pivoting: Downloaded portal spreadsheets often mix column totals with raw values. The API returns standardized schema with numeric values ready for statistical modeling.
- Reproducibility: Academic papers and industry reports require transparent methodologies. A Python script allows peers and clients to reproduce your exact dataset with a single command.
- Scalability: You can loop through all 97 HS chapters or an entire trading bloc (e.g., ASEAN, EU, AfCFTA) without clicking through hundreds of web pages.
Follow Automate Trades across our social channels for more practical automation scripts and workflows in international trade and economics.
Comments
Post a Comment