2019年3月28日 星期四

[量化狼]MACD 指標科學實驗二部曲

MACD策略
        MACD全名為Moving Average Convergence / Divergence,由名字就可以知道MACD是一個以均線為基礎的指標。

MACD指標只需要使用收盤價就可以計算,在計算上需要先算出兩條長短天期的指數移動平均(EMA),再用兩條均線相減做出DIFF,最後再用DIFF做出指數移動平均值DEA
EMA_1 = 2/(12+1)*收盤價 + 11/(12+1)*(前日EMA_1)
EMA_2 = 2/(26+1)*收盤價 + 25/(26+1)*(前日EMA_2)
DIFF = EMA_1 - EMA_2
DEA = 2/(9+1)*DIFF + 8/(9+1)*(前日DEA)

        可以發現公式裡有3個參數,分別是EMA_1EMA_2DEA取指數平均的天期,在此實測當中我們並不修改預設的參數,來試試看預設版的MACD到底能不能在台指期取得作用。
在這篇文章中,將示範 
1.     基本策略:DIFF向上穿越DEA(黃金交叉)時做多,DIFF向下穿越DEA(死亡交叉)時多單平倉。
2.     改良策略:DIFF>DEA時做多,DIFF<DEA時多單平倉;DIFF向下穿越DEA(死亡交叉)時做空,空單輸50點時停損。





1.    基本策略:

DIFF向上穿越DEA(黃金交叉)時做多,DIFF向下穿越DEA(死亡交叉)時多單平倉。
策略名稱
MACD策略1
交易層級
1
交易成本
來回600
回測期間
2001-2019/2
程式碼:
Var :
  EMA_1(0) ,
  EMA_2(0) ,
  DIFF(0) ,
  DEA(0) ;
 
EMA_1 = 2/(12+1)*c + 11/(12+1)*EMA_1 ;
EMA_2 = 2/(26+1)*c + 25/(26+1)*EMA_2 ;
DIFF = EMA_1 - EMA_2 ;
DEA = 2/(9+1)*DIFF + 8/(9+1)*DEA ;

if marketposition<=0 and DIFF cross over DEA then
  Buy 1 share at next bar market ;
if marketposition>0 and DIFF cross below DEA then
  sell all share at next bar market ;


if dayofmonth(date)>14 and dayofmonth(date)<22 and dayofweek(date)=3 and time>=1330 and time<=1345 then  begin
  sell("CheckDay Sell") all shares at this bar close ;
  buytocover("CheckDay Buytocover") all shares at this bar close ; 

end ;
權益曲線:
以損益圖就可以明顯看出,在2009年之前此策略表現並不是很好,且有交易次數太少的問題;總體來說,並不是一個很好的策略


2.    改良策略:

DIFF>DEA時做多,DIFF<DEA時多單平倉;DIFF向下穿越DEA(死亡交叉)時做空,空單輸50點時停損。

程式碼:
Var :
  EMA_1(0) ,
  EMA_2(0) ,
  DIFF(0) ,
  DEA(0) ;
 
EMA_1 = 2/(12+1)*c + 11/(12+1)*EMA_1 ;
EMA_2 = 2/(26+1)*c + 25/(26+1)*EMA_2 ;
DIFF = EMA_1 - EMA_2 ;
DEA = 2/(9+1)*DIFF + 8/(9+1)*DEA ;

if marketposition<=0 and DIFF>DEA then
  Buy 1 share at next bar market ;
if marketposition>=0 and DIFF cross below DEA then
  sellshort 1 share at next bar market ;
if marketposition>0 and DIFF<DEA then
  sell all share at next bar market ;
if marketposition<0 then
  buytocover all shares at next bar entryprice+50 stop ;

if dayofmonth(date)>14 and dayofmonth(date)<22 and dayofweek(date)=3 and time>=1330 and time<=1345 then  begin
  sell("CheckDay Sell") all shares at this bar close ;
  buytocover("CheckDay Buytocover") all shares at this bar close ; 

end ;
權益曲線:

以損益圖來看算是還不錯,不用黃金交叉進場而改用DIFF>DEA時做多,使得交易次數變多,再加上空方也有操作,整體績效平滑許多
除以上兩種之外,先前曾經運用更進階的MACD概念如MACD逐高策略、MACD+ADX二維趨勢策略,在策略的發展上,給大家更不一樣的思考方式