DAY 15
0

## Day15 - Shioaji X Backtesting -均線突破策略

Backtesting到底要怎麼用呢？這邊我們會一步一步向大家介紹，

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

class OneMA(Strategy):

n1 = 60  #預設的均線參數

def init(self): #初始化會用到的參數和指標，告知要如何計算
self.sma1 = self.I(SMA, self.data.Close, self.n1)

def next(self): #回測的時候每一根K棒出現什麼狀況要觸發進出場
#如果收盤價>sma1(也就是60ma)，而且目前沒有多單部位
if (self.data.Close > self.sma1) and (not self.position.is_long) :
#如果收盤價<sma1(也就是60ma)
elif (self.data.Close < self.sma1):
self.position.close()#部位出場
#如果要做空就用self.sell()
``````

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

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

``````Out:
---------------------------------------------
Start                     2020-01-02 00:00:00
End                       2021-09-22 00:00:00
Duration                    629 days 00:00:00
Exposure [%]                        58.028617
Equity Final [\$]                 15061.227055
Equity Peak [\$]                  21692.629027
Return [%]                          50.612271
Buy & Hold Return [%]               72.861357
Max. Drawdown [%]                   -30.56984
Avg. Drawdown [%]                   -4.895715
Max. Drawdown Duration      244 days 00:00:00
Avg. Drawdown Duration       30 days 00:00:00
Win Rate [%]                        27.777778
Max. Trade Duration         162 days 00:00:00
Avg. Trade Duration          21 days 00:00:00
Expectancy [%]                       5.630253
SQN                                   0.84756
Sharpe Ratio                         0.231967
Sortino Ratio                        3.252764
Calmar Ratio                         0.099253
_strategy                               OneMA
``````

``````bt.plot(superimpose = False)
``````