3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在量化选股和基本面分析中,公司的财务健康状况是评估其长期投资价值的核心指标之一。**资产负债率(总负债 / 总资产)**是衡量企业财务风险和杠杆水平的重要指标。负债率过高意味着财务风险较大,而资产负债率较低的企业通常具备更强的抗风险能力和稳健的财务结构。
本文将介绍如何在 PTrade 量化交易平台 中使用 get_fundamentals API 获取上市公司资产负债表数据,计算资产负债率,并筛选出低负债的优质股票。
在 PTrade 中,获取财务数据主要通过 get_fundamentals 接口。对于资产负债表(balance_statement),我们可以查询以下关键字段:
total_assets: 资产总计(元)total_liability: 负债合计(元)# 查询指定股票池在指定日期的资产总计与负债合计
stocks = ['600570.SS', '000001.SZ']
fields = ['total_assets', 'total_liability']
# 按日期查询模式(默认返回指定日期前最新发布的财报数据)
df = get_fundamentals(stocks, 'balance_statement', fields, date='20231231')
get_fundamentals 读取资产负债表中的 total_assets 与 total_liability。资产负债率 = total_liability / total_assets。以下为可以在 PTrade 中直接运行的日线/盘前选股策略代码:
import pandas as pd
import numpy as np
def initialize(context):
# 设置参考基准为沪深300
set_benchmark('000300.SS')
# 设置最大持仓股票数量
g.max_stock_count = 10
# 运行定时任务:每天盘前 09:15 执行基本面选股
run_daily(context, fundamental_select, time='09:15')
def before_trading_start(context, data):
g.target_stocks = []
def fundamental_select(context):
# 1. 获取全 A 股股票列表
current_date = context.blotter.current_dt.strftime('%Y%m%d')
all_stocks = get_Ashares(date=current_date)
# 2. 过滤 ST、停牌及退市股票
filtered_stocks = filter_stock_by_status(all_stocks, filter_type=["ST", "HALT", "DELISTING"], query_date=current_date)
# 3. 读取资产负债表数据(资产总计、负债合计)
fields = ['total_assets', 'total_liability']
funda_df = get_fundamentals(filtered_stocks, 'balance_statement', fields=fields, date=current_date)
if funda_df is None or funda_df.empty:
log.warning("未获取到财务数据")
return
# 4. 清理无效数据并计算资产负债率
funda_df = funda_df.dropna(subset=['total_assets', 'total_liability'])
# 过滤掉总资产小于等于0的异常数据
funda_df = funda_df[funda_df['total_assets'] > 0]
funda_df['debt_asset_ratio'] = funda_df['total_liability'] / funda_df['total_assets']
# 5. 设定筛选条件:资产负债率低于 40%(0.4)
low_debt_stocks = funda_df[funda_df['debt_asset_ratio'] < 0.4]
# 6. 按资产负债率升序排序,选取负债率最低的前 N 只股票
selected_df = low_debt_stocks.sort_values(by='debt_asset_ratio', ascending=True)
g.target_stocks = selected_df.index.tolist()[:g.max_stock_count]
log.info("筛选出的低负债优质股票列表: %s" % g.target_stocks)
# 更新交易股票池
set_universe(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(context.portfolio.positions)
if position_count < g.max_stock_count:
available_cash = context.portfolio.cash
value_per_stock = available_cash / (g.max_stock_count - position_count)
for stock in g.target_stocks:
if get_position(stock).amount == 0:
order_value(stock, value_per_stock)
log.info("买入低负债优质股: %s, 目标金额: %.2f" % (stock, value_per_stock))
get_industry_stocks 按行业进行分位点筛选,避免选股集中在单一行业。profit_ability 表中的 roe)以及成长能力指标(如 operating_revenue_grow_rate)进行多因子综合打分选股。get_fundamentals 默认根据公告日期(publ_date)过滤,确保回测时不包含未来数据。