BackTrader 中文文档(二十一)(1)https://developer.aliyun.com/article/1505416
让我们滚动
注意
示例中的默认行为是使用cerebro.rolloverdata。可以通过传递-no-cerebro标志来更改。在这种情况下,示例使用RollOver和cerebro.adddata
实现包括一个示例,可在backtrader源代码中找到。
期货连接
让我们从纯连接开始,运行示例而不带任何参数。
$ ./rollover.py Len, Name, RollName, Datetime, WeekDay, Open, High, Low, Close, Volume, OpenInterest 0001, FESX, 199FESXM4, 2013-09-26, Thu, 2829.0, 2843.0, 2829.0, 2843.0, 3.0, 1000.0 0002, FESX, 199FESXM4, 2013-09-27, Fri, 2842.0, 2842.0, 2832.0, 2841.0, 16.0, 1101.0 ... 0176, FESX, 199FESXM4, 2014-06-20, Fri, 3315.0, 3324.0, 3307.0, 3322.0, 134777.0, 520978.0 0177, FESX, 199FESXU4, 2014-06-23, Mon, 3301.0, 3305.0, 3265.0, 3285.0, 730211.0, 3003692.0 ... 0241, FESX, 199FESXU4, 2014-09-19, Fri, 3287.0, 3308.0, 3286.0, 3294.0, 144692.0, 566249.0 0242, FESX, 199FESXZ4, 2014-09-22, Mon, 3248.0, 3263.0, 3231.0, 3240.0, 582077.0, 2976624.0 ... 0306, FESX, 199FESXZ4, 2014-12-19, Fri, 3196.0, 3202.0, 3131.0, 3132.0, 226415.0, 677924.0 0307, FESX, 199FESXH5, 2014-12-22, Mon, 3151.0, 3177.0, 3139.0, 3168.0, 547095.0, 2952769.0 ... 0366, FESX, 199FESXH5, 2015-03-20, Fri, 3680.0, 3698.0, 3672.0, 3695.0, 147632.0, 887205.0 0367, FESX, 199FESXM5, 2015-03-23, Mon, 3654.0, 3655.0, 3608.0, 3618.0, 802344.0, 3521988.0 ... 0426, FESX, 199FESXM5, 2015-06-18, Thu, 3398.0, 3540.0, 3373.0, 3465.0, 1173246.0, 811805.0 0427, FESX, 199FESXM5, 2015-06-19, Fri, 3443.0, 3499.0, 3440.0, 3488.0, 104096.0, 516792.0
这使用cerebro.chaindata,结果应该很清楚:
- 每当一个数据源结束时,下一个数据源接管
- 这总是在星期五和星期一之间发生:示例中的期货总是在星期五到期
期货滚动没有检查
让我们执行--rollover
$ ./rollover.py --rollover --plot Len, Name, RollName, Datetime, WeekDay, Open, High, Low, Close, Volume, OpenInterest 0001, FESX, 199FESXM4, 2013-09-26, Thu, 2829.0, 2843.0, 2829.0, 2843.0, 3.0, 1000.0 0002, FESX, 199FESXM4, 2013-09-27, Fri, 2842.0, 2842.0, 2832.0, 2841.0, 16.0, 1101.0 ... 0176, FESX, 199FESXM4, 2014-06-20, Fri, 3315.0, 3324.0, 3307.0, 3322.0, 134777.0, 520978.0 0177, FESX, 199FESXU4, 2014-06-23, Mon, 3301.0, 3305.0, 3265.0, 3285.0, 730211.0, 3003692.0 ... 0241, FESX, 199FESXU4, 2014-09-19, Fri, 3287.0, 3308.0, 3286.0, 3294.0, 144692.0, 566249.0 0242, FESX, 199FESXZ4, 2014-09-22, Mon, 3248.0, 3263.0, 3231.0, 3240.0, 582077.0, 2976624.0 ... 0306, FESX, 199FESXZ4, 2014-12-19, Fri, 3196.0, 3202.0, 3131.0, 3132.0, 226415.0, 677924.0 0307, FESX, 199FESXH5, 2014-12-22, Mon, 3151.0, 3177.0, 3139.0, 3168.0, 547095.0, 2952769.0 ... 0366, FESX, 199FESXH5, 2015-03-20, Fri, 3680.0, 3698.0, 3672.0, 3695.0, 147632.0, 887205.0 0367, FESX, 199FESXM5, 2015-03-23, Mon, 3654.0, 3655.0, 3608.0, 3618.0, 802344.0, 3521988.0 ... 0426, FESX, 199FESXM5, 2015-06-18, Thu, 3398.0, 3540.0, 3373.0, 3465.0, 1173246.0, 811805.0 0427, FESX, 199FESXM5, 2015-06-19, Fri, 3443.0, 3499.0, 3440.0, 3488.0, 104096.0, 516792.0
相同的行为。可以清楚地看到合同更改是在 3 月、6 月、9 月、12 月的第 3 个星期五进行的。
但这大多是错误的。backtradr不可能知道,但作者知道EuroStoxx 50期货在12:00 CET 停止交易。因此,即使到期月份的第 3 个星期五有每日条形图,更改发生得太晚。
在一周内更改
示例中实现了一个checkdate可调用对象,用于计算当前活跃合同的到期日期。
checkdate将在月份的第 3 个星期五到来时(例如,如果星期一是银行假日,则可能是星期二)进行滚动。
$ ./rollover.py --rollover --checkdate --plot Len, Name, RollName, Datetime, WeekDay, Open, High, Low, Close, Volume, OpenInterest 0001, FESX, 199FESXM4, 2013-09-26, Thu, 2829.0, 2843.0, 2829.0, 2843.0, 3.0, 1000.0 0002, FESX, 199FESXM4, 2013-09-27, Fri, 2842.0, 2842.0, 2832.0, 2841.0, 16.0, 1101.0 ... 0171, FESX, 199FESXM4, 2014-06-13, Fri, 3283.0, 3292.0, 3253.0, 3276.0, 734907.0, 2715357.0 0172, FESX, 199FESXU4, 2014-06-16, Mon, 3261.0, 3275.0, 3252.0, 3262.0, 180608.0, 844486.0 ... 0236, FESX, 199FESXU4, 2014-09-12, Fri, 3245.0, 3247.0, 3220.0, 3232.0, 650314.0, 2726874.0 0237, FESX, 199FESXZ4, 2014-09-15, Mon, 3209.0, 3224.0, 3203.0, 3221.0, 153448.0, 983793.0 ... 0301, FESX, 199FESXZ4, 2014-12-12, Fri, 3127.0, 3143.0, 3038.0, 3042.0, 1409834.0, 2934179.0 0302, FESX, 199FESXH5, 2014-12-15, Mon, 3041.0, 3089.0, 2963.0, 2980.0, 329896.0, 904053.0 ... 0361, FESX, 199FESXH5, 2015-03-13, Fri, 3657.0, 3680.0, 3627.0, 3670.0, 867678.0, 3499116.0 0362, FESX, 199FESXM5, 2015-03-16, Mon, 3594.0, 3641.0, 3588.0, 3629.0, 250445.0, 1056099.0 ... 0426, FESX, 199FESXM5, 2015-06-18, Thu, 3398.0, 3540.0, 3373.0, 3465.0, 1173246.0, 811805.0 0427, FESX, 199FESXM5, 2015-06-19, Fri, 3443.0, 3499.0, 3440.0, 3488.0, 104096.0, 516792.0
好多了。现在滚动发生在5 天前。快速查看Len指数就可以看到。例如:
199FESXM4到199FESXU4发生在len171-172。没有checkdate时发生在176-177
滚动将在到期月份的第 3 个星期五之前的星期一发生。
添加成交量条件
即使有改进,情况仍然可以进一步改善,不仅日期,而且协商的成交量也将被考虑在内。当新合同的交易量超过当前活跃合同时进行切换。
让我们添加一个checkcondition并运行。
$ ./rollover.py --rollover --checkdate --checkcondition --plot Len, Name, RollName, Datetime, WeekDay, Open, High, Low, Close, Volume, OpenInterest 0001, FESX, 199FESXM4, 2013-09-26, Thu, 2829.0, 2843.0, 2829.0, 2843.0, 3.0, 1000.0 0002, FESX, 199FESXM4, 2013-09-27, Fri, 2842.0, 2842.0, 2832.0, 2841.0, 16.0, 1101.0 ... 0175, FESX, 199FESXM4, 2014-06-19, Thu, 3307.0, 3330.0, 3300.0, 3321.0, 717979.0, 759122.0 0176, FESX, 199FESXU4, 2014-06-20, Fri, 3309.0, 3318.0, 3290.0, 3298.0, 711627.0, 2957641.0 ... 0240, FESX, 199FESXU4, 2014-09-18, Thu, 3249.0, 3275.0, 3243.0, 3270.0, 846600.0, 803202.0 0241, FESX, 199FESXZ4, 2014-09-19, Fri, 3273.0, 3293.0, 3250.0, 3252.0, 1042294.0, 3021305.0 ... 0305, FESX, 199FESXZ4, 2014-12-18, Thu, 3095.0, 3175.0, 3085.0, 3172.0, 1309574.0, 889112.0 0306, FESX, 199FESXH5, 2014-12-19, Fri, 3195.0, 3200.0, 3106.0, 3147.0, 1329040.0, 2964538.0 ... 0365, FESX, 199FESXH5, 2015-03-19, Thu, 3661.0, 3691.0, 3646.0, 3668.0, 1271122.0, 1054639.0 0366, FESX, 199FESXM5, 2015-03-20, Fri, 3607.0, 3664.0, 3595.0, 3646.0, 1182235.0, 3407004.0 ... 0426, FESX, 199FESXM5, 2015-06-18, Thu, 3398.0, 3540.0, 3373.0, 3465.0, 1173246.0, 811805.0 0427, FESX, 199FESXM5, 2015-06-19, Fri, 3443.0, 3499.0, 3440.0, 3488.0, 104096.0, 516792.0
更好了*。我们已将切换日期移至众所周知的到期月份第 3 个星期五之前的星期四
这应该不会让人感到惊讶,因为到期的期货在那个星期五交易时间更少,成交量必须很小。
注意
通过checkdate可调用函数,到那个星期四也可以设置为滚动日期。但这并不是示例的重点。
结论
backtrader 现在包含了一个灵活的机制,允许滚动期货以创建连续流。
使用示例
$ ./rollover.py --help usage: rollover.py [-h] [--no-cerebro] [--rollover] [--checkdate] [--checkcondition] [--plot [kwargs]] Sample for Roll Over of Futures optional arguments: -h, --help show this help message and exit --no-cerebro Use RollOver Directly (default: False) --rollover --checkdate Change during expiration week (default: False) --checkcondition Change when a given condition is met (default: False) --plot [kwargs], -p [kwargs] Plot the read data applying any kwargs passed For example: --plot style="candle" (to plot candles) (default: None)
示例代码
from __future__ import (absolute_import, division, print_function, unicode_literals) import argparse import bisect import calendar import datetime import backtrader as bt class TheStrategy(bt.Strategy): def start(self): header = ['Len', 'Name', 'RollName', 'Datetime', 'WeekDay', 'Open', 'High', 'Low', 'Close', 'Volume', 'OpenInterest'] print(', '.join(header)) def next(self): txt = list() txt.append('%04d' % len(self.data0)) txt.append('{}'.format(self.data0._dataname)) # Internal knowledge ... current expiration in use is in _d txt.append('{}'.format(self.data0._d._dataname)) txt.append('{}'.format(self.data.datetime.date())) txt.append('{}'.format(self.data.datetime.date().strftime('%a'))) txt.append('{}'.format(self.data.open[0])) txt.append('{}'.format(self.data.high[0])) txt.append('{}'.format(self.data.low[0])) txt.append('{}'.format(self.data.close[0])) txt.append('{}'.format(self.data.volume[0])) txt.append('{}'.format(self.data.openinterest[0])) print(', '.join(txt)) def checkdate(dt, d): # Check if the date is in the week where the 3rd friday of Mar/Jun/Sep/Dec # EuroStoxx50 expiry codes: MY # M -> H, M, U, Z (Mar, Jun, Sep, Dec) # Y -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 -> year code. 5 -> 2015 MONTHS = dict(H=3, M=6, U=9, Z=12) M = MONTHS[d._dataname[-2]] centuria, year = divmod(dt.year, 10) decade = centuria * 10 YCode = int(d._dataname[-1]) Y = decade + YCode if Y < dt.year: # Example: year 2019 ... YCode is 0 for 2020 Y += 10 exp_day = 21 - (calendar.weekday(Y, M, 1) + 2) % 7 exp_dt = datetime.datetime(Y, M, exp_day) # Get the year, week numbers exp_year, exp_week, _ = exp_dt.isocalendar() dt_year, dt_week, _ = dt.isocalendar() # print('dt {} vs {} exp_dt'.format(dt, exp_dt)) # print('dt_week {} vs {} exp_week'.format(dt_week, exp_week)) # can switch if in same week return (dt_year, dt_week) == (exp_year, exp_week) def checkvolume(d0, d1): return d0.volume[0] < d1.volume[0] # Switch if volume from d0 < d1 def runstrat(args=None): args = parse_args(args) cerebro = bt.Cerebro() fcodes = ['199FESXM4', '199FESXU4', '199FESXZ4', '199FESXH5', '199FESXM5'] store = bt.stores.VChartFile() ffeeds = [store.getdata(dataname=x) for x in fcodes] rollkwargs = dict() if args.checkdate: rollkwargs['checkdate'] = checkdate if args.checkcondition: rollkwargs['checkcondition'] = checkvolume if not args.no_cerebro: if args.rollover: cerebro.rolloverdata(name='FESX', *ffeeds, **rollkwargs) else: cerebro.chaindata(name='FESX', *ffeeds) else: drollover = bt.feeds.RollOver(*ffeeds, dataname='FESX', **rollkwargs) cerebro.adddata(drollover) cerebro.addstrategy(TheStrategy) cerebro.run(stdstats=False) if args.plot: pkwargs = dict(style='bar') if args.plot is not True: # evals to True but is not True npkwargs = eval('dict(' + args.plot + ')') # args were passed pkwargs.update(npkwargs) cerebro.plot(**pkwargs) def parse_args(pargs=None): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Sample for Roll Over of Futures') parser.add_argument('--no-cerebro', required=False, action='store_true', help='Use RollOver Directly') parser.add_argument('--rollover', required=False, action='store_true') parser.add_argument('--checkdate', required=False, action='store_true', help='Change during expiration week') parser.add_argument('--checkcondition', required=False, action='store_true', help='Change when a given condition is met') # Plot options parser.add_argument('--plot', '-p', nargs='?', required=False, metavar='kwargs', const=True, help=('Plot the read data applying any kwargs passed\n' '\n' 'For example:\n' '\n' ' --plot style="candle" (to plot candles)\n')) if pargs is not None: return parser.parse_args(pargs) return parser.parse_args() if __name__ == '__main__': runstrat()
信用利息
原文:
www.backtrader.com/blog/posts/2016-08-22-credit-interest/credit-interest/
在一些情况下,真实经纪人的现金金额可能会减少,因为资产操作包括利率。例如:
- 股票的空头卖出
- ETFs 长和短
这意味着不仅交易构成了系统的盈利,因为信用的利息也在消耗账户。
为了涵盖这种情况,backtrader在1.8.8.96版本开始(功能)可以考虑到这一点。
扩展 CommissionInfo
即使与任何order/trade无关,从账户中扣除现金的折扣可以被建模为经纪人收取的佣金。因此,鉴于backtrader已经提供了灵活和可扩展的佣金系统,该系统已稍微扩展以支持credit interest。
现在可以使用两个新参数实例化 CommissionInfo:
interest(默认:0.0)
如果这个值不为零,那么这就是持有空头寸时收取的年利率。这主要是为了股票空头卖出
公式:days \* price \* abs(size) \* (interest / 365)
必须以绝对值指定:0.05 -> 5%
注意
通过覆盖方法_get_credit_interest可以改变行为interest_long(默认:False)
一些产品(如 ETFs)无论是空头还是多头都会收取利息。如果这是True并且interest不为零,则会对两个方向收取利息。
参数也可以通过broker使用以下方法设置:
def setcommission(self, commission=0.0, margin=None, mult=1.0, commtype=None, percabs=True, stocklike=False, interest=0.0, interest_long=False, name=None)
其中 interest 和 interest_long 显然与上文的含义相同。
应用一个 CommissionInfo
对于佣金百分比的股票,带有credit interest的典型使用场景如下
import backtrader as bt cerebro = bt.Cerebro() comminfo = bt.CommissionInfo(commtype=bt.CommissionInfo.COMM_PERC, # % commission commission=0.005, # 0.5% percabs=True, # perc expressed in abs terms stocklike=True, interest=0.05, # 5% anual credit interest rate ) cerebro.broker.addcommissioninfo(comminfo) ...
如果最终用户有自己的佣金方案,这将非常有用。
一个更简单的案例与setcommission:
import backtrader as bt cerebro = bt.Cerebro() cerebro.broker.setcommission(commtype=bt.CommissionInfo.COMM_PERC, # % commission commission=0.005, # 0.5% percabs=True, # perc expressed in abs terms stocklike=True, interest=0.05, # 5% anual credit interest rate ) ...
其余的和任何其他常规的backtrader脚本一样。
一些样本场景
仅限long,无退出,无利息
为了建立一个最低基线,让我们先不要利息,只让脚本进入市场并避免退出。
$ ./credit-interest.py --plot --stocklike --long --no-exit 01 2005-04-11 23:59:59 BUY Size: +10 / Price: 3088.47
现在应该很清楚了。从总投资组合价值中有一条平直的现金线,不显示任何扣除。
仅限long,无退出和利息
让我们尝试添加利息,看看会发生什么(我们将添加一个巨大的15%利息来尝试注意到这些动向)
$ ./credit-interest.py --plot --stocklike --long --no-exit --interest 0.15 01 2005-04-11 23:59:59 BUY Size: +10 / Price: 3088.47
什么都没变!这是意料之中的。在大多数情况下,利息只适用于short头寸(使用信用卖出)而这是一个long-only头寸。
让我们告诉脚本也要为long头寸做这个
$ ./credit-interest.py --plot --stocklike --long --no-exit --interest 0.15 --interest_long 01 2005-04-11 23:59:59 BUY Size: +10 / Price: 3088.47
改变已经存在。有一个减少,并且很大(鉴于正在收取的利息很大)
BackTrader 中文文档(二十一)(3)https://developer.aliyun.com/article/1505419