iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
永豐金融APIs

永豐金API之30天不中斷Q&A系列 第 22

Day22 - Shioaji X Backtesting -雙均線策略

  • 分享至 

  • xImage
  •  

Shioaji X Backtesting -雙均線策略

好啦!經過這麼多堂課,相信大家對Backtesting有一定的認識了,
今天要來和大家分享的是常見的雙均線策略。

雙均線策略-TwoMA

from backtesting import Backtest, Strategy 
from backtesting.lib import crossover
from backtesting.test import SMA 

class TwoMA(Strategy):   
    # 定義長短天期均線參數
    n1 = 20
    n2 = 60
    
    # 先算好均線(技術指標)價格
    def init(self):       
        self.sma1 = self.I(SMA, self.data.Close, self.n1)
        self.sma2 = self.I(SMA, self.data.Close, self.n2)

    #一次推進一根 K 棒    
    def next(self):       
        #短天期均線較長天期均線高,隔日開盤價買進
        if self.sma1 > self.sma2 and (not self.position.is_long):
            self.buy()
        #短天期均線較長天期均線低,隔日開盤價賣出
        elif self.sma2 > self.sma1 :
            self.position.close()

Backtesting回測囉!

#輸入回測的條件,df是上一篇台積電日K資料,TwoMA是寫好的策略,初始資金10000,交易成本0.2%
bt = Backtest(df, TwoMA, cash=10000, commission=0.002)

#將跑完回測得到的數據放到stats
stats = bt.run()
stats

從下面的回測結果可以發現:

資料:台積電2020-2021/9/22

策略:「短均線>長均線做多,短均線<長均線出場」

績效:單單用月線和季線的組合,竟然就有90%的報酬!

Out:
---------------------------------------------
Start                     2020-01-02 00:00:00
End                       2021-09-22 00:00:00
Duration                    629 days 00:00:00
Exposure [%]                        59.300477
Equity Final [$]                 19049.461623
Equity Peak [$]                  22923.436404
Return [%]                          90.494616
Buy & Hold Return [%]               72.861357
Max. Drawdown [%]                  -16.899625
Avg. Drawdown [%]                   -3.820395
Max. Drawdown Duration      244 days 00:00:00
Avg. Drawdown Duration       27 days 00:00:00
# Trades                                    2
Win Rate [%]                             50.0
Best Trade [%]                     101.822896
Worst Trade [%]                     -0.202401
Avg. Trade [%]                      50.810247
Max. Trade Duration         322 days 00:00:00
Avg. Trade Duration         187 days 00:00:00
Expectancy [%]                      51.012648
SQN                                  0.992163
Sharpe Ratio                         0.704301
Sortino Ratio                             NaN
Calmar Ratio                          3.00659
_strategy                               TwoMA

一行code把圖畫出來

bt.plot(superimpose = False)

接著來做最佳化吧!

stats = bt.optimize(n1=range(10, 41, 1),
                    n2=range(41, 121, 1),
                    maximize='Equity Final [$]',
                    )
stats
Out:
---------------------------------------------
Start                     2020-01-02 00:00:00
End                       2021-09-22 00:00:00
Duration                    629 days 00:00:00
Exposure [%]                        55.166932
Equity Final [$]                 21305.634403
Equity Peak [$]                  22923.436404
Return [%]                         113.056344
Buy & Hold Return [%]               72.861357
Max. Drawdown [%]                  -14.561664
Avg. Drawdown [%]                   -3.776633
Max. Drawdown Duration      244 days 00:00:00
Avg. Drawdown Duration       28 days 00:00:00
# Trades                                    3
Win Rate [%]                            100.0
Best Trade [%]                     102.861905
Worst Trade [%]                      1.855479
Avg. Trade [%]                      35.984833
Max. Trade Duration         315 days 00:00:00
Avg. Trade Duration         116 days 00:00:00
Expectancy [%]                            NaN
SQN                                  1.160389
Sharpe Ratio                          0.62127
Sortino Ratio                             NaN
Calmar Ratio                         2.471203
_strategy                  TwoMA(n1=40,n2=48)

最佳化後用40和48這兩條均線可以得到最佳解!

雖然這績效看起來真的驚人,但這看起來也未免太人工了,
因此這邊只是幫大家熟悉一下基本策略如何實作及最佳化,
大家可別直接拿去用啊!

之前安裝了Talib,下一篇會介紹用Talib的RSI低買高賣策略!


上一篇
Day21 - Blocking & Non-blocking Mode
下一篇
Day23 - Shioaji X Backtesting - RSI低買高賣策略
系列文
永豐金API之30天不中斷Q&A26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言