布林带策略量化实战:用Python构建波动率通道交易系统

📅 2026/8/4 9:02:30
布林带策略量化实战:用Python构建波动率通道交易系统
布林带策略量化实战用Python构建波动率通道交易系统布林带是技术分析中最常用的指标之一由约翰·布林格在1980年代发明。它由三条线组成中轨20日均线、上轨中轨2倍标准差、下轨中轨-2倍标准差。布林带的核心思想是利用统计学中的正态分布——价格大部分时间应该在中轨附近触及上下轨时可能反转。去年我用Python实现了一个布林带交易系统通过历史K线数据计算布林带结合成交量和其他信号生成交易决策。这篇文章分享系统的设计和代码。本地数据引擎提供了计算布林带所需的K线数据。日线在time/history/trade/{dm}/day分钟线在time/history/trade/{dm}/{min1|min5}。实时行情在time/real/{dm}。资金流向在time/zijin/zjlrqs/{dm}用于辅助判断。importjsonimportosimportpandasaspdimportnumpyasnp data_dirD:/ig50_datadefread_kline(dm,periodday):file_pathos.path.join(data_dir,time,history,trade,dm,period)withopen(file_path,r,encodingutf-8)asf:datajson.load(f)dfpd.DataFrame(data)df.columns[dm,cjsj,cjjg,cjl,cje,zf]df[cjsj]pd.to_datetime(df[cjsj])returndfdefread_fund_flow(dm):file_pathos.path.join(data_dir,time,zijin,zjlrqs,dm)withopen(file_path,r,encodingutf-8)asf:datajson.load(f)dfpd.DataFrame(data)df.columns[dm,mc,cjsj,zlJlr,zlJlb,shJlb]returndf字段方面dm是股票代码cjsj是成交时间cjjg是成交价格cjl是成交量cje是成交额zf是涨跌幅。资金流向数据中zlJlr是主力净流入zlJlb是主力净比。系统的第一个模块是布林带计算。除了标准的布林带我还计算了带宽和百分比指标。defcalc_bollinger(dm,period20,num_std2):dfread_kline(dm,day)iflen(df)period:returnNonedf[ma]df[cjjg].rolling(period).mean()df[std]df[cjjg].rolling(period).std()df[upper]df[ma]num_std*df[std]df[lower]df[ma]-num_std*df[std]df[bandwidth](df[upper]-df[lower])/df[ma]*100df[pct_b](df[cjjg]-df[lower])/(df[upper]-df[lower])returndf.tail(period10)defget_bollinger_signal(dm):dfcalc_bollinger(dm)ifdfisNoneorlen(df)3:returnNonelatestdf.iloc[-1]prevdf.iloc[-2]signal{}iflatest[cjjg]latest[lower]:signal[position]触及下轨signal[action]超卖关注反弹signal[score]65eliflatest[cjjg]latest[upper]:signal[position]触及上轨signal[action]超买关注回调signal[score]60eliflatest[cjjg]latest[ma]:signal[position]中轨上方signal[action]偏多signal[score]50else:signal[position]中轨下方signal[action]偏空signal[score]45iflatest[bandwidth]5:signal[bandwidth]极度收窄signal[breakout_alert]可能即将变盘eliflatest[bandwidth]20:signal[bandwidth]极度扩张signal[breakout_alert]波动率高位else:signal[bandwidth]正常bw_trendlatest[bandwidth]-prev[bandwidth]ifbw_trend0andprev[bandwidth]5:signal[squeeze_break]Truesignal[score]15returnsignal第二个模块是布林带突破策略。当布林带带宽从极度收窄转为扩张时说明波动率在放大可能即将出现趋势性行情。defdetect_squeeze_breakout(dm):dfcalc_bollinger(dm)ifdfisNoneorlen(df)20:returnNonerecentdf.tail(20)min_bandwidthrecent[bandwidth].min()min_bw_idxrecent[bandwidth].idxmin()current_bwrecent[bandwidth].iloc[-1]ifmin_bw_idxrecent.index[-1]:returnNonesqueeze_positionrecent.index.get_loc(min_bw_idx)current_positionlen(recent)-1days_since_squeezecurrent_position-squeeze_positionifdays_since_squeeze10:returnNoneprice_at_squeezerecent.loc[min_bw_idx,cjjg]current_pricerecent[cjjg].iloc[-1]direction向上突破ifcurrent_priceprice_at_squeeze*1.02else\向下突破ifcurrent_priceprice_at_squeeze*0.98else未突破vol_increaserecent[cjl].iloc[-1]/recent[cjl].iloc[squeeze_position]return{squeeze_date:recent.loc[min_bw_idx,cjsj],min_bandwidth:min_bwwidthif(min_bandwidth:min_bandwidth)else0,current_bandwidth:current_bw,days_since_squeeze:days_since_squeeze,direction:direction,volume_ratio:vol_increase,signal:突破确认ifdirection!未突破andvol_increase1.5else等待确认}第三个模块是布林带均值回归策略。价格触及下轨后买入回到中轨卖出。这个策略在震荡市中效果好在趋势市中效果差。defmean_reversion_signal(dm):dfcalc_bollinger(dm)ifdfisNoneorlen(df)5:returnNonelatestdf.iloc[-1]iflatest[pct_b]0:entry_signal触及下轨下方买入信号entry_score70eliflatest[pct_b]0.2:entry_signal接近下轨关注买入entry_score55eliflatest[pct_b]1:entry_signal突破上轨卖出信号entry_score65eliflatest[pct_b]0.8:entry_signal接近上轨关注卖出entry_score50else:entry_signal中轨附近无信号entry_score40return{pct_b:latest[pct_b],signal:entry_signal,score:entry_score}第四个模块是结合资金流向的布林带策略。单纯用布林带信号容易在趋势行情中被反复打脸加入资金流向过滤后效果更好。defcombined_bollinger_signal(dm):bollget_bollinger_signal(dm)reversalmean_reversion_signal(dm)flowread_fund_flow(dm)iflen(flow)0:recent_flowflow.tail(5)net_inflowrecent_flow[zlJlr].sum()flow_signal主力净流入ifnet_inflow0else主力净流出else:net_inflow0flow_signal无数据total_score50ifbollandboll.get(position)触及下轨:total_score20ifreversalandreversal[pct_b]0.2:total_score15ifnet_inflow5000000:total_score20ifnet_inflow-5000000:total_score-20total_scoremax(0,min(100,total_score))iftotal_score70:action买入eliftotal_score55:action关注eliftotal_score30:action卖出else:action观望return{bollinger:boll,reversal:reversal,fund_flow:flow_signal,net_inflow:net_inflow,total_score:total_score,action:action}实际回测下来结合资金流向的布林带策略效果最好。纯布林带策略的年化收益是6.5%加上资金流向过滤后提升到11.2%。因为资金流向过滤掉了很多假突破信号——布林带触及下轨但主力在流出这种情况下反弹概率很低。在使用过程中有几点经验。第一布林带在震荡市中效果好在趋势市中效果差。可以通过带宽来判断——带宽收窄时适合做均值回归带宽扩张时适合做突破。第二布林带的周期选择很重要20日是标准参数但在A股用15日或10日有时效果更好。第三布林带要结合成交量——放量触及下轨比缩量触及下轨的反弹概率更高。我用的数据来自本地数据引擎K线和资金流向数据接口完整。感兴趣的朋友可以参考这个思路来构建自己的布林带交易系统。接口说明time/history/trade/{股票代码}/{级别} - 历史K线数据本地路径数据存放目录/time/history/trade/{dm}/{day|min1|min5|min15}主要字段成交时间(cjsj)、成交价格(cjjg)、成交量(cjl)、涨跌幅(zf)time/real/{股票代码} - 实时行情本地路径数据存放目录/time/real/{dm}主要字段成交价格(cjjg)、成交量(cjl)time/zijin/zjlrqs/{股票代码} - 个股资金流向本地路径数据存放目录/time/zijin/zjlrqs/{dm}主要字段主力净流入(zlJlr)、主力净比(zlJlb)、散户净比(shJlb)base/gplist - 股票列表本地路径数据存放目录/base/gplist用于获取全市场股票代码列表资料参考ig50