3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在股票量化投资中,除了关注盈利能力外,**防范债务风险(避雷)**同样至关重要。上市公司若短期偿债能力不足,易陷入资金链断裂的危机。在 ptrade 量化交易平台 中,我们可以利用 get_fundamentals 接口查询 debt_paying_ability(偿债能力)表,筛选出流动比率与速动比率良好的低风险标的。
在 debt_paying_ability 财务数据表中,重点关注以下两个指标:
current_ratio):流动资产 / 流动负债。通常认为流动比率 $> 1.5$ 或 $> 2$ 时,企业短期偿债安全性较高。quick_ratio):(流动资产 - 存货) / 流动负债。剔除了变现能力较慢的存货,速动比率 $> 1$ 表明企业具备较强的即期偿债能力。使用 get_fundamentals 函数可以轻松获取全市场或指定股票池的财务数据:
# 示例:获取指定股票池在特定日期的流动比率与速动比率
df = get_fundamentals(
security=stocks,
table='debt_paying_ability',
fields=['current_ratio', 'quick_ratio'],
date='20231231'
)
以下策略展示了如何在盘前运行逻辑中,过滤掉偿债能力差的风险股票(流动比率 $< 1.5$ 或速动比率 $< 1.0$),并在安全股票池中执行简单的买入逻辑。
import pandas as pd
def initialize(context):
# 设置参考基准
set_benchmark('000300.SS')
# 设置策略运行周期:每天盘前筛选股票
run_daily(context, filter_risk_stocks, time='09:15')
def filter_risk_stocks(context):
# 1. 获取全市场 A 股代码
all_stocks = get_Ashares()
# 2. 剔除 ST、停牌、退市股票
valid_stocks = filter_stock_by_status(all_stocks, filter_type=["ST", "HALT", "DELISTING"])
# 3. 获取偿债能力财务数据
# 不传 date 默认获取离当前回测/交易时间最近的已发布财报数据
debt_df = get_fundamentals(
security=valid_stocks,
table='debt_paying_ability',
fields=['current_ratio', 'quick_ratio']
)
if debt_df is None or debt_df.empty:
log.warning("未能获取到偿债能力数据")
return
# 4. 设置安全避雷筛选条件:流动比率 > 1.5 且 速动比率 > 1.0
safe_condition = (debt_df['current_ratio'] > 1.5) & (debt_df['quick_ratio'] > 1.0)
safe_stocks = debt_df[safe_condition].index.tolist()
log.info("筛选前股票数量: %d, 偿债能力避雷后安全股票数量: %d" % (len(valid_stocks), len(safe_stocks)))
# 更新全局选股池(取前 20 只作为标的示例)
g.target_stocks = safe_stocks[:20]
set_universe(g.target_stocks)
def handle_data(context, data):
# 简易交易逻辑:均分资金调仓买入安全股票池
if not hasattr(g, 'target_stocks') or not g.target_stocks:
return
# 取得当前的现金
cash = context.portfolio.cash
num_stocks = len(g.target_stocks)
if num_stocks > 0 and cash > 10000:
target_value_per_stock = context.portfolio.portfolio_value / num_stocks
for stock in g.target_stocks:
order_target_value(stock, target_value_per_stock)
ROE(净资产收益率)和 PE_TTM(市盈率)进行二次筛选,构建“高质量+低风险”的价值选股策略。