Thanks for visiting my blog ... more projects and code samples available on GitHub.

Code with Devmnj.

Fix Panda dataframe errors for Backtrader

Cover Image for Fix Panda dataframe errors for Backtrader
Devmnj
Devmnj

Backtrader

BackTrader is a python framework for developing and testing algorithamic trading startegies. It is a great item in the tool kit of stock trader/Alogist.

Fix the Panda DataFrame for BT

I start expirimenting with yfinance data and it is working well with BackTrader as well as Backtesting Framework. I got the Attribute Error : str object has no attribute to_pydatettime while working on historical data from broker.

This happends when the date column is not in panda date format. We can replace the colum with panda datatime object it using the following statement.

df['datetime']= pd.to_datetime(df['datetime'])

While I fixed the date error I got another on the datetime column, Attribute Error : int object has no attribute to_pydatettime.

While observing and compare the datafrmae with a yfinance, I found the dataframe I had in a different format, an index column of 0-n, while yfinance dataframe has the date as index column.

Using the Panda builtin functions , able to correct the index column issue and date format.

So I need to replace the numbered index column with datetime column and the problem solved.

Hope this will help someone.

Here is my final code

df =pd.DataFrame(data['Success'])
df =df[['datetime','open','high','low','close','volume']]
df['datetime']= pd.to_datetime(df['datetime']) 
df.set_index('datetime', inplace=True)