1

I am not able to understand the error - AttributeError: 'int' object has no attribute 'to_pydatetime', I will be really grateful, if anyone could please help me out in this?

from datetime import date, datetime
import pandas as pd
import backtrader as bt

file_name = 'fromstart/2021 APR NIFTY.txt'
dataframe = pd.read_csv(file_name)
data = bt.feeds.PandasData(
    dataname = dataframe,
    fromdate = datetime(2021, 1, 1),
    todate = datetime(2021, 4, 30),
    )

class AllInOne(bt.Strategy):
    def __init__(self):
        self.dataopen = self.datas[0].open_p      # Keep a reference to the "open" line in the data[0] dataseries
        self.datahigh = self.datas[0].high_p      # Keep a reference to the "high" line in the data[0] dataseries
        self.datalow = self.datas[0].low_p        # Keep a reference to the "low" line in the data[0] dataseries
        self.dataclose = self.datas[0].close_p    # Keep a reference to the "close" line in the data[0] dataseries

    def next(self):
        pass

if __name__ == '__main__' :
    cerebro = bt.Cerebro()  # We initialize the `cerebro` backtester.
    cerebro.adddata(data) # We add the dataset in the Data cell.
    cerebro.addstrategy(AllInOne)
    print('Starting Portfolio Value: {0:8.2f}'.format(cerebro.broker.getvalue()))
    results = cerebro.run()
    print('Final Portfolio Value: {0:8.2f}'.format(cerebro.broker.getvalue()))

Data and stacktrace:

data feed image

error image

meowulf
  • 367
  • 1
  • 5
  • 14
r_goel
  • 43
  • 1
  • 6
  • pretty sure either you or backtrader is trying to convert the date column and can't because it thinks it's an integer and not a data type it handle. See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.to_pydatetime.html – Jonathan Leon Jun 18 '21 at 02:55
  • Did you resolve this? – run-out Jun 26 '21 at 21:01

3 Answers3

1

You need to

  • Firstly, you must have a datetime column with datetime64[ms] datatype
dataframe["datetime"] = pd.to_datetime(dataframe["date"] + " " + dataframe["time"])
  • Then you can either set datetime to index, or specify datetime = -1

In backtrader documentation:

        # Possible values for datetime (must always be present)
        #  None : datetime is the "index" in the Pandas Dataframe
        #  -1 : autodetect position or case-wise equal name
        #  >= 0 : numeric index to the colum in the pandas dataframe
        #  string : column name (as index) in the pandas dataframe
        ('datetime', None),

Code:

# good to use verify_integrity to prevent duplicated datetime
dataframe = dataframe.set_index("datetime", verify_integrity=True)
data = backtrader.feeds.PandasData(dataname=dataFrame)

or

data = backtrader.feeds.PandasData(dataname=dataFrame, datetime=-1)
gowestyang
  • 21
  • 2
0

I had the same error and the next steps have worked for me.

  1. This is the CSV File Data that I am using.

Data from csv file

  1. I think you should concatenate the columns "date" and "time".
  2. Finally, when reading csv file, specify the index and parse the time.
pathfile = ".../2021-10-11--2021-10-15.csv"
df_data = pd.read_csv(pathfile, delimiter=",", index_col="Datetime", parse_dates= True)
blackbishop
  • 30,945
  • 11
  • 55
  • 76
0

This worked for me, for feeding in my custom dataset.

datapath = '../db/stockData/daily/ONGC.csv'
dataframe = pd.read_csv(datapath,
                            parse_dates=True,
                        index_col="timestamp",
                       )

dataframe.index = pd.to_datetime(dataframe.index,format="%Y-%m-%d",utc=True)
data = bt.feeds.PandasData(dataname=dataframe)

cerebro.adddata(data)
pankaj pundir
  • 377
  • 3
  • 6