天天看點

通過Tushare和backtrader實作量化投資回測一.Tushare介紹二.安裝Tushare三.backtrader介紹和安裝四.編寫代碼五.運作結果

通過Tushare和backtrader實作量化投資回測(tushare ID=418443)

  • 一.Tushare介紹
  • 二.安裝Tushare
  • 三.backtrader介紹和安裝
  • 四.編寫代碼
    • 1、初始化tushare,擷取指定股票代碼的股票曆史資料。
    • 2、加載資料
    • 3、加載backtrader引擎,初始化投資金額
    • 4、增加政策
    • 5、布林線規則政策的具體實作
    • 6、輸出回測結果并列印圖形
  • 五.運作結果

一.Tushare介紹

Tushare是一個免費開源的python财經資料接口包。主要實作對股票資料等從資料采集、清晰加工和資料存儲的過程。考慮到Python pandas包在金融量化分析中展現出的優勢,Tushare傳回的絕大部分的資料格式都是pandas DataFrame類型,非常便于用pandas/NumPy/Matplotlib進行資料分析和可視化。當然也可以通過Tushare的資料存儲功能将資料儲存到本地後用excel或關系資料庫分析。

二.安裝Tushare

方式1:pip install tushare

方式2:通路https://pypi.python.org/pypi/Tushare/下載下傳安裝

通過Tushare和backtrader實作量化投資回測一.Tushare介紹二.安裝Tushare三.backtrader介紹和安裝四.編寫代碼五.運作結果

可以通過https://tushare.pro/register?reg=418443 注冊,在個人中心中擷取token值

通過Tushare和backtrader實作量化投資回測一.Tushare介紹二.安裝Tushare三.backtrader介紹和安裝四.編寫代碼五.運作結果

token=‘你複制下來的token’

ts.set_token(token)

pro=ts.pro_api()

三.backtrader介紹和安裝

Backtrader的特點,就是兩點:

1、易于使用;

2、參見第1條。

那麼如何使用Backtrader呢?比把大象裝進冰箱複雜點,一共4步:

建立一個Cerebro引擎:

1、加入一個Strategy。

2、加載資料。

3、執行:cerebro.run()。

4、對執行結果可視化。

就是這麼簡單!

這麼簡單如何執行那麼多複雜的量化政策,關鍵就是Backtrader作為一個平台,具有極高的可配置性,也就是可以根據需要進行不同的配置,完成不同的量化政策回測,後續将進行較長的描述。

安裝Backtrader

pip install backtrader
           

四.編寫代碼

本次使用pycharm軟體作為python開發環境。

1、初始化tushare,擷取指定股票代碼的股票曆史資料。

token = '你複制下來的token'
ts.set_token(token)
pro = ts.pro_api(timeout=60)
# 指定股票代碼
ts_code = '000400.SZ'
code = '000400'
start_date = '20200101'
# 擷取資料
def get_data(start):
    df = ts.pro_bar(ts_code=ts_code, adj='qfq', start_date=start)
    df = df.iloc[::-1]
    df.index = pd.to_datetime(df.trade_date)
    df['openinterest'] = 0
    df = df[['open', 'high', 'low', 'close', 'vol', 'openinterest']]
    df = df.rename(columns={'vol': 'volume'})
    return df
           

2、加載資料

start_time = '2020-01-01'
accept_date = getdate(1)  # 查找這個日期是買入賣出點的股票
start = datetime.datetime.strptime(start_time, "%Y-%m-%d")
end = datetime.datetime.strptime(accept_date, "%Y-%m-%d")
buy_count = 0   # 買入次數
sell_count = 0   # 賣出次數
k_line_data = get_data(start.date().strftime("%Y%M%D"))
print(k_line_data)
k_line_data.to_csv("csvfile\\" + ts_code + ".csv")
data = bt.feeds.PandasData(dataname=k_line_data, fromdate=start, todate=end)
           

3、加載backtrader引擎,初始化投資金額

# 加載backtrader引擎
back_trader = bt.Cerebro()
# 将資料傳入
back_trader.adddata(data)
# 政策加進來
back_trader.addsizer(bt.sizers.FixedSize, stake=2000)
# 設定以收盤價成交,作弊模式
back_trader.broker.set_coc(True)
# 賬号資金初始化
startCash = 100000
back_trader.broker.set_cash(startCash)
# 設定手續費
back_trader.broker.setcommission(commission=0.001)
           

4、增加政策

# 布林線規則:跌破下軌,買入;超過上軌,賣出
back_trader.addstrategy(boll_strategy)
           

5、布林線規則政策的具體實作

# 定義政策
class boll_strategy(bt.Strategy):
    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print('%s,%s' % (dt.isoformat(), txt))

    def __init__(self):
        # 指定價格序列
        self.dataclose = self.datas[0].close

        #交易訂單狀态初始化
        self.order = None

        #計算布林線
        ##使用自帶的indicators中自帶的函數計算出支撐線和壓力線,period設定周期,預設是20
        self.lines.top = bt.indicators.BollingerBands(self.datas[0], period=20).top
        self.lines.bot = bt.indicators.BollingerBands(self.datas[0], period=20).bot

    def next(self):
        # 檢查訂單狀态
        if self.order:
            print("等待成交")
            return

        # 檢查持倉
        if not self.position:
            # 沒有持倉,買入開倉
            if self.dataclose <= self.lines.bot[0]:
                print("================")
                print("收盤價跌破lower線,執行買入")
                self.order = self.buy()
        else:
            # 手裡有持倉,判斷賣平
            if self.dataclose >= self.lines.top[0]:
                print("======================")
                print("收盤價超過upper線,執行賣出")
                self.order = self.sell()

    def notify(self, order):

        if order.status in [order.Submitted, order.Accepted]:
            if order.status in [order.Submitted]:
                self.log("送出訂單......")
            if order.status in [order.Accepted]:
                self.log("接受訂單......")
            return

        # Check if an order has been completed
        # Attention: broker could reject order if not enougth cash
        if order.status in [order.Completed, order.Canceled, order.Margin]:
            if order.isbuy():
                self.log('執行買入, %.2f' % order.executed.price)
                gloVar.buy_count = gloVar.buy_count + 1
            elif order.issell():
                self.log('執行賣出, %.2f' % order.executed.price)
                gloVar.sell_count = gloVar.sell_count + 1
            self.bar_executed = len(self)

        self.log("訂單完成......")
        print("======================")
        # Write down: no pending order
        self.order = None
           

6、輸出回測結果并列印圖形

# 輸出初始化資料
d1 = start.date().strftime("%Y-%m-%d")
d2 = end.date().strftime("%Y-%m-%d")
print(f'初始化資金:{startCash},回測時間:{d1}:{d2}')
# 開啟回測
result = back_trader.run()

# Print out the final result
print('最終資金: %.2f' % back_trader.broker.getvalue())
profit_ratio = (int(back_trader.broker.getvalue()) - startCash) / startCash * 100
print('投資收益率: %.2f%%' % profit_ratio)
print('買入次數:%s ;賣出次數:%s' % (gloVar.buy_count, gloVar.sell_count))
print("股票代碼:%s,%s淨資産收益率:%s%%" % (ts_code, profit_time, roe))
# Plot the result
back_trader.plot(style='candlestick')
           

五.運作結果

從下面的執行結果,可以清晰看到本次投資股票的投資收益率和交易次數:

最終資金: 106992.30
投資收益率: 6.99%
買入次數:6 ;賣出次數:6
股票代碼:000400.SZ,淨資産收益率:%
           

輸出交易圖形:

通過Tushare和backtrader實作量化投資回測一.Tushare介紹二.安裝Tushare三.backtrader介紹和安裝四.編寫代碼五.運作結果