3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在量化交易中,传统的简单移动平均线(MA)仅考虑了收盘价,忽略了交易的核心要素——成交量。在“尾盘跌停后择时买入”这类高波动、极端情绪的策略中,使用 VWAP(成交量加权平均价) 和 成交量分布 能够更真实地反映市场资金的实际持仓成本,从而更精准地判断筹码是否沉淀和稳定。
以下将详细介绍如何在聚宽(JoinQuant)平台中计算 T+1 至 T+4 的 VWAP,并结合成交量分布进行筹码稳定性判断,最后给出完整的策略实现代码。
在 T 日尾盘跌停后:
在聚宽中,我们可以通过 get_bars 或 attribute_history 获取高频或日线数据。由于 get_bars 支持直接返回 money(成交额)和 volume(成交量),计算 VWAP 非常方便:
$$\text{VWAP} = \frac{\text{money}}{\text{volume}}$$
import pandas as pd
import numpy as np
def get_period_vwap(security, end_date, count=4):
# 获取 T+1 至 T+4(共4个交易日)的日线数据
bars = get_bars(security, count=count, unit='1d',
fields=['date', 'money', 'volume', 'close'],
include_now=True, end_dt=end_date, fq_ref_date=end_date)
if len(bars) == 0:
return None, None
# 计算 4 日整体 VWAP
total_money = bars['money'].sum()
total_volume = bars['volume'].sum()
period_vwap = total_money / total_volume if total_volume > 0 else None
return period_vwap, bars
以下是一个实用的量化策略示例:在股票跌停后的 T+1 至 T+4 期间,利用 VWAP 和成交量分布进行择时买入。
# 导入聚宽函数库
from jqdata import *
import numpy as np
import pandas as pd
def initialize(context):
# 设定沪深300作为基准
set_benchmark('000300.XSHG')
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 佣金印花税设置
set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
# 股票池:以平安银行为例
g.security = '000001.XSHE'
# 运行控制
run_daily(market_open, time='every_bar')
def market_open(context):
security = g.security
current_data = get_current_data()
# 1. 获取历史数据,判断 T 日是否跌停
# 获取过去5天的数据(包含T日)
hist = attribute_history(security, 5, '1d', ['close', 'low_limit', 'paused'])
if hist.empty or hist['paused'].iloc[-1]:
return
# 假设倒数第5天为 T 日(跌停日)
t_close = hist['close'].iloc[-5]
t_low_limit = hist['low_limit'].iloc[-5]
# 判断 T 日是否确实跌停
if t_close <= t_low_limit * 1.005: # 容差范围
# 2. 计算 T+1 至 T+4 (即最近4个交易日) 的整体 VWAP
# 此时 hist 的后4天即为 T+1 至 T+4
bars = get_bars(security, count=4, unit='1d',
fields=['close', 'money', 'volume'],
include_now=True, end_dt=context.previous_date)
if len(bars) < 4:
return
total_money = bars['money'].sum()
total_volume = bars['volume'].sum()
period_vwap = total_money / total_volume if total_volume > 0 else 0
# 3. 获取当前最新价格
current_price = current_data[security].last_price
cash = context.portfolio.available_cash
# 4. 择时买入逻辑:
# 当前价格站上 T+1~T+4 的整体 VWAP,且当前价格高于这4天的收盘中位数(代表筹码分布向上突破)
close_median = np.median(bars['close'])
if current_price > period_vwap and current_price > close_median:
if security not in context.portfolio.positions:
order_value(security, cash)
log.info("筹码沉淀完成,突破VWAP,买入 %s" % (security))
# 5. 止损/止盈逻辑
elif security in context.portfolio.positions:
# 如果价格跌破 4日 VWAP,说明筹码松动,止损卖出
if current_price < period_vwap * 0.97:
order_target(security, 0)
log.info("筹码松动,跌破VWAP止损,卖出 %s" % (security))
get_current_tick 获取日内实时 Tick 数据,计算日内实时 VWAP。当实时价格同时突破“历史4日整体 VWAP”和“今日日内 VWAP”时,为共振买入点。