如何解决使用Backtrader和Python以及本地csv文件进行回溯测试的数据源错误?

2024-05-19 01:49:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用backtrader和python构建用于回测加密策略的代码,但每次尝试连接数据源时都会出现错误,我尝试了不同的数据源方法,并尝试了许多其他连接方式,但每次都会出现一些或其他类型的错误,似乎没有任何效果。请帮忙

提到了我在代码中尝试使用的两种方法

代码:

import backtrader as bt
import os
import sys
import datetime

cerebro = bt.Cerebro()

#Method 1: YahooFinanceCSVData
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, 'C:/Users/admin/xx/xx2/xx.csv')
data = bt.feeds.YahooFinanceCSVData(dataname=datapath, reverse=False)

#Method 2: GenericCSVData
data = bt.feeds.GenericCSVData (dataname='filename.csv', dtformat=1)

cerebro.adddata(data)

cerebro.run()

cerebro.plot()
<end>

数据文件的第一个字符串: 1623809640000401224.02000000040129.7000000040100.00000000 40107.65000000,12.5374970162380969999502950.08549781339,4.72578400189573.50347000,0

#错误 #方法1#ValueError month必须在1..12中 #方法2#OSError[Errno 22]无效参数


Tags: path方法代码importdataos错误sys
1条回答
网友
1楼 · 发布于 2024-05-19 01:49:52

文件显示:

dtformat: Format used to parse the datetime CSV field. See the python strptime/strftime documentation for the format.

If a numeric value is specified, it will be interpreted as follows

1: The value is a Unix timestamp of type int representing the number of seconds since Jan 1st, 1970

2: The value is a Unix timestamp of type float

如果您试图直接转换日期时间,您会得到:

from datetime import datetime
ts = 1623809640000
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

错误:

                                     -
ValueError                                Traceback (most recent call last)
<ipython-input-15-2bb3006fc757> in <module>
      4 # if you encounter a "year is out of range" error the timestamp
      5 # may be in milliseconds, try `ts /= 1000` in that case
  > 6 print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

ValueError: year 53426 is out of range

这是因为您的日期时间以毫秒为单位。修正为秒除以1000,得到:

from datetime import datetime
ts = 1623809640000 / 1000
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

导致:


"2021-06-16 02:14:00"

我相信这可能是你问题的根源

相关问题 更多 >

    热门问题