AttributeError: 'numpy.float64' object has no attribute 'to_pydatetime'

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import backtrader as bt
import akshare as ak
import datetime
import pandas as pd
class akharePdData(bt.feeds.PandasData):
    '''从Tushare读取A股票数据日线'''
    params = (
        ('fromdate', datetime.datetime(2018, 1, 2)),
        ('todate', datetime.datetime(2022,3, 21)),
        ('nullvalue' , 0.0),
        ('dtformat' , ('%Y-%m-%d')),
        ('datetime',-1),
        ('open', 2),
        ('high', 4),
        ('low', 5),
        ('close', 3),
        ('volume', 6),
        ('openinterest', -1),
    )


if __name__ == '__main__':
    cerebro = bt.Cerebro()
    dt_start=datetime.datetime.strptime("2018-01-01", "%Y-%m-%d")
    dt_end=datetime.datetime.strptime("2022-03-31", "%Y-%m-%d")
    print(dt_start)
    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol='603777', period="daily", start_date="20180101",
                                            end_date="20220331", adjust="")
    stock_zh_a_hist_df['date'] = pd.to_datetime(stock_zh_a_hist_df['日期'])
    stock_zh_a_hist_df.index = pd.to_datetime(stock_zh_a_hist_df['日期'], format='%Y-%m-%d')
    data = akharePdData(dataname=stock_zh_a_hist_df, fromdate=dt_start, todate=dt_end)
    print(stock_zh_a_hist_df)
    print(stock_zh_a_hist_df.dtypes)
    print(stock_zh_a_hist_df.columns.values[0])
    cerebro.adddata(data)
    cerebro.broker.setcash(100000.0)
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.run()
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.plot()

以上修改后可运行,主要改动如下: 

注意点:

("2018-01-01", "%Y-%m-%d")和pd.to_datetime(stock_zh_a_hist_df['日期'], format='%Y-%m-%d')此二者格式一致

 ('nullvalue' , 0.0),
 ('dtformat' , ('%Y-%m-%d')),
 ('datetime',-1),  这三个部分也要格式一致,同时datetime必须为-1


另附上官网评论
    • cnkenzh
      cnkenzh2021-06-09
      请教一个问题,我用akshare的数据代替了例程里面从csv文件里面读取数据,运行后得到一个错误,显示调用pandafeed.py时, dt = tstamp.to_pydatetime()

      AttributeError: 'int' object has no attribute 'to_pydatetime'
      这是什么问题?要怎样解决?谢谢
    • 饭饭
      饭饭回复cnkenzh2021-12-15
      时间戳要在index里,而且需要是start="20200101" ,dates = datetime.datetime.strptime(start, "%Y%m%d") dates为最终格式


posted @ 2022-04-06 21:31  星涅爱别离  阅读(1152)  评论(0编辑  收藏  举报