量化策略系列教程:12Boll指標策略

小哥每天一嘮叨~用掘金、用掘金、用掘金證經社量化社區 - 證經社~~有沒有覺得小哥的策略跑的收益率很高呀!可以把你們的回測圖給小哥發過來,看著都覺得自己牛×!哈哈

1.策略原理及邏輯

1.1策略原理

布林線指標,即BOLL指標,其英文全稱是「Bollinger Bands」,布林線(BOLL)由約翰·布林先生創造,其利用統計原理,求出股價的標準差及其信賴區間,從而確定股價的波動範圍及未來走勢,利用波帶顯示股價的安全高低價位,因而也被稱為布林帶。其上下限範圍不固定,隨股價的滾動而變化。布林指標和麥克指標MIKE一樣同屬路徑指標,股價波動在上限和下限的區間之內,這條帶狀區的寬窄,隨著股價波動幅度的大小而變化,股價漲跌幅度加大時,帶狀區變寬,漲跌幅度狹小盤整時,帶狀區則變窄。

計算公式

中軌線=N日的移動平均線

上軌線=中軌線+兩倍的標準差

下軌線=中軌線-兩倍的標準差

(1)計算MA

MA=N日內的收盤價之和÷N

(2)計算標準差MD

MD=平方根(N-1)日的(C-MA)的兩次方之和除以N

(3)計算MB、UP、DN線

MB=(N-1)日的MA

UP=MB+k×MD

DN=MB-k×MD

(K為參數,可根據股票的特性來做相應的調整,一般默認為2)

指標表示

在股市分析軟體中,BOLL指標一共由四條線組成,即上軌線UP 、中軌線MB、下軌線DN和價格線。其中上軌線UP是UP數值的連線;中軌線MB是MB數值的連線;下軌線DN是DN數值的連線;在實戰中,投資者不需要進行BOLL指標的計算,主要是了解BOLL的計算方法和過程,以便更加深入地掌握BOLL指標的實質,為運用指標打下基礎。

布林線有四個主要功能

  (1)布林線可以指示支撐和壓力位置;

  (2)布林線可以顯示超買、超賣;

  (3)布林線可以指示趨勢;

  (4)布林線具備通道功能。

  布林線的理論使用原則是:當股價穿越最外面的壓力線(支撐線)時,表示賣點(買點)出現。當股價延著壓力線(支撐線)上升(下降)運行,雖然股價並未穿越,但若回頭突破第二條線即是賣點或買點。

1.2策略邏輯

  • 當布林線的上、中、下軌線同時向上運行時,且當前價格高於中軌的價格,則買入。
  • 當布林線的上、中、下軌線同時向下運行時,或者當前價格低於中軌的價格,則賣出。

2. 代碼解讀:

2.1配置文件【boll_stock.ini】(提示ini配置文件,需要保存成UTF8格式)

[strategy]nusername=npassword=n;回測模式nmode=4ntd_addr=localhost:8001nstrategy_id=n;訂閱代碼注意及時更新nsubscribe_symbols=nn[backtest]nstart_time=2016-03-01 09:00:00nend_time=2016-12-18 15:00:00nn;策略初始資金ninitial_cash=1000000nn;委託量成交比率,默認=1(每個委託100%成交)ntransaction_ratio=1nn;手續費率,默認=0(不計算手續費)ncommission_ratio=0.0003nn;滑點比率,默認=0(無滑點)nslippage_ratio=0.00246nn;行情復權模式,0=不復權,1=前復權nprice_type=1nn;基準nbench_symbol=SHSE.000903nn[para]n;數據訂閱周期nbar_type=86400nn;boll指標參數nn;boll周期nboll_period=22nn;上下軌偏差係數nnbdev_up=2nnbdev_down=2nnma_type=0nn#止盈止損n;是否固定止盈止損nis_fixation_stop=0n;是否移動止盈nis_movement_stop=1nn;移動盈利開始比率及固定盈利比率nstop_fixation_profit=0.2n;虧損比率nstop_fixation_loss=0.068nn;移動止盈比率nstop_movement_profit=0.068nn;累計開倉距離當前的最大交易日n;若開倉距今超過這個日期,則認為未開過倉nopen_max_days=22nn;歷史數據長度nhist_size=30nn;開倉量nopen_vol=2000n

2.2策略文件【boll_stock.py】

#!/usr/bin/env pythonn# encoding: utf-8nnimport sysnimport loggingnimport logging.confignimport configparsernimport csvnimport numpy as npnimport datetimenimport talibnimport arrownfrom gmsdk import *nnEPS = 1e-6nINIT_CLOSE_PRICE = 0nnnclass BOLL_STOCK(StrategyBase):n cls_config = Nonen cls_user_name = Nonen cls_password = Nonen cls_mode = Nonen cls_td_addr = Nonen cls_strategy_id = Nonen cls_subscribe_symbols = Nonen cls_stock_pool = []nn cls_backtest_start = Nonen cls_backtest_end = Nonen cls_initial_cash = 1000000n cls_transaction_ratio = 1n cls_commission_ratio = 0.0n cls_slippage_ratio = 0.0n cls_price_type = 1n cls_bench_symbol = Nonenn def __init__(self, *args, **kwargs):n super(BOLL_STOCK, self).__init__(*args, **kwargs)n self.cur_date = Nonen self.dict_close = {}n self.dict_open_close_signal = {}n self.dict_entry_high_low = {}n self.dict_last_factor = {}n self.dict_open_cum_days = {}nn @classmethodn def read_ini(cls, ini_name):n """n 功能:讀取策略配置文件n """n cls.cls_config = configparser.ConfigParser()n cls.cls_config.read(ini_name)nn @classmethodn def get_strategy_conf(cls):n """n 功能:讀取策略配置文件strategy段落的值n """n if cls.cls_config is None:n returnnn cls.cls_user_name = cls.cls_config.get(strategy, username)n cls.cls_password = cls.cls_config.get(strategy, password)n cls.cls_strategy_id = cls.cls_config.get(strategy, strategy_id)n cls.cls_subscribe_symbols = cls.cls_config.get(strategy, subscribe_symbols)n cls.cls_mode = cls.cls_config.getint(strategy, mode)n cls.cls_td_addr = cls.cls_config.get(strategy, td_addr)n if len(cls.cls_subscribe_symbols) <= 0:n cls.get_subscribe_stock()n else:n subscribe_ls = cls.cls_subscribe_symbols.split(,)n for data in subscribe_ls:n index1 = data.find(.)n index2 = data.find(., index1 + 1, -1)n cls.cls_stock_pool.append(data[:index2])nn returnnn @classmethodn def get_backtest_conf(cls):n """n 功能:讀取策略配置文件backtest段落的值n """n if cls.cls_config is None:n returnnn cls.cls_backtest_start = cls.cls_config.get(backtest, start_time)n cls.cls_backtest_end = cls.cls_config.get(backtest, end_time)n cls.cls_initial_cash = cls.cls_config.getfloat(backtest, initial_cash)n cls.cls_transaction_ratio = cls.cls_config.getfloat(backtest, transaction_ratio)n cls.cls_commission_ratio = cls.cls_config.getfloat(backtest, commission_ratio)n cls.cls_slippage_ratio = cls.cls_config.getfloat(backtest, slippage_ratio)n cls.cls_price_type = cls.cls_config.getint(backtest, price_type)n cls.cls_bench_symbol = cls.cls_config.get(backtest, bench_symbol)nn returnnn @classmethodn def get_stock_pool(cls, csv_file):n """n 功能:獲取股票池中的代碼n """n csvfile = open(csv_file, r)n reader = csv.reader(csvfile)n for line in reader:n cls.cls_stock_pool.append(line[0])nn returnnn @classmethodn def get_subscribe_stock(cls):n """n 功能:獲取訂閱代碼n """n cls.get_stock_pool(stock_pool.csv)n bar_type = cls.cls_config.getint(para, bar_type)n if 86400 == bar_type:n bar_type_str = .bar. + dailyn else:n bar_type_str = .bar. + %d % cls.cls_config.getint(para, bar_type)nn cls.cls_subscribe_symbols = ,.join(data + bar_type_str for data in cls.cls_stock_pool)n returnnn def utc_strtime(self, utc_time):n """n 功能:utc轉字元串時間n """n str_time = %s % arrow.get(utc_time).to(local)n str_time.replace(T, )n str_time = str_time.replace(T, )n return str_time[:19]nn def get_para_conf(self):n """n 功能:讀取策略配置文件para(自定義參數)段落的值n """n if self.cls_config is None:n returnnn self.boll_period = self.cls_config.getint(para, boll_period)n self.nbdev_up = self.cls_config.getfloat(para, nbdev_up)n self.nbdev_down = self.cls_config.getfloat(para, nbdev_down)n self.ma_type = self.cls_config.getint(para, ma_type)nn self.hist_size = self.cls_config.getint(para, hist_size)n self.open_vol = self.cls_config.getint(para, open_vol)n self.open_max_days = self.cls_config.getint(para, open_max_days)nn self.is_fixation_stop = self.cls_config.getint(para, is_fixation_stop)n self.is_movement_stop = self.cls_config.getint(para, is_movement_stop)nn self.stop_fixation_profit = self.cls_config.getfloat(para, stop_fixation_profit)n self.stop_fixation_loss = self.cls_config.getfloat(para, stop_fixation_loss)nn self.stop_movement_profit = self.cls_config.getfloat(para, stop_movement_profit)nn returnnn def init_strategy(self):n """n 功能:策略啟動初始化操作n """n if self.cls_mode == gm.MD_MODE_PLAYBACK:n self.cur_date = self.cls_backtest_startn self.end_date = self.cls_backtest_endn else:n self.cur_date = datetime.date.today().strftime(%Y-%m-%d) + 08:00:00n self.end_date = datetime.date.today().strftime(%Y-%m-%d) + 16:00:00nn self.dict_open_close_signal = {}n self.dict_entry_high_low = {}n self.get_last_factor()n self.init_data()n self.init_entry_high_low()n returnnn def init_data(self):n """n 功能:獲取訂閱代碼的初始化數據n """n for ticker in self.cls_stock_pool:n # 初始化倉位操作信號字典n self.dict_open_close_signal.setdefault(ticker, False)nn daily_bars = self.get_last_n_dailybars(ticker, self.hist_size - 1, self.cur_date)n if len(daily_bars) <= 0:n continuenn end_daily_bars = self.get_last_n_dailybars(ticker, 1, self.end_date)n if len(end_daily_bars) <= 0:n continuenn if ticker not in self.dict_last_factor:n continuenn end_adj_factor = self.dict_last_factor[ticker]n cp_ls = [data.close * data.adj_factor / end_adj_factor for data in daily_bars]n cp_ls.reverse()nn # 留出一個空位存儲當天的一筆數據n cp_ls.append(INIT_CLOSE_PRICE)n close = np.asarray(cp_ls, dtype=np.float)nn # 存儲歷史的closen self.dict_close.setdefault(ticker, close)nn # end = time.clock()n # logging.info(init_data cost time: %f s % (end - start))nn def init_data_newday(self):n """n 功能:新的一天初始化數據n """n # 新的一天,去掉第一筆數據,並留出一個空位存儲當天的一筆數據n for key in self.dict_close:n if len(self.dict_close[key]) >= self.hist_size and abs(self.dict_close[key][-1] - INIT_CLOSE_PRICE) > EPS:n self.dict_close[key] = np.append(self.dict_close[key][1:], INIT_CLOSE_PRICE)n elif len(self.dict_close[key]) < self.hist_size and abs(self.dict_close[key][-1] - INIT_CLOSE_PRICE) > EPS:n self.dict_close[key] = np.append(self.dict_close[key][:], INIT_CLOSE_PRICE)nn # 初始化倉位操作信號字典n for key in self.dict_open_close_signal:n self.dict_open_close_signal[key] = Falsenn # 開倉後到當前的交易日天數n keys = list(self.dict_open_cum_days.keys())n for key in keys:n if self.dict_open_cum_days[key] >= self.open_max_days:n del self.dict_open_cum_days[key]n else:n self.dict_open_cum_days[key] += 1nn def get_last_factor(self):n """n 功能:獲取指定日期最新的復權因子n """n for ticker in self.cls_stock_pool:n daily_bars = self.get_last_n_dailybars(ticker, 1, self.end_date)n if daily_bars is not None and len(daily_bars) > 0:n self.dict_last_factor.setdefault(ticker, daily_bars[0].adj_factor)nn def init_entry_high_low(self):n """n 功能:獲取進場後的最高價和最低價,模擬或實盤交易啟動時載入n """n pos_list = self.get_positions()n high_list = []n low_list = []n for pos in pos_list:n symbol = pos.exchange + . + pos.sec_idn init_time = self.utc_strtime(pos.init_time)nn cur_time = datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S)nn daily_bars = self.get_dailybars(symbol, init_time, cur_time)nn high_list = [bar.high for bar in daily_bars]n low_list = [bar.low for bar in daily_bars]nn if len(high_list) > 0:n highest = np.max(high_list)n else:n highest = pos.vwapnn if len(low_list) > 0:n lowest = np.min(low_list)n else:n lowest = pos.vwapnn self.dict_entry_high_low.setdefault(symbol, [highest, lowest])nn def on_bar(self, bar):n if self.cls_mode == gm.MD_MODE_PLAYBACK:n if bar.strtime[0:10] != self.cur_date[0:10]:n self.cur_date = bar.strtime[0:10] + 08:00:00n # 新的交易日n self.init_data_newday()nn symbol = bar.exchange + . + bar.sec_idnn self.movement_stop_profit_loss(bar)n self.fixation_stop_profit_loss(bar)nn # 填充價格n if symbol in self.dict_close:n self.dict_close[symbol][-1] = bar.closenn pos = self.get_position(bar.exchange, bar.sec_id, OrderSide_Bid)nn if self.dict_open_close_signal[symbol] is False:n # 當天未有對該代碼開、平倉n if symbol in self.dict_close:n upper, middle, lower = talib.BBANDS(self.dict_close[symbol], timeperiod=self.boll_period,n nbdevup=self.nbdev_up, nbdevdn=self.nbdev_down, matype=self.ma_type)nn if pos is None and symbol not in self.dict_open_cum_days n and (upper[-1] > upper[-2] and upper[-2] > upper[-3] n and middle[-1] > middle[-2] and middle[-2] > middle[-3] n and lower[-1] > lower[-2] and lower[-2] > lower[-3] n and bar.close > middle[-1]):n # 有開倉機會則設置已開倉的交易天數n self.dict_open_cum_days[symbol] = 0nn cash = self.get_cash()n cur_open_vol = self.open_voln if cash.available / bar.close > self.open_vol:n cur_open_vol = self.open_voln else:n cur_open_vol = int(cash.available / bar.close / 100) * 100nn if cur_open_vol == 0:n print(no available cash to buy, available cash: %.2f % cash.available)n else:n # 上、中、下軌同時向上運行n self.open_long(bar.exchange, bar.sec_id, bar.close, cur_open_vol)n self.dict_open_close_signal[symbol] = Truen logging.info(open long, symbol:%s, time:%s, price:%.2f % (symbol, bar.strtime, bar.close))n elif pos is not None and (upper[-1] < upper[-2] and middle[-1] < middle[-2] and lower[-1] < lower[-2] n or bar.close < middle[-1]):n # 上、中、下軌線同時向下運行時n vol = pos.volume - pos.volume_todayn if vol > 0:n self.close_long(bar.exchange, bar.sec_id, bar.close, vol)n self.dict_open_close_signal[symbol] = Truen logging.info(close long, symbol:%s, time:%s, price:%.2f % (symbol, bar.strtime, bar.close))n # print close long, symbol:%s, time:%s %(symbol, bar.strtime)nn def on_order_filled(self, order):n symbol = order.exchange + . + order.sec_idn if order.position_effect == PositionEffect_CloseYesterday n and order.side == OrderSide_Bid:n pos = self.get_position(order.exchange, order.sec_id, order.side)n if pos is None and self.is_movement_stop == 1:n self.dict_entry_high_low.pop(symbol)nn def fixation_stop_profit_loss(self, bar):n """n 功能:固定止盈、止損,盈利或虧損超過了設置的比率則執行止盈、止損n """n if self.is_fixation_stop == 0:n returnnn symbol = bar.exchange + . + bar.sec_idn pos = self.get_position(bar.exchange, bar.sec_id, OrderSide_Bid)n if pos is not None:n if pos.fpnl > 0 and pos.fpnl / pos.cost >= self.stop_fixation_profit:n self.close_long(bar.exchange, bar.sec_id, 0, pos.volume - pos.volume_today)n self.dict_open_close_signal[symbol] = Truen logging.info(n fixnation stop profit: close long, symbol:%s, time:%s, price:%.2f, vwap: %s, volume:%s % (symbol,n bar.strtime,n bar.close,n pos.vwap,n pos.volume))n elif pos.fpnl < 0 and pos.fpnl / pos.cost <= -1 * self.stop_fixation_loss:n self.close_long(bar.exchange, bar.sec_id, 0, pos.volume - pos.volume_today)n self.dict_open_close_signal[symbol] = Truen logging.info(n fixnation stop loss: close long, symbol:%s, time:%s, price:%.2f, vwap:%s, volume:%s % (symbol,n bar.strtime,n bar.close,n pos.vwap,n pos.volume))nn def movement_stop_profit_loss(self, bar):n """n 功能:移動止盈, 移動止盈止損按進場後的最高價乘以設置的比率與當前價格相比,n 並且盈利比率達到設定的盈虧比率時,執行止盈n """n if self.is_movement_stop == 0:n returnnn entry_high = Nonen entry_low = Nonen pos = self.get_position(bar.exchange, bar.sec_id, OrderSide_Bid)n symbol = bar.exchange + . + bar.sec_idnn is_stop_profit = Truenn if pos is not None and pos.volume > 0:n if symbol in self.dict_entry_high_low:n if self.dict_entry_high_low[symbol][0] < bar.close:n self.dict_entry_high_low[symbol][0] = bar.closen is_stop_profit = Falsen if self.dict_entry_high_low[symbol][1] > bar.close:n self.dict_entry_high_low[symbol][1] = bar.closen [entry_high, entry_low] = self.dict_entry_high_low[symbol]nn else:n self.dict_entry_high_low.setdefault(symbol, [bar.close, bar.close])n [entry_high, entry_low] = self.dict_entry_high_low[symbol]n is_stop_profit = Falsenn if is_stop_profit:n # 移動止盈n if bar.close <= (n 1 - self.stop_movement_profit) * entry_high and pos.fpnl / pos.cost >= self.stop_fixation_profit:n if pos.volume - pos.volume_today > 0:n self.close_long(bar.exchange, bar.sec_id, 0, pos.volume - pos.volume_today)n self.dict_open_close_signal[symbol] = Truen logging.info(n movement stop profit: close long, symbol:%s, time:%s, price:%.2f, vwap:%.2f, volume:%s % (n symbol,n bar.strtime, bar.close, pos.vwap, pos.volume))nn # 止損n if pos.fpnl < 0 and pos.fpnl / pos.cost <= -1 * self.stop_fixation_loss:n self.close_long(bar.exchange, bar.sec_id, 0, pos.volume - pos.volume_today)n self.dict_open_close_signal[symbol] = Truen logging.info(n movement stop loss: close long, symbol:%s, time:%s, price:%.2f, vwap:%.2f, volume:%s % (symbol,n bar.strtime,n bar.close,n pos.vwap,n pos.volume))nnnif __name__ == __main__:n print(get_version())n logging.config.fileConfig(logging.ini)n BOLL_STOCK.read_ini(boll_stock.ini)n BOLL_STOCK.get_strategy_conf()nn boll_stock = BOLL_STOCK(username=BOLL_STOCK.cls_user_name,n password=BOLL_STOCK.cls_password,n strategy_id=BOLL_STOCK.cls_strategy_id,n subscribe_symbols=BOLL_STOCK.cls_subscribe_symbols,n mode=BOLL_STOCK.cls_mode,n td_addr=BOLL_STOCK.cls_td_addr)nn if BOLL_STOCK.cls_mode == gm.MD_MODE_PLAYBACK:n BOLL_STOCK.get_backtest_conf()n ret = boll_stock.backtest_config(start_time=BOLL_STOCK.cls_backtest_start,n end_time=BOLL_STOCK.cls_backtest_end,n initial_cash=BOLL_STOCK.cls_initial_cash,n transaction_ratio=BOLL_STOCK.cls_transaction_ratio,n commission_ratio=BOLL_STOCK.cls_commission_ratio,n slippage_ratio=BOLL_STOCK.cls_slippage_ratio,n price_type=BOLL_STOCK.cls_price_type,n bench_symbol=BOLL_STOCK.cls_bench_symbol)nn boll_stock.get_para_conf()n boll_stock.init_strategy()n ret = boll_stock.run()nnprint(run result %s % ret)n

如果想了解相關的python函數和掘金介面函數,走下方通道:

http://zjshe.cn/q/forum.php?mod=viewthread&tid=60&extra=page%3D1

有不了解的可以給小編留言哦,小編會細心為大家解答~


推薦閱讀:

大家聊聊使用JoinQuant是什麼體驗?
成長股的奧秘,PEG選股策略研究丨礦友必讀
【理論】量化並行效率:阿姆達爾定律
TaLib在股票技術分析中的應用

TAG:量化 | 策略 | Python |