简体   繁体   English

ValueError:日期超出了 backtrader 中发生的月份的范围

[英]ValueError: day is out of range for month occuring in backtrader

Please help with this error, this is the error I am getting while feeding my own csv data to the backtrader.请帮助解决此错误,这是我将自己的 csv 数据提供给 backtrader 时遇到的错误。

data sample is as follows数据样本如下

csv数据样本

I am new to python and the python community我是 python 和 python 社区的新手

error:错误:

C:\\Python\\python.exe C:\\Users\\harif\\PycharmProjects\\untitled\\venv\\learning\\dataframe1.py Traceback (most recent call last): File "C:\\Users\\harif\\PycharmProjects\\untitled\\venv\\learning\\dataframe1.py", line 32, in fromdate=datetime(2, 10, 2016), ValueError: day is out of range for month C:\\Python\\python.exe C:\\Users\\harif\\PycharmProjects\\untitled\\venv\\learning\\dataframe1.py Traceback(最近一次调用):文件“C:\\Users\\harif\\PycharmProjects\\untitled\\venv\\learning \\dataframe1.py", line 32, in fromdate=datetime(2, 10, 2016), ValueError: day is out of range for month

Process finished with exit code 1进程以退出代码 1 结束

import backtrader as bt


# Create a subclass of Strategy to define the indicators and logic

class SmaCross(bt.Strategy):
    # list of parameters which are configurable for the strategy
    params = dict(
        pfast=10,  # period for the fast moving average
        pslow=30  # period for the slow moving average
    )

    def __init__(self):
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal

    def next(self):
        if not self.position:  # not in the market
            if self.crossover > 0:  # if fast crosses slow to the upside
                self.buy()  # enter long

        elif self.crossover < 0:  # in the market & cross to the downside
            self.close()  # close long position


cerebro = bt.Cerebro()  # create a "Cerebro" engine instance

# Create a data feed
data = bt.feeds.GenericCSVData(dataname=r'C:\Hard_Drive\Tick_Data\tickdata_2\sp.csv',
                               fromdate=datetime(2, 10, 2016),
                               todate=datetime(1, 10, 2019))
print(data)
# cerebro.adddata(data)  # Add the data feed

# cerebro.addstrategy(SmaCross)  # Add the trading strategy
# cerebro.run()  # run it all
# cerebro.plot()  # and plot it with a single command

Date time object accepts values in this order.日期时间对象按此顺序接受值。

datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]

There are 2 ways of fixing this.有 2 种方法可以解决此问题。

  1. You can write the values in the correct order.您可以按正确的顺序写入值。 eg: datetime(2016, 10, 2)例如: datetime(2016, 10, 2)
  2. You can specify which value is what.您可以指定哪个值是什么。 eg: datetime(day=2, month=10, year=2016),例如: datetime(day=2, month=10, year=2016),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM