最近,一些同学问我:"如何写一个量化程序,让股票在满足特定条件时自动卖出?"
确实,相比于充满情绪的手动操作,将成熟的卖出策略交给程序执行,不仅能克服人性的贪婪与恐惧,还能解放我们的时间和精力。
今天,我们就以一个常见的短线策略为例,写一个自动卖出示例。
在写代码之前,我们必须先明确卖出的逻辑。一个没有清晰策略的程序,只是危险的"瞎执行"。这里我们以两种经典的短线卖出场景为例:
1. 涨停封单不足卖出
这里简单演示下 代码示例:
def should_sell_by_limit_up(tick_data, stock_code):
"""
条件1:涨停封单不足卖出
"""
try:
current_price = tick_data['lastPrice']
upstop_price = get_upstop_price(stock_code)
# 使用容错比较,避免浮点数精度问题
if upstop_price > 0 and abs(current_price - upstop_price) < 0.01:
buy1_volume = tick_data.get('bid1_volume', 0)
if buy1_volume < BUY_1_VOLUME_THRESHOLD:
print(f"[涨停封单卖出] {stock_code} 封单量仅{buy1_volume}手,低于阈值{BUY_1_VOLUME_THRESHOLD}手")
return True
except Exception as e:
print(f"涨停封单判断出错 {stock_code}: {e}")
return False2. 冲高回落卖出
这里简单演示下 代码示例:
def should_sell_by_fallback(tick_data, stock_code):
"""
条件2:冲高回落卖出
"""
if stock_code not in stock_status_dict:
stock_status_dict[stock_code] = {'hit_high': False, 'peak_price': 0.0}
status = stock_status_dict[stock_code]
current_price = tick_data['lastPrice']
total_amount = tick_data['amount']
total_volume = tick_data['volume']
# 获取股票板块对应的策略参数
stock_prefix = get_stock_prefix(stock_code)
strategy_param = PARAM_MAP.get(stock_prefix, PARAM_MAP['00'])
# 计算分时均价(VWAP)
vwap = calculate_vwap(total_amount, total_volume)
if vwap == 0:
return False
# 计算相对于VWAP的涨幅
increase_from_vwap = (current_price - vwap) / vwap
# 第一步:判断是否冲高到阈值
if not status['hit_high'] and increase_from_vwap >= strategy_param['high_threshold']:
status['hit_high'] = True
status['peak_price'] = current_price
print(f"[{stock_code}] 冲高条件激活,价格已超过分时均价{strategy_param['high_threshold'] * 100}%")
return False
# 第二步:如果已冲高,则更新最高价,并判断是否回落
if status['hit_high']:
if current_price > status['peak_price']:
status['peak_price'] = current_price
decline_from_peak = (status['peak_price'] - current_price) / status['peak_price']
if decline_from_peak >= strategy_param['fallback_threshold']:
print(f"[{stock_code}] 冲高回落卖出!从最高点{status['peak_price']:.2f}回落{decline_from_peak * 100:.2f}%")
return True
return False如果我的分享对你投资有所帮助,不吝啬给个点赞关注呗。 这个号没啥推荐流量,养个新号, 后续主要分享AI量化相关。