【Python量化实战 #09】Python获取指数行情与ETF数据:沪深300示例
做指数增强或 ETF 轮动,需要稳定的指数列表与历史行情。本文是「Python量化实战」第 9 篇:index_list / index_history / etf_list 的用法与简单对比框架。
Playground:https://www.mairuiapi.com/playground
指数文档:https://www.mairuiapi.com/hszsdata
环境准备
pip install mairui pandas
GitHub:https://github.com/MaiRuiApi/mairui
指数列表与历史行情
import os
import pandas as pd
from mairui import Client
licence = os.environ.get("MAIRUI_LICENCE", "your_licence")
with Client(licence=licence) as api:
indexes = pd.DataFrame(api.index_list() or [])
print(indexes.head())
# 指数代码以列表/文档为准,例如上证相关代码
idx_code = "000300.SH" # 示例,请按实际列表选择沪深300代码
bars = api.index_history(idx_code, "d", st="20240101", et="20241231")
idx_df = pd.DataFrame(bars or [])
print(idx_df.tail())
ETF 列表
with Client(licence=licence) as api:
etfs = pd.DataFrame(api.etf_list() or [])
funds = pd.DataFrame(api.fund_list() or [])
print("etf", len(etfs), "fund", len(funds))
print(etfs.head())
简单收益对比骨架
# 将收盘价转为日收益,再累计(列名请对齐)
if "c" in idx_df.columns:
px = idx_df["c"].astype(float)
elif "close" in idx_df.columns:
px = idx_df["close"].astype(float)
else:
px = None
print("请先确认收盘价字段", idx_df.columns.tolist())
if px is not None and len(px) > 2:
ret = px.pct_change().fillna(0)
cum = (1 + ret).cumprod()
print("累计净值末值", float(cum.iloc[-1]))
避坑
- 指数代码与股票代码体系不同,勿混用。
- ETF 行情是否与股票同一套历史接口,以文档为准。
- 回测请注明区间,例如 2024-01-01 至 2024-12-31。
下一篇:概念/行业成分股。文档:指数 · Playground
麦蕊智数 · Python量化实战 #09



