3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
多均线发散多头排列(MA Ribbon)是一种经典的技术分析形态,当短期、中期和长期移动平均线按顺序从上至下排列且呈发散状态时,通常意味着标的处于极强的单边上涨趋势中。本文将介绍如何在 ptrade 量化交易平台上实现多均线多头排列的选股与自动交易策略。
MA5 > MA10 > MA20 > MA60。before_trading_start 中进行全市场或指定股票池选股,在 handle_data 盘中根据选股结果进行买入,对不再满足多头排列的持仓标的进行卖出平仓。set_universe(security_list):设置订阅股票池。get_history(count, frequency, field, security_list, fq):获取历史 K 线数据,用于计算 MA5、MA10、MA20、MA60。filter_stock_by_status(stocks, filter_type):过滤 ST、停牌及退市股票。order_target_value(security, value):按目标价值进行下单调仓。def initialize(context):
# 设置参考基准
set_benchmark('000300.SS')
# 设置初始股票池(以沪深300成分股为例)
g.security_pool = get_index_stocks('000300.XBHS')
set_universe(g.security_pool)
# 选定的目标股票列表及最大持仓数量
g.target_stocks = []
g.max_hold_count = 5
def before_trading_start(context, data):
# 1. 过滤 ST、停牌、退市股票
valid_stocks = filter_stock_by_status(g.security_pool, filter_type=["ST", "HALT", "DELISTING"])
# 2. 获取过去 70 天的日线收盘价数据(确保计算 MA60 所需数据充足)
df_close = get_history(70, frequency='1d', field='close', security_list=valid_stocks, fq='pre')
selected = []
for stock in valid_stocks:
try:
# 获取单只股票的收盘价序列
if isinstance(df_close, dict):
prices = df_close[stock]['close']
else:
prices = df_close.query('code in [@stock]')['close']
if len(prices) < 60:
continue
# 计算各周期均线
ma5 = prices[-5:].mean()
ma10 = prices[-10:].mean()
ma20 = prices[-20:].mean()
ma60 = prices[-60:].mean()
# 条件判断:多均线发散多头排列
if ma5 > ma10 and ma10 > ma20 and ma20 > ma60:
selected.append(stock)
except Exception as e:
continue
# 记录选出的目标股票
g.target_stocks = selected[:g.max_hold_count]
log.info("今日筛选出的多头排列股票: %s" % g.target_stocks)
def handle_data(context, data):
# 获取当前持仓
current_positions = list(context.portfolio.positions.keys())
# 1. 卖出不在目标选股池中的股票
for stock in current_positions:
if stock not in g.target_stocks:
order_target_value(stock, 0)
log.info("卖出平仓标的: %s" % stock)
# 2. 买入目标选股池中的股票
if len(g.target_stocks) > 0:
# 平分可用资金
target_value_per_stock = context.portfolio.portfolio_value / g.max_hold_count
for stock in g.target_stocks:
if data[stock]['close'] > 0:
order_target_value(stock, target_value_per_stock)
log.info("买入/调仓标的: %s, 目标市值: %s" % (stock, target_value_per_stock))
order_target_value 传入 limit_price 限制下单价格,避免涨停开盘时高追。get_fundamentals 接口过滤 PE/PB 异常或业绩亏损的股票,增强策略稳定性。get_history 时开启 is_dict=True 提升数据提取效率。