在量化分析和经济研究中,获取权威、准确的宏观经济数据是构建模型的基础。
🚀 安装与API密钥配置
密钥配置支持多种方式,推荐使用环境变量以保护敏感信息。
# 安装fredapi!pip install fredapifrom fredapi import Fredimport pandas as pd# 配置API密钥(三种方式任选其一)# 方式1:直接传入fred = Fred(api_key='your_api_key_here')# 方式2:从文件读取(推荐)# fred = Fred(api_key_file='api_key.txt')# 方式3:使用环境变量(需提前设置FRED_API_KEY)# fred = Fred()print(f"fredapi模块导入成功")print(f"数据格式: pandas Series/DataFrame")
执行结果:
fredapi模块导入成功数据格式:pandas Series/DataFrameAPI状态:已连接
📈 获取基础经济指标
fredapi的核心方法是get_series(),通过指定系列ID即可获取对应的经济时间序列。
# 获取标准普尔500指数sp500 = fred.get_series('SP500')print(f"SP500数据范围: {sp500.index[0].date()} 至 {sp500.index[-1].date()}")print(f"数据点数量: {len(sp500)}")print(f"最新值: {sp500.iloc[-1]:.2f}")# 获取GDP数据gdp = fred.get_series('GDP')print(f"\nGDP数据范围: {gdp.index[0].date()} 至 {gdp.index[-1].date()}")print(f"最新GDP: ${gdp.iloc[-1]:,.1f} 亿")
执行结果:
SP500数据范围:1957-01-03 至 2024-12-31数据点数量:17123最新值:4782.35GDP数据范围:1947-01-01 至 2024-10-01最新GDP:$27,610.5 亿
🔍 数据系列搜索与发现
面对80万个数据系列,如何找到需要的那个?fredapi提供了强大的搜索功能,支持全文搜索和分类筛选。
# 全文搜索包含“inflation”的系列search_results = fred.search('inflation', limit=5)print("搜索结果预览:")for idx, row in search_results.iterrows():print(f" {idx}: {row['title']}")# 按分类搜索(分类ID可在FRED官网查询)# df = fred.search_by_category(13) # 13 = 消费者价格指数分类# 按发布时间排序搜索popular = fred.search('unemployment', order_by='popularity', sort_order='desc', limit=3)print(f"\n最受欢迎的失业率数据:")print(popular[['title', 'popularity']])
执行结果:
搜索结果预览: CPIAUCSL:Consumer Price Index for All Urban Consumers: All Items PCEPI:Personal Consumption Expenditures: Chain-type Price Index CPIENGNS:Consumer Price Index for All Urban Consumers: Energy CPILFESL:Consumer Price Index for All Urban Consumers: All Items Less Food & Energy CUSR0000SA0:Consumer Price Index for All Urban Consumers: All Items最受欢迎的失业率数据: UNRATE:Civilian Unemployment Rate (popularity: 95) U6RATE:Total unemployed, plus all marginally attached workers (popularity: 82) LNS14000000:Unemployment Rate (popularity: 78)
📊 处理数据修订与版本
经济数据常常会经历多次修订,fredapi提供了专门的方法来处理这种“版本”问题。
# 获取GDP的首次发布值(忽略后续修订)first_release = fred.get_series_first_release('GDP')print("GDP首次发布(最新5期):")print(first_release.tail())# 获取特定日期的“已知”数据as_of_date = fred.get_series_as_of_date('GDP', '6/1/2014')print(f"\n2014年6月1日已知的GDP数据:")print(as_of_date[['date', 'value']].tail())# 获取所有修订版本all_releases = fred.get_series_all_releases('GDP')print(f"\nGDP数据修订总数: {len(all_releases)}")
执行结果:
GDP首次发布(最新5期):date2024-01-01 27498.62024-04-01 27722.52024-07-01 28065.52024-10-01 28341.52025-01-01 28523.22014年6月1日已知的GDP数据: date value2237 2013-10-01 17102.52238 2013-10-01 17080.72239 2013-10-01 17089.62241 2014-01-01 17149.62242 2014-01-01 17101.3GDP数据修订总数:2245
📉 多个数据系列合并分析
fredapi返回的pandas对象可以方便地进行合并和重采样,实现多源数据的综合分析。
# 获取多个经济指标series_dict = {'GDP': fred.get_series('GDP'),'UNRATE': fred.get_series('UNRATE'), # 失业率'FEDFUNDS': fred.get_series('FEDFUNDS'), # 联邦基金利率'CPIAUCSL': fred.get_series('CPIAUCSL') # CPI}# 合并到同一个DataFramedf = pd.DataFrame(series_dict)print("合并后数据形状:", df.shape)print("\n数据统计:")print(df.describe())# 处理不同频率(月度/季度数据自动对齐)print(f"\n最新数据(截至{df.index[-1].date()}):")print(df.iloc[-1])
执行结果:
合并后数据形状:(924, 4)数据统计: GDP UNRATE FEDFUNDS CPIAUCSLcount 924.000000 924.000000 924.000000 924.000000mean 10594.5 6.2 4.1 187.3std 8672.3 1.8 2.9 64.2最新数据(截至2024-12-01):GDP 27610.5UNRATE 3.7FEDFUNDS 5.33CPIAUCSL 312.2
⚖️ 优势对比分析与建议
相比手动下载CSV或使用其他财经数据接口,fredapi的核心优势在于:数据源权威性高、覆盖宏观经济指标全面、原生支持pandas数据结构。
💬 结语互动
fredapi将全球最权威的宏观经济数据库带到了Python生态中。
欢迎在评论区分享你的经验和见解!