3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 ptrade 量化交易平台中,可以通过 get_fundamentals 接口获取上市公司的财务基本面数据。若要基于营运能力(如存货周转率 inventory_turnover_rate)进行龙头股票筛选,需要查询 operating_ability 财务数据表。
get_fundamentals 接口支持查询营运能力指标表:
'operating_ability'(营运能力表)'inventory_turnover_rate'(存货周转率)、'accounts_receivables_turnover_rate'(应收账款周转率)、'total_asset_turnover_rate'(总资产周转率)等。'20231231',回测中不传默认取当前回测日日期)。before_trading_start 中获取股票池(如沪深300或全A股)。get_fundamentals 获取股票池中所有标的的 inventory_turnover_rate。handle_data 中进行等权重调仓买入。def initialize(context):
# 设置参考基准
set_benchmark('000300.SS')
# 设定持仓股票数量
g.hold_count = 5
g.target_stocks = []
def before_trading_start(context, data):
# 1. 获取沪深300成分股列表作为选股基础池
stocks = get_index_stocks('000300.XBHS')
# 2. 查询营运能力数据表中的存货周转率指标
df_fundamentals = get_fundamentals(
security=stocks,
table='operating_ability',
fields=['inventory_turnover_rate'],
date=None
)
if df_fundamentals is not None and not df_fundamentals.empty:
# 3. 过滤空值并按存货周转率降序排列
df_clean = df_fundamentals.dropna(subset=['inventory_turnover_rate'])
df_sorted = df_clean.sort_values(by='inventory_turnover_rate', ascending=False)
# 4. 选取存货周转率最高的前 N 只龙头股票
g.target_stocks = list(df_sorted.index[:g.hold_count])
log.info("最新筛选出的营运能力龙头标的: %s" % g.target_stocks)
def handle_data(context, data):
if not g.target_stocks:
return
# 卖出不在目标池中的股票
for stock in list(context.portfolio.positions.keys()):
if stock not in g.target_stocks:
order_target(stock, 0)
log.info("卖出标的: %s" % stock)
# 等权重买入目标标的
position_count = len(g.target_stocks)
if position_count > 0:
target_value = context.portfolio.portfolio_value / position_count
for stock in g.target_stocks:
order_target_value(stock, target_value)
log.info("构建持仓标的: %s,目标金额: %s" % (stock, target_value))
get_fundamentals 接口每秒调用不可超过 100 次,单次最大返回量限制为 50000 条单元格。如果对全市场 A 股进行全量查询,建议结合 time.sleep(1) 或按板块分批获取。date 参数时,系统默认按财报实际发布日期(publ_date)进行匹配,可有效避免数据前瞻偏误。