量化策略系列教程:18MACD策略
最近小哥有點忙,一直顧不上更新,今天會給大家更新點新東西的~證經社量化社區 - 證經社
1.策略原理及邏輯
1.1指標定義
指數平滑異同移動平均線(Moving Average Convergence / Divergence, MACD)是股票交易中一種常見的技術分析工具,由Gerald Appel於1970年代提出,用於研判股票價格變化的強度、方向、能量,以及趨勢周期,以便把握股票買進和賣出的時機。MACD指標由一組曲線與圖形組成,通過收盤時股價或指數的快變及慢變的指數移動平均值(EMA)之間的差計算出來。「快」指更短時段的EMA,而「慢」則指較長時段的EMA,最常用的是12及26日EMA。
1.2指標計算公式
1).差離值(DIF值):
先利用收盤價的指數移動平均值(12日/26日)計算出差離值。
2).訊號線(DEM值,又稱MACD值):
- 計算出DIF後,會再畫一條「訊號線」,通常是DIF的9日指數移動平均值。
- 〖公式〗
3).柱形圖或棒形圖(histogram / bar graph):
- 接著,將DIF與DEM的差畫成「柱形圖」(MACD bar / OSC)。
- 〖公式〗
簡寫為
示例圖:
上表為收市價圖表(OHLC chart),
下表的綠線是差離值(DIF),紅線是訊號線(DEM),白色區塊柱形圖(MACD bar / OSC)是兩者的差(D-M)。
1.3指標解讀
MACD其實就是兩條指數移動平均線——EMA(12)和EMA(26)——的背離和交叉,EMA(26)可視為MACD的零軸,但是MACD呈現的訊息雜訊較均線少。
MACD是一種趨勢分析指標,不宜同時分析不同的市場環境。以下為三種交易訊號:
- 差離值(DIF值)與訊號線(DEM值,又稱MACD值)相交;
- 差離值與零軸相交;
- 股價與差離值的背離。
差離值(DIF)形成「快線」,訊號線(DEM)形成「慢線」。
當差離值(DIF)從下而上穿過訊號線(DEM),為買進訊號;相反若從上而下穿越,為賣出訊號。買賣訊號可能出現頻繁,需要配合其他指標(如:RSI、KD)一同分析。
棒形圖(MACD bar / Oscillator,OSC)的作用是顯示出「差離值」與「訊號線」的差,同時將兩條線的走勢具體化,以利判斷差離值和訊號線交叉形成的買賣訊號,例如正在下降的棒形圖代表兩線的差值朝負的方向走,趨勢向下;靠近零軸時,差離值和訊號線將相交出現買賣訊號。
棒形圖會根據正負值分布在零軸(X軸)的上下。棒形圖在零軸上方時表示走勢較強,反之則是走勢較弱。
差離值由下而上穿過零軸代表市場氣氛利好股價,相反由上而下則代表利淡股價。差離值與訊號線均在零軸上方時,被稱為多頭市場,反之,則被稱為空頭市場。
當股價創新低,但MACD並沒有相應創新低(牛市背離),視為利好(利多)訊息,股價跌勢或將完結。相反,若股價創新高,但MACD並沒有相應創新高(熊市背離),視為利淡(利空)訊息。同樣地,若股價與棒形圖不配合,也可作類似結論。
MACD是一種中長線的研判指標。當股市強烈震蕩或股價變化巨大(如送配股拆細等)時,可能會給出錯誤的信號。所以在決定股票操作時,應該謹慎參考其他指標,以及市場狀況,不能完全信任差離值的單一研判,避免造成損失。
1.4策略邏輯
- DIF、DEA均為正,DIF向上突破DEA,買入
- DIF、DEA均為負,DIF向下跌破DEA,賣出
2.策略代碼
2.1配置文件【macd_stock.ini】(提示ini配置文件,需要保存成UTF8格式)
[strategy]nusername=npassword=n;回測模式nmode=4ntd_addr=localhost:8001nstrategy_id=n;訂閱代碼注意及時更新nsubscribe_symbols=nn[backtest]nstart_time=2014-03-01 09:00:00nend_time=2016-03-18 16:00:00nninitial_cash=1000000nntransaction_ratio=1nncommission_ratio=0.0003nn;滑點比率,默認=0(無滑點)nslippage_ratio=0.00246nnnprice_type=1nnbench_symbol=SHSE.000016nn[para]nbar_type=86400nnlong_term=26nshort_term=12nmacd_term=9nn#止盈止損n;是否固定止盈止損nis_fixation_stop=0n;是否移動止盈nis_movement_stop=1nn;移動盈利開始比率及固定盈利比率nstop_fixation_profit=0.20n;虧損比率nstop_fixation_loss=0.068nn;移動止盈比率nstop_movement_profit=0.068nnhist_size=60nnopenlong_signal=2nnopen_vol=2000nn##############################################################n# logger settingsn##############################################################n[loggers]nkeys=rootnn[logger_root]nlevel=INFOnhandlers=console,filenn[handlers]nkeys=console,filenn[handler_file]nclass=handlers.RotatingFileHandlernargs=(mack_stock.log,a,1000,5)nformatter=simplenn[handler_console]nclass=StreamHandlernargs = (sys.stdout,)nformatter=simplenn[formatters]nkeys = simplenn[formatter_simple]nformat=%(asctime)s - %(name)s - %(levelname)s - %(message)sndatefmt=n
2.2策略文件【macd_stock.py】
#!/usr/bin/env pythonn# encoding: utf-8nnimport sysnimport loggingnimport logging.confignimport configparsernimport csvnimport numpy as npnimport datetimenimport talibnfrom gmsdk import *nnEPS = 1e-6nINIT_CLOSE_PRICE = 0nnnclass MACD_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(MACD_STOCK, self).__init__(*args, **kwargs)n self.cur_date = Nonen self.dict_close = {}n self.dict_openlong_signal = {}n self.dict_entry_high_low = {}n self.dict_last_factor = {}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])n 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.long_term = self.cls_config.getint(para, long_term)n self.short_term = self.cls_config.getint(para, short_term)n self.macd_term = self.cls_config.getint(para, macd_term)n self.hist_size = self.cls_config.getint(para, hist_size)n self.openlong_signal = self.cls_config.getint(para, openlong_signal)nn self.open_vol = self.cls_config.getint(para, open_vol)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_openlong_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_openlong_signal.setdefault(ticker, 0)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 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 # 未取足指標所需全部歷史數據時回測過程中補充數據n self.dict_close[key] = np.append(self.dict_close[key][:], INIT_CLOSE_PRICE)nn # 初始化買多信號字典n # for key in self.dict_openlong_signal:n # self.dict_openlong_signal.setdefault(key, 0)nn 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 symbol in self.dict_close:n close = self.dict_close[symbol]n dif, dea, macd = talib.MACD(close,n fastperiod=self.short_term,n slowperiod=self.long_term,n signalperiod=self.macd_term)n if pos is None and (dif[-1] > EPS and dea[-1] > EPS and dif[-1] > dif[-2] and dif[-1] > dea[-1]):n 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 self.dict_openlong_signal[symbol] += 1n if self.dict_openlong_signal[symbol] == self.openlong_signal:n self.open_long(bar.exchange, bar.sec_id, 0, self.open_vol)n pos = self.get_position(bar.exchange, bar.sec_id, OrderSide_Bid)n self.dict_openlong_signal[symbol] = 0n logging.info(open long, symbol:%s, time:%s, price:%.2f % (symbol, bar.strtime, bar.close))n elif pos is not None and (dif[-1] < EPS and dea[-1] < EPS and dif[-1] < dif[-2] and dif[-1] < dea[-1]):n vol = pos.volume - pos.volume_todayn if vol > 0:n self.close_long(bar.exchange, bar.sec_id, 0, vol)n logging.info(close long, symbol:%s, time:%s, price:%.2f % (symbol, bar.strtime, bar.close))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 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 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 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 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 cur_date = datetime.date.today().strftime(%Y%m%d)n log_file = macd_stock + cur_date + .logn logging.config.fileConfig(macd_stock.ini)n MACD_STOCK.read_ini(macd_stock.ini)n MACD_STOCK.get_strategy_conf()nn macd_stock = MACD_STOCK(username=MACD_STOCK.cls_user_name,n password=MACD_STOCK.cls_password,n strategy_id=MACD_STOCK.cls_strategy_id,n subscribe_symbols=MACD_STOCK.cls_subscribe_symbols,n mode=MACD_STOCK.cls_mode,n td_addr=MACD_STOCK.cls_td_addr)nn if MACD_STOCK.cls_mode == gm.MD_MODE_PLAYBACK:n MACD_STOCK.get_backtest_conf()n ret = macd_stock.backtest_config(start_time=MACD_STOCK.cls_backtest_start,n end_time=MACD_STOCK.cls_backtest_end,n initial_cash=MACD_STOCK.cls_initial_cash,n transaction_ratio=MACD_STOCK.cls_transaction_ratio,n commission_ratio=MACD_STOCK.cls_commission_ratio,n slippage_ratio=MACD_STOCK.cls_slippage_ratio,n price_type=MACD_STOCK.cls_price_type,n bench_symbol=MACD_STOCK.cls_bench_symbol)nn macd_stock.get_para_conf()n macd_stock.init_strategy()n ret = macd_stock.run()n
2.3股票池文件【stock_pool.csv】
SHSE.600000nSHSE.600010nSHSE.600011nSHSE.600015nSHSE.600016nSHSE.600018nSHSE.600019nSHSE.600023nSHSE.600028nSHSE.600030nSHSE.600031nSHSE.600036nSHSE.600048nSHSE.600050nSHSE.600104nSHSE.600111nSHSE.600115nSHSE.600150nSHSE.600276nSHSE.600340nSHSE.600372nSHSE.600398nSHSE.600485nSHSE.600518nSHSE.600519nSHSE.600585nSHSE.600637nSHSE.600690nSHSE.600705nSHSE.600795nSHSE.600837nSHSE.600886nSHSE.600887nSHSE.600893nSHSE.600900nSHSE.600958nSHSE.600959nSHSE.600999nSHSE.601006nSHSE.601018nSHSE.601088nSHSE.601111nSHSE.601166nSHSE.601169nSHSE.601186nSHSE.601211nSHSE.601225nSHSE.601288nSHSE.601318nSHSE.601328nSHSE.601336nSHSE.601377nSHSE.601390nSHSE.601398nSHSE.601600nSHSE.601601nSHSE.601618nSHSE.601628nSHSE.601633nSHSE.601668nSHSE.601669nSHSE.601688nSHSE.601727nSHSE.601766nSHSE.601788nSHSE.601800nSHSE.601808nSHSE.601818nSHSE.601857nSHSE.601898nSHSE.601899nSHSE.601901nSHSE.601939nSHSE.601985nSHSE.601988nSHSE.601989nSHSE.601998nSHSE.603288nSZSE.000001nSZSE.000002nSZSE.000063nSZSE.000069nSZSE.000166nSZSE.000333nSZSE.000538nSZSE.000625nSZSE.000651nSZSE.000725nSZSE.000776nSZSE.000858nSZSE.000895nSZSE.002024nSZSE.002252nSZSE.002304nSZSE.002415nSZSE.002594nSZSE.002736nSZSE.002739nSZSE.300059nSZSE.300104n
如果想了解相關的python函數和掘金介面函數,走下方通道:
http://zjshe.cn/q/forum.php?mod=viewthread&tid=96&extra=page%3D1
有不了解的可以給小編留言哦,小編會細心為大家解答~
推薦閱讀:
※掘金量化擂台賽
※【量化】均值回歸入門
※成長股的奧秘,PEG選股策略研究丨礦友必讀
※BAW定價模型研究-美式期權定價模型簡介
※給Python小白看的10個使用案例,入門Python就在這裡