Skip to content

宏观数据 API 教程 ​

📊 数据是研究的燃料 —— 用程序自动获取宏观数据,让你的分析有"原料"。

🎯 为什么要用 API? ​

痛点API 解决
手动下载太慢自动化拉取
数据容易错统一来源
历史难获取一行代码取 30 年数据
实时性差程序可定时更新
复制粘贴易错一次写好永久用

📊 主要数据源对比 ​

数据源范围费用难度推荐
akshareA 股 / 国内宏观免费⭐⭐⭐⭐⭐⭐
TushareA 股 / 国内宏观积分制⭐⭐⭐⭐⭐⭐
baostockA 股免费⭐⭐⭐⭐⭐⭐
Wind全市场贵⭐⭐⭐⭐⭐(机构)
FRED美国宏观免费⭐⭐⭐⭐⭐⭐
Yahoo Finance全球股市免费⭐⭐⭐⭐⭐⭐
World Bank各国宏观免费⭐⭐⭐⭐⭐
FRED美国 + 全球免费⭐⭐⭐⭐⭐⭐

🇺🇸 FRED(美联储经济数据库) ​

📌 介绍 ​

  • Federal Reserve Economic Data
  • 美国圣路易斯联储维护
  • 80 万+ 时间序列
  • 完全免费
  • 数据权威(美联储官方)

🔧 Python 接入 ​

bash
# 安装
pip install fredapi pandas
python
import pandas as pd
from fredapi import Fred

# 免费 API key(去 https://fred.stlouisfed.org/docs/api/api_key.html 申请)
fred = Fred(api_key='YOUR_API_KEY')

# ====== 获取美国 GDP ======
gdp = fred.get_series('GDP')
print(gdp.tail())
# date
# 2024-01-01    28220.0
# 2024-04-01    28480.0
# 2024-07-01    28700.0
# 2024-10-01    28920.0

# ====== 获取 CPI ======
cpi = fred.get_series('CPIAUCSL')  # 城市消费者 CPI
print(cpi.tail())

# ====== 获取失业率 ======
unrate = fred.get_series('UNRATE')
print(unrate.tail())

# ====== 批量获取 ======
data = {
    'GDP': fred.get_series('GDP'),
    'CPI': fred.get_series('CPIAUCSL'),
    '失业率': fred.get_series('UNRATE'),
    '联邦基金利率': fred.get_series('FEDFUNDS')
}
df = pd.DataFrame(data)
print(df.tail())

📊 常用 FRED 指标 ​

Series ID指标频率
GDP国内生产总值季度
CPIAUCSL城市 CPI月
UNRATE失业率月
FEDFUNDS联邦基金利率月
DGS1010 年期国债收益率日
DGS22 年期国债收益率日
M2SLM2 货币供应月
INDPRO工业生产指数月
RSAFS零售销售月
BAMLH0A0HYM2高收益债利差日
DEXUSEU美元 / 欧元汇率日
DCOILWTICOWTI 原油价格日
GOLDAMGBD228NLBM黄金价格日
VIXCLSVIX 波动率指数日
DAAA穆迪 Aaa 公司债收益率月
T10YIE10 年期通胀预期日

📊 实战案例:美林时钟自动识别 ​

python
import pandas as pd
import numpy as np
from fredapi import Fred

def identify_economic_phase(fred):
    """根据 FRED 数据识别经济周期阶段"""
    
    # 获取关键指标
    gdp_growth = fred.get_series('GDPC1').pct_change(4)  # 实际 GDP 同比
    cpi_yoy = fred.get_series('CPIAUCSL').pct_change(12)  # CPI 同比
    unemp = fred.get_series('UNRATE')
    
    latest_gdp = gdp_growth.iloc[-1]
    latest_cpi = cpi_yoy.iloc[-1]
    latest_unemp = unemp.iloc[-1]
    prev_unemp = unemp.iloc[-2]
    
    # 美林时钟四阶段判断
    growth_rising = latest_gdp > 0
    inflation_high = latest_cpi > 2.5
    unemployment_rising = latest_unemp > prev_unemp
    
    if growth_rising and not inflation_high:
        return "复苏 (Recovery)"
    elif growth_rising and inflation_high:
        return "过热 (Overheat)"
    elif not growth_rising and inflation_high:
        return "滞胀 (Stagflation)"
    else:
        return "衰退 (Recession)"

# 运行
fred = Fred(api_key='YOUR_API_KEY')
phase = identify_economic_phase(fred)
print(f"当前经济周期: {phase}")
# 建议配置:
# 复苏:股票 / 工业 / 可选消费
# 过热:商品 / 能源 / 材料
# 滞胀:现金 / 黄金 / 必需消费
# 衰退:债券 / 公用事业 / 医疗

🇨🇳 Tushare(A股数据) ​

📌 介绍 ​

  • 国内最专业的金融数据 API
  • A 股 / 期货 / 基金 / 港股 全覆盖
  • 积分制:注册送 100 积分,基础数据够用
  • 数据准确度高于 akshare

🔧 安装与注册 ​

bash
# 安装
pip install tushare

# 注册:https://tushare.pro/register
# 获得 token

🔧 Python 接入 ​

python
import tushare as ts

# 初始化(用自己的 token)
pro = ts.pro_api('YOUR_TOKEN')

# ====== 获取股票基本信息 ======
df = pro.stock_basic(
    list_status='L',  # 上市
    fields='ts_code,name,industry,list_date'
)
print(df.head())

# ====== 获取日线行情 ======
df = pro.daily(
    ts_code='000001.SZ',  # 平安银行
    start_date='20240101',
    end_date='20241231'
)
print(df.head())

# ====== 获取财务数据 ======
df = pro.income(
    ts_code='600519.SH',  # 贵州茅台
    period='20241231',
    fields='ts_code,end_date,revenue,n_income'
)
print(df)

# ====== 获取宏观数据 ======
# CPI
df = pro.cn_cpi(
    m='12',  # 月
    fields='month,cpi,ppi'
)

# M2
df = pro.cn_money_supply(
    m='12',
    fields='month,m2,m2_yoy'
)

# GDP
df = pro.cn_gdp(
    q='2024Q4',
    fields='quarter,gdp,gdp_yoy'
)

📊 常用 Tushare 接口 ​

接口用途积分
stock_basic股票基本信息100
daily日线行情100
daily_basic每日指标100
income利润表2000
balancesheet资产负债表2000
cashflow现金流量表2000
dividend分红送股2000
cn_cpi中国 CPI100
cn_money_supply货币供应100
cn_gdp中国 GDP100
index_daily指数日线100
fund_basic基金基本信息100
futures_daily期货日线100
shibor银行间拆借利率100

🇨🇳 akshare(免费 A 股 + 宏观) ​

📌 介绍 ​

  • 完全免费,无注册
  • 数据源丰富(爬虫)
  • 适合学习和个人使用
  • 偶尔数据格式会变(不保证稳定)

🔧 Python 接入 ​

bash
pip install akshare
python
import akshare as ak
import pandas as pd

# ====== A 股股票列表 ======
df = ak.stock_zh_a_spot_em()  # 实时行情
print(df.head())

# ====== 个股历史 K 线 ======
df = ak.stock_zh_a_hist(
    symbol='600519',  # 茅台
    period='daily',
    start_date='20240101',
    end_date='20241231',
    adjust='qfq'  # 前复权
)
print(df.head())

# ====== 指数行情 ======
df = ak.stock_zh_index_daily(symbol='sh000300')  # 沪深 300
print(df.head())

# ====== 宏观数据 ======
# CPI
df = ak.macro_china_cpi()
# PPI
df = ak.macro_china_ppi()
# GDP
df = ak.macro_china_gdp()
# M2
df = ak.macro_china_money_supply()
# PMI
df = ak.macro_china_pmi()
# LPR
df = ak.macro_china_lpr()

# ====== 基金 ======
df = ak.fund_open_fund_info_em(symbol='000001', indicator='单位净值走势')
print(df.head())

📊 akshare 数据分类 ​

类别函数说明
A 股行情stock_zh_a_*K 线、实时行情
港股行情stock_hk_*港股实时
美股行情stock_us_*美股实时
期货futures_*期货数据
基金fund_*开放式基金
债券bond_*国债、地方债
外汇currency_*汇率
黄金futures_foreign_*黄金、白银
宏观macro_china_*CPI/GDP/PMI 等
美联储macro_usa_*美国宏观

🌍 Yahoo Finance(全球股市) ​

📌 介绍 ​

  • 全球最全的免费金融数据
  • 股票 / ETF / 指数 / 外汇 / 加密货币
  • API 稳定(10+ 年)

🔧 Python 接入 ​

bash
pip install yfinance
python
import yfinance as yf
import pandas as pd

# ====== 下载美股历史数据 ======
apple = yf.Ticker('AAPL')
df = apple.history(period='1y')
print(df.head())

# ====== 下载多只股票 ======
tickers = yf.Tickers('AAPL MSFT GOOGL NVDA')
df = tickers.history(period='1mo')
print(df.head())

# ====== 下载港股 ======
tsla = yf.Ticker('0700.HK')  # 腾讯
df = tsla.history(period='6mo')
print(df.head())

# ====== 下载指数 ======
spx = yf.Ticker('^SPX')  # 标普 500
df = spx.history(period='1y')
print(df.head())

# ====== 实时报价 ======
info = apple.info
print(info['marketCap'])      # 市值
print(info['trailingPE'])      # PE
print(info['dividendYield'])   # 股息率

# ====== 财务数据 ======
df = apple.financials  # 利润表
print(df)

# ====== 财报日期 ======
cal = apple.calendar
print(cal)

📊 常用 Yahoo Finance 代码 ​

代码类型说明
AAPL股票苹果
MSFT股票微软
^SPX指数标普 500
^DJI指数道琼斯
^IXIC指数纳斯达克综合
^VIX指数波动率指数
0700.HK港股腾讯
9988.HK港股阿里
BTC-USD加密比特币
GC=F期货黄金
CL=F期货原油
EURUSD=X外汇欧元 / 美元
SPYETF标普 500 ETF
QQQETF纳指 100 ETF

📊 实战项目 ​

项目 1:美林时钟仪表板 ​

python
import pandas as pd
import matplotlib.pyplot as plt
from fredapi import Fred

def build_clock_dashboard():
    fred = Fred(api_key='YOUR_KEY')
    
    # 获取数据
    data = {
        'GDP': fred.get_series('GDPC1').pct_change(4) * 100,
        'CPI': fred.get_series('CPIAUCSL').pct_change(12) * 100,
        '失业率': fred.get_series('UNRATE'),
        '10Y国债': fred.get_series('DGS10'),
    }
    df = pd.DataFrame(data).dropna()
    latest = df.iloc[-1]
    
    # 打印仪表板
    print('=' * 50)
    print(f'    美林时钟仪表板 - {df.index[-1].date()}')
    print('=' * 50)
    print(f'GDP 同比:        {latest["GDP"]:.2f}%')
    print(f'CPI 同比:        {latest["CPI"]:.2f}%')
    print(f'失业率:          {latest["失业率"]:.2f}%')
    print(f'10Y 国债:        {latest["10Y国债"]:.2f}%')
    print('-' * 50)
    
    # 阶段判断
    if latest['GDP'] > 2 and latest['CPI'] < 3:
        phase = '复苏'
        advice = '股票 / 工业 / 可选消费'
    elif latest['GDP'] > 2 and latest['CPI'] > 3:
        phase = '过热'
        advice = '商品 / 能源 / 材料'
    elif latest['GDP'] < 0 and latest['CPI'] > 3:
        phase = '滞胀'
        advice = '现金 / 黄金 / 必需消费'
    else:
        phase = '衰退'
        advice = '债券 / 公用事业 / 医疗'
    
    print(f'当前阶段:        {phase}')
    print(f'配置建议:        {advice}')

build_clock_dashboard()

项目 2:A 股宏观经济仪表板 ​

python
import akshare as ak
import pandas as pd
import matplotlib.pyplot as plt

def build_a_share_dashboard():
    # 获取多个宏观指标
    indicators = {
        'CPI': ak.macro_china_cpi(),
        'PPI': ak.macro_china_ppi(),
        'M2': ak.macro_china_money_supply(),
        'PMI': ak.macro_china_pmi(),
        'GDP': ak.macro_china_gdp()
    }
    
    # 打印最新数据
    for name, df in indicators.items():
        if not df.empty:
            latest = df.iloc[0]
            print(f'{name}: {latest.iloc[1]}')  # 第二列是数值

build_a_share_dashboard()

项目 3:跨市场资产对比 ​

python
import yfinance as yf
import akshare as ak
import pandas as pd
import matplotlib.pyplot as plt

def cross_market_compare():
    # 美股
    sp500 = yf.Ticker('^SPX').history(period='1y')['Close']
    # A 股
    a股 = ak.stock_zh_index_daily(symbol='sh000300').set_index('date')['close']
    
    # 标准化
    sp500_norm = sp500 / sp500.iloc[0] * 100
    a股_norm = a股 / a股.iloc[0] * 100
    
    # 画图
    plt.figure(figsize=(12, 6))
    plt.plot(sp500_norm.index, sp500_norm.values, label='S&P 500')
    plt.plot(a股_norm.index, a股_norm.values, label='沪深 300')
    plt.title('美股 vs A 股 1 年走势')
    plt.legend()
    plt.grid(True)
    plt.show()

cross_market_compare()

🛠️ 工具组合 ​

📌 数据分析流水线 ​

原始数据 (API)
    ↓
清洗 (pandas)
    ↓
可视化 (matplotlib / plotly / seaborn)
    ↓
分析(统计 / 机器学习)
    ↓
报告(Jupyter / Streamlit / Dash)

📌 推荐组合 ​

用途工具
美股数据yfinance + FRED
A 股数据akshare + Tushare
港股数据akshare + 富途 API
宏观数据FRED + akshare + Wind
数据清洗pandas + numpy
可视化matplotlib + plotly
分析scipy + statsmodels
机器学习scikit-learn + PyTorch
报告Jupyter + Streamlit

📌 Jupyter Notebook 模板 ​

python
# Cell 1: 导入库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import akshare as ak
from fredapi import Fred
import yfinance as yf

# Cell 2: 设定主题
plt.style.use('seaborn-v0_8')
plt.rcParams['font.sans-serif'] = ['SimHei']  # 中文
plt.rcParams['axes.unicode_minus'] = False

# Cell 3: 获取数据
# ...

# Cell 4: 分析
# ...

# Cell 5: 可视化
# ...

⚠️ 注意事项 ​

1. 数据限制 ​

  • 频率限制:FRED 120 次/分钟
  • Tushare 积分:高级数据要 2000+ 积分
  • akshare 稳定性:爬虫数据格式会变
  • 延迟:FRED 数据有 1-7 天延迟

2. 数据清洗 ​

  • 缺失值:用 ffill / bfill 填充
  • 异常值:用 3σ 原则过滤
  • 复权:股票数据要复权处理
  • 频率转换:日 / 周 / 月对齐

3. 道德合规 ​

  • 遵守 API 服务条款
  • 不爬取付费内容
  • 数据不用于非法目的
  • 引用时注明数据来源

📖 相关阅读 ​

来源 ​

💡 数据截至 2026-08;具体规则以交易所/监管机构最新公告为准。

本知识库内容仅供学习参考,不构成任何投资建议。
本站总访问量 ... 次 · 访客数 ... 人