| name | api-data-fetcher |
| description | Fetch economic data from FRED, World Bank, and other APIs |
| workflow_stage | data |
| compatibility | ["claude-code","cursor","codex","gemini-cli"] |
| author | Awesome Econ AI Community |
| version | 1.0.0 |
| tags | ["Python","API","FRED","World-Bank","data-collection"] |
API Data Fetcher
Purpose
This skill helps economists fetch data from major economic data APIs including FRED (Federal Reserve Economic Data), World Bank, IMF, BLS, and OECD. It generates clean, documented Python code with proper error handling.
When to Use
- Downloading macroeconomic indicators
- Building custom datasets from multiple sources
- Automating data updates for ongoing projects
- Fetching cross-country panel data
Instructions
Step 1: Identify Data Requirements
Ask the user:
- What data do you need? (GDP, unemployment, inflation, etc.)
- What time period and frequency?
- What countries/regions?
- Preferred output format? (CSV, DataFrame, etc.)
Step 2: Select Appropriate API
| Data Type | Best Source | Package |
|---|
| US macro | FRED | fredapi |
| Global development | World Bank | wbdata |
| Labor statistics | BLS | bls |
| Cross-country | OECD | pandasdmx |
| Financial | Yahoo Finance | yfinance |
Step 3: Generate Clean Code
Include:
- API key handling (environment variables)
- Error handling for API failures
- Data cleaning and formatting
- Documentation of series definitions
Example Output
"""
Economic Data Fetcher
=====================
Downloads macroeconomic data from FRED and World Bank APIs.
Requires: fredapi, wbdata, pandas
Setup: Set FRED_API_KEY environment variable
Get a free key from: https://fred.stlouisfed.org/docs/api/api_key.html
"""
import os
import pandas as pd
from datetime import datetime, timedelta
from typing import List, Optional, Dict
def fetch_fred_series(
series_ids: List[str],
start_date: str = "2000-01-01",
end_date: Optional[str] = None,
api_key: Optional[str] = None
) -> pd.DataFrame:
"""
Fetch time series data from FRED.
Parameters
----------
series_ids : list of str
FRED series IDs (e.g., ['GDP', 'UNRATE', 'CPIAUCSL'])
start_date : str
Start date in YYYY-MM-DD format
end_date : str, optional
End date (defaults to today)
api_key : str, optional
FRED API key (defaults to FRED_API_KEY env var)
Returns
-------
pd.DataFrame
DataFrame with date index and series as columns
Example
-------
>>> df = fetch_fred_series(['GDP', 'UNRATE'], '2010-01-01')
"""
try:
from fredapi import Fred
except ImportError:
raise ImportError("Install fredapi: pip install fredapi")
api_key = api_key or os.environ.get('FRED_API_KEY')
api_key:
ValueError(
)
fred = Fred(api_key=api_key)
end_date = end_date datetime.now().strftime()
data = {}
series_id series_ids:
:
series = fred.get_series(
series_id,
observation_start=start_date,
observation_end=end_date
)
data[series_id] = series
()
Exception e:
()
df = pd.DataFrame(data)
df.index.name =
df
FRED_SERIES = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
}
() -> pd.DataFrame:
:
wbdata
ImportError:
ImportError()
end_year = end_year datetime.now().year
all_data = []
indicator_code, indicator_name indicators.items():
:
data = wbdata.get_dataframe(
{indicator_code: indicator_name},
country=countries,
)
data = data.reset_index()
all_data.append(data)
()
Exception e:
()
all_data:
df = all_data[]
other_df all_data[:]:
df = df.merge(other_df, on=[, ], how=)
df[] = pd.to_datetime(df[]).dt.year
df = df[(df[] >= start_year) & (df[] <= end_year)]
df
pd.DataFrame()
WORLD_BANK_INDICATORS = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
}
__name__ == :
us_macro = fetch_fred_series(
series_ids=[, , , ],
start_date=
)
()
(us_macro.tail())
us_macro.to_csv()
()
indicators = {
: ,
: ,
:
}
cross_country = fetch_world_bank_data(
indicators=indicators,
countries=[, , , , , , , ],
start_year=
)
()
(cross_country.head())
cross_country.to_csv(, index=)
()
Requirements
Python Packages
pip install fredapi wbdata pandas
API Keys
Set environment variables:
export FRED_API_KEY="your_key_here"
Best Practices
- Store API keys in environment variables - never hardcode
- Add rate limiting for bulk downloads
- Cache data locally to avoid repeated API calls
- Document series definitions from the source
- Check for revisions in real-time data
Common Pitfalls
- ❌ Hardcoding API keys in scripts
- ❌ Not handling API rate limits
- ❌ Ignoring data vintages/revisions
- ❌ Mixing data frequencies without proper handling
References
Changelog
v1.0.0
- Initial release with FRED and World Bank support