Getting GDP data
We’ll show two options: World Bank and FRED
World Bank GDP per capita via WB API
API-based, no key needed, works in both R and Python.
- Same data source (World Bank).
- Official packages in Python, R
- No messy HTML scraping.
- Clear structure: select indicator → countries → year → get table.
📈 GDP per capita (constant 2015 US$), code: NY.GDP.PCAP.KD
Python (using wbdata
or pandas-datareader
):
import wbdata
import pandas as pd
from datetime import datetime
# Set countries and indicator
= ['USA', 'HUN', 'DEU']
countries = {'NY.GDP.PCAP.KD': 'GDP_per_capita'}
indicator
# Get data
= wbdata.get_dataframe(indicator, country=countries, data_date=datetime(2021, 1, 1))
df print(df.head())
R (using wbstats
):
install.packages("wbstats")
library(wbstats)
# Set indicator and countries
<- wb(indicator = "NY.GDP.PCAP.KD", country = c("US", "HU", "DE"),
gdp_data startdate = 2021, enddate = 2021)
head(gdp_data)
FRED
FRED (Federal Reserve Economic Data) provides economic time series (e.g. GDP, inflation, interest rates).
- You need an API key, but the process is straightforward
- works in both R and Python with identical logic in both languages: set key → request series → get dataframe.
🔑 Get API Key
- Sign up at https://fred.stlouisfed.org/
- Go to your account settings to get your API key.
- Copy your API key, you’ll need it with code
✅ Example: U.S. GDP per capita (A939RC0Q052SBEA
)
Details at FRED site
Python (using fredapi
)
from fredapi import Fred
= Fred(api_key='your_api_key_here')
fred
# GDP per capita
= fred.get_series('A939RC0Q052SBEA')
gdp_pc print(gdp_pc.tail())
R (using fredr
)
install.packages("fredr")
library(fredr)
fredr_set_key("your_api_key_here")
# GDP per capita
<- fredr(series_id = "A939RC0Q052SBEA")
gdp_pc head(gdp_pc)