1. 程式人生 > 其它 >AttributeError: 'numpy.float64' object has no attribute 'to_pydatetime'

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