3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 ptrade 量化交易平台中,get_stock_info 是一个非常常用的 API,用于获取股票、可转债、ETF 等标的的基础信息。以下是关于其返回数据结构及解析方法的详细解答:
get_stock_info(stocks, field=None) 返回的是一个嵌套字典(Nested Dictionary),其类型为 dict[str: dict[str: str, ...], ...]。
'600570.SS')。'stock_name', 'listed_date', 'de_listed_date')。数据结构示例:
{
'600570.SS': {
'stock_name': '恒生电子',
'listed_date': '2003-12-16',
'de_listed_date': '2900-01-01'
},
'600571.SS': {
'stock_name': '信雅达',
'listed_date': '2002-11-01',
'de_listed_date': '2900-01-01'
}
}
注意:如果 field 参数不填或传入 None,内层字典将只返回 'stock_name' 字段。
解析这种嵌套字典的最佳实践是使用 Python 字典的 .get() 方法,这样可以有效避免因股票代码或字段不存在而引发的 KeyError 异常。
如果你只需要查询单只股票,可以直接通过键值访问,或者使用 .get() 增加代码健壮性:
def handle_data(context, data):
security = '600570.SS'
# 获取包含所有字段的信息
stock_info_dict = get_stock_info(security, ['stock_name', 'listed_date', 'de_listed_date'])
# 解析嵌套字典
if security in stock_info_dict:
info = stock_info_dict[security]
stock_name = info.get('stock_name', '未知名称')
listed_date = info.get('listed_date', '未知日期')
log.info(f"股票名称: {stock_name}, 上市日期: {listed_date}")
当传入一个股票列表时,可以通过遍历外层字典的 .items() 来快速解析所有股票的信息:
def handle_data(context, data):
securities = ['600570.SS', '600571.SS']
# 批量获取信息
stock_infos = get_stock_info(securities, ['stock_name', 'listed_date'])
# 遍历解析
for code, info in stock_infos.items():
name = info.get('stock_name')
list_date = info.get('listed_date')
log.info(f"代码: {code}, 名称: {name}, 上市日: {list_date}")
为了在策略中更方便地调用,你可以封装一个辅助函数,专门用于提取特定股票的特定字段:
def get_specific_stock_field(stock_code, field_name):
"""快速获取特定股票的特定字段值"""
info_dict = get_stock_info(stock_code, [field_name])
# 链式使用 .get() 安全提取
return info_dict.get(stock_code, {}).get(field_name, None)
# 使用示例
name = get_specific_stock_field('600570.SS', 'stock_name')
{股票代码: {字段名: 字段值}}。dict.get(key, default) 方法来逐层解析,防止因停牌、退市或代码错误导致的数据缺失引发策略崩溃。