其他分享
首页 > 其他分享> > backtrader进行期货回测要注意的问题:保证金等设置,拼接滚动合约

backtrader进行期货回测要注意的问题:保证金等设置,拼接滚动合约

作者:互联网

点此获取backtrader技术教程

==================

很多同学问如何用backtrader进行期货回测。以下给个例子,与普通股票回测不同的是佣金的设置方式。

import datetime  # For datetime objects
import backtrader as bt
import backtrader.feeds as btfeeds
import backtrader.indicators as btind
import pandas as pd
import numpy as np
from datetime import datetime
class Par_SAR(bt.Strategy):
    params = (('period', 2), ('af', 0.02), ('afmax', 0.2))

    def __init__(self):
       pass
       



if __name__ == '__main__':
    # rb 15 min data 
    brf_min_bar = bt.feeds.GenericCSVData(
        dataname='E:/Quant/Backtrader/backtrader-master/China_Market/data/rb_15m.csv',
        timeframe=bt.TimeFrame.Minutes,
        #fromdate=datetime.datetime(2019, 5, 1),
        #todate=datetime.datetime(2020, 6, 1),
        nullvalue=0.0,
        dtformat=('%Y-%m-%d %H:%M:%S'),
        datetime=1,
        time=-1,
        high=4,
        low=5,
        open=3,
        close=6,
        volume=-1,
        # openinterest=-1
    )
    # Add the Data Feed to Cerebro
    cerebro.adddata(brf_min_bar)
    #cerebro.resampledata(brf_min_bar, timeframe=bt.TimeFrame.Days)

    # Add strategy
    cerebro.addstrategy(Par_SAR)
    # 设置初始资本为100,000
    cerebro.broker.setcash(1000000.0) 

    # 设置期货佣金模式
    cerebro.broker.setcommission(commission=0.0001, margin=2800.0, mult=10.0)

    cerebro.run()

以上佣金设置,实际上使用了backtrader内置的佣金类CommInfoBase,该类可设置的参数如下。当然,多数参数采用默认值即可,无需设置,如以上案例,只设置了3个参数,其他都是默认值。以下参数中的leverage,可能与期货也有关系。另外,该类也可以考虑借款利息。

Params:

 

If this param is set to something else than None, then it will be passed to the internal _commtype attribute and the same will be done with the param stocklike and the internal attribute _stocklike

另外,backtrader还允许将不同到期日的期货合约滚动拼接起来形成连续期货(The RollOver Data Feed),例子如下

import backtrader as bt

cerebro = bt.Cerebro()
data0 = bt.feeds.MyFeed(dataname='Expiry0')
data1 = bt.feeds.MyFeed(dataname='Expiry1')
...
dataN = bt.feeds.MyFeed(dataname='ExpiryN')

drollover = bt.feeds.RollOver(data0, data1, ..., dataN, dataname='MyRoll', **kwargs)
cerebro.adddata(drollover)

cerebro.run()

RollOver类有两个参数控制如何拼接合约,checkdate和 checkcondition。详细描述参考 Data Feeds - Rollover - Backtrader

标签:set,backtrader,cerebro,datetime,bt,回测,拼接,def
来源: https://blog.csdn.net/qtbgo/article/details/116082418