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
另附上官网评论
风雨兼程,前程可待!