【Python量化实战 #09】想配沪深300、中证500?用 Python 一键拉指数与 ETF 数据

发布时间:2026/8/23 9:26:25
【Python量化实战 #09】想配沪深300、中证500?用 Python 一键拉指数与 ETF 数据 系列Python量化实战 · 第 9 篇想配宽基、做指数增强或干脆拿 ETF 当底仓第一步就卡住沪深300、中证500 的代码到底是多少历史行情去哪拉ETF 列表怎么取手点行情软件一个一个查太慢。本文用 Python 把指数列表、指数历史 K 线、ETF/基金列表一次性拉齐并给出一个累计收益计算骨架。本文你将得到什么用index_list / index_history拉指数列表与历史 K 线用etf_list / fund_list取 ETF 与基金列表一套「累计净值」计算骨架pct_change cumprod指数代码体系与股票不同等 3 个避坑点SDKhttps://github.com/MaiRuiApi/mairui运行环境Python 3.11 · pandas 2.0回测/示例区间示意2024-01-01 至 2024-12-31环境准备pipinstallmairui pandasimportosimportpandasaspdfrommairuiimportClient licenceLICENCE-66D8-9F96-0C7F0FBCD073# 演示证书演示证书读者复制即用无需替换指数列表与历史 K 线withClient(licencelicence)asapi:index_list_dfpd.DataFrame(api.index_list()or[])print(index_list_df.head())index_code000300.SH# 请按列表实际代码调整index_barsapi.index_history(index_code,d,st20240101,et20241231,)index_dfpd.DataFrame(index_barsor[])print(index_df.tail())ETF / 基金列表withClient(licencelicence)asapi:etf_dfpd.DataFrame(api.etf_list()or[])fund_dfpd.DataFrame(api.fund_list()or[])print(etf,len(etf_df),fund,len(fund_df))print(etf_df.head())累计收益骨架close_colNonefornamein(c,close,spj):ifnameinindex_df.columns:close_colnamebreakifclose_col:priceindex_df[close_col].astype(float)daily_retprice.pct_change().fillna(0)nav(1daily_ret).cumprod()print(nav_end,float(nav.iloc[-1]))else:print(columns,index_df.columns.tolist())避坑指数代码与股票代码体系不同。ETF 历史行情接口以文档为准可能与股票接口不同。非投资建议。下一篇第 10 篇概念/行业成分股查询与批量拉行情。写在最后本文只做数据接入与代码演示不构成任何投资建议累计收益仅为方法演示不对收益作任何承诺。