【问题标题】:ValueError: day is out of range for month occuring in backtraderValueError:在 backtrader 中出现的日期超出月份的范围
【发布时间】:2020-01-14 10:21:09
【问题描述】:

请帮助解决这个错误,这是我在将自己的 csv 数据提供给反向交易者时遇到的错误。

数据样本如下

我是 python 和 python 社区的新手

错误:

C:\Python\python.exe C:\Users\harif\PycharmProjects\untitled\venv\learning\dataframe1.py 回溯(最近一次通话最后): 文件“C:\Users\harif\PycharmProjects\untitled\venv\learning\dataframe1.py”,第 32 行,在 fromdate=datetime(2, 10, 2016), ValueError: day is out of range for month

进程以退出代码 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

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    日期时间对象按此顺序接受值。

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

    有两种方法可以解决这个问题。

    1. 您可以按正确的顺序写入值。例如:datetime(2016, 10, 2)
    2. 您可以指定哪个值是什么。例如:datetime(day=2, month=10, year=2016),

    【讨论】:

    • 谢谢 Sidharth,这很有帮助。根据您的建议进行更正后,现在出现的另一个错误是:文件“C:\Python\lib\site-packages\backtrader\feeds\csvgeneric.py”,第 114 行,在 _loadline dt = datetime.strptime (dtfield, dtformat) 文件“C:\Python\lib_strptime.py”,第 565 行,在 _strptime_datetime tt,fraction = _strptime(data_string, format) 文件“C:\Python\lib_strptime.py”,第 362 行,在 _strptime ( data_string, format)) ValueError: 时间数据 '2/10/2016' 与格式 '%Y-%m-%d %H:%M:%S 不匹配
    • 可以分享代码吗?如果觉得有用请点赞
    • 嗨 Siddharth,它与上面的代码相同,只是我更改了这部分代码 fromdate=datetime(year=2016, month=10, day=2), todate=datetime(year= 2019,月=10,日=1,))
    • 你能告诉我如何给你点赞,因为我是新手,在任何地方都看不到点赞按钮。
    猜你喜欢
    • 2023-03-12
    • 2017-07-29
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多