2019年3月13日 星期三

[量化狼]KD指標科學實驗三部曲


KD:指標 台指實驗

KD是常見的技術指標之一,用收盤價、一段時間的最高價和一段時間最低價計算出的趨勢指標;在計算上需要循序推導出RSVK值最後在導出D值:
很明顯地,K值和D值就是RSV的移動均線;市面上有很多書籍或網站喜歡用9日的高低點來計算(也就是N=9),在此我們就來試試多數人使用的KD方法,若以純粹做多,是否能在台指期取得作用。
        在這篇文章中,將示範三種策略 :
1:K值向上穿越D(黃金交叉)時做多,K值向下穿越D(死亡交叉)時多單平倉。
2:K值和D值處於超賣區(<20)時做多,K值和D值處於超買區(>80)時多單平倉。
3:RSV寫出改良版的簡單策略;N改為55RSV>65時做多,RSV<10時多單平倉
KD策略1: 
K值向上穿越D(黃金交叉)時做多,K值向下穿越D(死亡交叉)時多單平倉。
策略名稱
KD策略1
交易層級
1
交易成本
來回600
回測期間
2001-2019/2
權益曲線










程式碼: 
Var :
  RSV(50) ,
  K_(50) ,
  D_(50) ;
 
RSV = (c-Lowest(l,9))/(Highest(h,9)-Lowest(l,9))*100 ;
K_ = K_*2/3 + RSV*1/3 ;
D_ = D_*2/3 + K_*1/3 ;

//Gold Cross Buy
if marketposition<=0 and K_ cross above D_ then
  buy 1 share at next bar market ;
//Dead Cross Sell
if marketposition>0 and K_ cross below D_ then
  sell all shares 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年之前此策略表現並不是很好,但在之後的效果還算可以;總體來說,並不是一個很好的策略
KD策略2:
K值和D值處於超賣區(<20)時做多,K值和D值處於超買區(>80)時多單平倉。
策略名稱
KD策略2
交易層級
1
交易成本
來回600
回測期間
2001-2019/2
權益曲線
程式碼:
Var :
  RSV(50) ,
  K_(50) ,
  D_(50) ;
 
RSV = (c-Lowest(l,9))/(Highest(h,9)-Lowest(l,9))*100 ;
K_ = K_*2/3 + RSV*1/3 ;
D_ = D_*2/3 + K_*1/3 ;

//OverSelling Buy
if marketposition<=0 and K_<20 and D_<20 then
  buy 1 share at next bar market ;
//OverBought Sell
if marketposition>0 and K_>80 and D_>80 then
  sell all shares 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 ;
        以損益圖就可以發現,這存在交易次數太少的問題,並且跟策略1一樣,在2009年之前表現得並不好;總體來說,並不是一個好的策略 

KD策略3:
RSV寫出改良版的簡單策略;N改為55RSV>65時做多,RSV<10時多單平倉
策略名稱
KD策略3
交易層級
1
交易成本
來回600
回測期間
2001-2019/2
權益曲線:
程式碼:
Input :
  len(55) ,
  L_in(65) ,
  L_out(10) ;

Var :
  RSV(50) ;
 
RSV = (c-Lowest(l,len))/(Highest(h,len)-Lowest(l,len))*100 ;

if marketposition<=0 and RSV>L_in then
  buy 1 share at next bar market ;
if marketposition>0 and RSV<L_out then
  sell all shares 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 ;

        以損益圖可以發現,策略3比前兩個策略都好得多,程式碼也不會很難、比前面兩個策略的都還要簡單;筆者把策略績效放在後面,提供給讀者練習。
邏輯中文翻譯:
RSV>65時做多
RSV<10時多單平倉
結算出場

回測績效檢視: