backtrader不理解策略迭代表,就无法彻底理解多股操作

技术教程《扫地僧Backtrader给力教程系列一:股票量化回测核心篇》

backtrader文档本身并没有提出“策略迭代表”这个概念,这是我们在自编教程中提出的概念。在多股操作时,必须理解涉及多股的策略迭代表中数据的对齐方式,否则你就无法理解一些运行现象。比如下面这位的问题就是没有理解这个概念而造成困惑。

 

backtrader论坛上有人提了一个问题,见这里,他写了段简单的测试代码,如下。向策略加了两个行情数据,data0是指数(沪深300),data1是股票000001.SZ。在next中每迭代到一个bar,输出data0的日期,data1的收盘价等。

class TestStrategy(bt.Strategy):

    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

    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f, open, %.2f, cash, %.2f' % (self.datas[1].close[0],self.datas[1].open[0],cerebro.broker.getcash()))
        self.buy(self.datas[1])


# if __name__ == '__main__':
    # Create a cerebro entity
cerebro = bt.Cerebro()

# Add a strategy


# Datas are in a subfolder of the samples. Need to find where the script is
# because it could have been called from anywhere
# modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
# datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')
idxpath = ('data2/idx300.csv')
fromdate=datetime(2013, 1, 4)
todate=datetime(2013, 12, 31)
top_buyers=10
keep_buyers=50
universe_size=100

idx = bt.feeds.GenericCSVData(
            dataname=idxpath,
            name="idx300",
            dtformat ="%Y-%m-%d",
            # Do not pass values before this date
            fromdate=fromdate,
            todate=todate,
            openinterest=-1)
# spy = bt.feeds.YahooFinanceData(dataname='SPY',
#                                  fromdate=datetime(2012,2,28),
#                                  todate=datetime(2018,2,28),
#                                  plot=False)
cerebro.adddata(idx,timeframe=bt.TimeFrame.Days)  # add 沪深300 Index
ticker="000001.SZ"

df = pd.read_csv(f"data2/{ticker}.csv",
             parse_dates=True,
             usecols=[1,2,3,4,5],
             index_col=0).dropna(axis=0)
df[~df.index.duplicated()]
df=df.iloc[::-1]
df=df.loc[fromdate:todate]
cerebro.adddata(bt.feeds.PandasData(dataname=df,name=ticker, plot=False),timeframe=bt.TimeFrame.Days)

cerebro.addstrategy(TestStrategy)

# Set our desired cash start
cerebro.broker.setcash(100000.0)

# Print out the starting conditions
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

# Run over everything
cerebro.run()

# Print out the final result
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

输出结果

Starting Portfolio Value: 100000.00
2013-01-04, Close, 5.21, open, 5.32, cash, 100000.00
2013-01-04, Close, 5.31, open, 5.21, cash, 99994.79
2013-01-07, Close, 5.31, open, 5.21, cash, 99994.79
2013-01-07, Close, 5.21, open, 5.31, cash, 99984.18
2013-01-08, Close, 5.21, open, 5.31, cash, 99984.18
2013-01-08, Close, 5.17, open, 5.20, cash, 99973.78
2013-01-09, Close, 5.17, open, 5.20, cash, 99973.78
2013-01-09, Close, 5.17, open, 5.17, cash, 99963.45
2013-01-10, Close, 5.17, open, 5.17, cash, 99963.45
2013-01-10, Close, 5.06, open, 5.17, cash, 99953.11

他的问题是,为何输出结果中的日期会同一天重复两次。他预期应该是每天一条记录。

这个问题请参考我们教程中如下两节内容,1.2是简单的涉及单支股票的策略迭代表,11.2是复杂的涉及多支股票的策略迭代表。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扫地僧量化

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值