量化交易回測框架Backtrader使用框架的Sizers和自定義參數(shù)

簡介

框架默認(rèn)是每次購買的單位是1,按照美國的股票規(guī)則來的,實(shí)際上交易所的最小交易單位不一樣,比如國內(nèi)股票一手是證券市場的一個(gè)交易的最低限額,在中國上海證券交易所和深圳證券交易所的規(guī)定中,一手等于一百股。港股交易的每手股數(shù)是不固定的(各個(gè)上市公司自行決定一手是多少股),不同的股票規(guī)定數(shù)是不同的。那么通過什么可以修改購買多少呢。實(shí)例代碼具體可以參看Backtrader官方文檔quickstart

目標(biāo)

  1. 為策略增加自定義參數(shù)
  2. 修改默認(rèn)購買和賣出股票數(shù)量

原理

  1. 可以通過框架提供的Sizers的FixedSize設(shè)置每次默認(rèn)購買多少。比如設(shè)立設(shè)置了100股
    sizers.FixedSize, stake=100
  2. 通過給自定義strategy增加params成員變量,在對象初始化時(shí)賦值即可

實(shí)踐

自定義策略類

#############################################################
#class
#############################################################
# Create a Stratey
class TestStrategy(bt.Strategy):
    # 自定義均線的實(shí)踐間隔,默認(rèn)是5天
    params = (
        ('maperiod', 5),
    )
    def log(self, txt, dt=None):
        ''' Logging function for this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close
        # To keep track of pending orders
        self.order = None
        # buy price
        self.buyprice = None
        # buy commission
        self.buycomm = None
        # 增加均線,簡單移動(dòng)平均線(SMA)又稱“算術(shù)移動(dòng)平均線”,是指對特定期間的收盤價(jià)進(jìn)行簡單平均化
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.maperiod)
    #訂單狀態(tài)改變回調(diào)方法 be notified through notify_order(order) of any status change in an order
    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return
        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            elif order.issell():
               self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))
            self.bar_executed = len(self)
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')
        # Write down: no pending order
        self.order = None

    #交易狀態(tài)改變回調(diào)方法 be notified through notify_trade(trade) of any opening/updating/closing trade
    def notify_trade(self, trade):
        if not trade.isclosed:
            return
        # 每筆交易收益 毛利和凈利
        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))

    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f' % self.dataclose[0])
        # Check if an order is pending ... if yes, we cannot send a 2nd one
        if self.order:
            return
        # Check if we are in the market(當(dāng)前賬戶持股情況,size,price等等)
        if not self.position:
            # Not yet ... we MIGHT BUY if ...
            if self.dataclose[0] >= self.sma[0]:
                #當(dāng)收盤價(jià),大于等于均線的價(jià)格
                # BUY, BUY, BUY!!! (with all possible default parameters)
                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                # Keep track of the created order to avoid a 2nd order
                self.order = self.buy()
        else:
            # Already in the market ... we might sell
            if self.dataclose[0] < self.sma[0]:
                #當(dāng)收盤價(jià),小于均線價(jià)格
                # SELL, SELL, SELL!!! (with all possible default parameters)
                self.log('SELL CREATE, %.2f' % self.dataclose[0])
                # Keep track of the created order to avoid a 2nd order
                self.order = self.sell()

增加了sizers的main

########################################################################
#main
########################################################################
if __name__ == '__main__':
    # Create a cerebro entity(創(chuàng)建cerebro)
    cerebro = bt.Cerebro()
    # Add a strategy(加入自定義策略,可以設(shè)置自定義參數(shù),方便調(diào)節(jié))
    cerebro.addstrategy(TestStrategy, maperiod=7)
    # Get a pandas dataframe(獲取dataframe格式股票數(shù)據(jù))
    feedsdf = get_dataframe()
    # Pass it to the backtrader datafeed and add it to the cerebro(加入數(shù)據(jù))
    data = bt.feeds.PandasData(dataname=feedsdf)
    cerebro.adddata(data)
    # Add a FixedSize sizer according to the stake(國內(nèi)1手是100股,最小的交易單位)
    cerebro.addsizer(bt.sizers.FixedSize, stake=100)
    # Set our desired cash start(給經(jīng)紀(jì)人,可以理解為交易所股票賬戶充錢)
    cerebro.broker.setcash(10000.0)
     # Set the commission - 0.1%(設(shè)置交易手續(xù)費(fèi),雙向收取)
    cerebro.broker.setcommission(commission=0.001)
    # Print out the starting conditions(輸出賬戶金額)
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    # Run over everything(執(zhí)行回測)
    cerebro.run()
    # Print out the final result(輸出賬戶金額)
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

分析

這里注意自定義strategy類和main中間的增加的方法即可

源碼

全代碼請到github上clone了。github地址:[qtbt](https://github.com/horacepei/qtbt.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 金融知識大全(最全整理版) 本文實(shí)戰(zhàn)財(cái)經(jīng) 轉(zhuǎn)自 優(yōu)維金融空間,轉(zhuǎn)載請注明來源! 第一部分:銀行系金融知識大全! 1...
    cnnjzc閱讀 6,906評論 0 14
  • 項(xiàng)目地址:https://github.com/ricequant/rqalpha/ RQAlpha 簡介 RQA...
    Ricequant閱讀 10,466評論 1 10
  • 文|謝小瘋 4.許是舊人重逢 裂山散人轉(zhuǎn)過頭去,正是那送扇歸來的陳渙陳懷禮,陳渙重逢舊友,喜悅之情溢于言表,笑道:...
    謝小凡閱讀 463評論 2 2
  • 陳煒,焦點(diǎn)網(wǎng)絡(luò)初級11期,堅(jiān)持分享第31天20180907又出狀況,上午老師打電話說孩子跟高年級同學(xué)打起來了,趕緊...
    陳_8749閱讀 159評論 0 0
  • 江柏文:美紀(jì)要波瀾不驚黃金將繼續(xù)震蕩?虧損3大征兆你意想不到! 金融市場變化莫測黃金投資爆倉有哪幾種征兆?很多投資...
    江柏文閱讀 217評論 0 0

友情鏈接更多精彩內(nèi)容