问题描述
解决方案
在 JoinQuant 聚宽平台中,获取所有 ETF 基金代码列表主要使用 get_all_securities 函数,并将 types 参数设置为 ['etf']。
以下是具体的代码实现和说明:
获取 ETF 代码列表的方法
使用 get_all_securities(types=['etf'], date=None) 函数。
- types=['etf']: 指定只获取 ETF 类型的标的。
- date: (可选)指定日期。如果传入日期(如
'2023-10-27'),则只返回该日期当天还在上市的 ETF;如果不传(默认为None),则返回历史上所有存在过的 ETF(包括已退市的)。
代码示例
# -*- coding: utf-8 -*-
from jqdata import *
def initialize(context):
# 1. 获取所有 ETF 基金的详细信息(返回的是一个 DataFrame)
# 如果只想获取当前还在上市的,建议加上 date 参数,例如 date=context.current_dt
etf_df = get_all_securities(types=['etf'], date=context.current_dt)
# 打印 DataFrame 的前几行查看结构
print("ETF 信息表前5行:")
print(etf_df.head())
# 2. 提取 ETF 代码列表 (代码位于 DataFrame 的 index 中)
etf_codes = list(etf_df.index)
print(f"获取到的 ETF 数量: {len(etf_codes)}")
print("部分 ETF 代码示例:", etf_codes[:5])
# 3. (可选) 如果需要同时获取 ETF 和 LOF
# fund_df = get_all_securities(types=['etf', 'lof'], date=context.current_dt)
返回数据说明
get_all_securities 返回的是一个 pandas.DataFrame,其索引(Index)即为基金代码(如 510050.XSHG),包含以下列:
- display_name: 中文名称(如“上证50ETF”)
- name: 缩写简称(如“SZ50ETF”)
- start_date: 上市日期
- end_date: 退市日期(如果没有退市则为 2200-01-01)
- type: 类型(此处均为 'etf')
Q&A
Q: 如何获取场内交易的货币基金?
A: 将 types 参数设置为 ['mmf'] 即可获取场内货币基金列表。
Q: get_all_securities 返回的代码包含后缀吗?
A: 是的,返回的代码包含交易所后缀,例如 .XSHG(上交所)或 .XSHE(深交所)。
Q: 如何判断 ETF 是否已退市?
A: 查看返回 DataFrame 中的 end_date 字段。如果 end_date 小于当前日期,说明该 ETF 已退市。或者在调用函数时直接传入 date 参数(如当天日期),系统会自动过滤掉该日期已退市的标的。