Unable to feed my custom DataFrame to backtrader
Ahmad Nazari last edited by
Hello, I have a custom Pandas DataFrame and I want to feed this data that has different column names to backtrader. For do this, I wrote my code according to documentation:
from __future__ import (absolute_import, division, print_function, unicode_literals) import datetime import backtrader as bt # data class class PandasData(bt.feeds.DataBase): params = ( ('datetime', None), ('open', -1), ('high', -1), ('low', -1), ('close', -1), ('Volume', -1), ('pos_side', -1), ('entry', -1), ('exit', -1), ('pos_result', -1), ('ema1', 15), ('ema2', 16), ('ema3', 17), ) # Create a Stratey class TestStrategy(bt.Strategy): def log(self, txt, dt=None): ''' Logging function for this strategy''' dt = dt or self.datas.datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): # Keep a reference to the "close" line in the data dataseries self.dataclose = self.datas.close def next(self): # Simply log the closing price of the series from the reference self.log('Close, %.2f' % self.dataclose) if __name__ == '__main__': # Create a cerebro entity cerebro = bt.Cerebro() # Add a strategy cerebro.addstrategy(TestStrategy) # Create a Data Feed data_bt = PandasData(dataname=data) # represent the problem print('Len data:', len(data)) print('Len data_bt:', len(data_bt)) # Add the Data Feed to Cerebro cerebro.adddata(data_bt) # Set our desired cash start cerebro.broker.setcash(1000.0) # Print out the starting conditions print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) # Run over everything cerebro.run() # Print out the final result print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
but after running the above code, the length of the
0and cerebro doesn't loop through the dataset to backtest the strategy and below is the output:
for better show my dataset these 2 images are the
Hello, I stumbled across backtader after creating a whole lot of PYTHON UDF's for Excel with XLWINGS (awesome library btw)
thinking I was spiffy, I thought I'd use my existing code to create a dataframe to pass to Cerebro and use the already calculated indicators at my disposal. I didn't get it to work. so I just "rebuilt" the indicators in BT's INIT
i am really really new to BackTrader. thinking starting last friday.
This guy seems to have done it. his trading logic was off, but I think he has done what you're trying to do. I think the key is to structure the data so that Cerebro "knows" where to look for the values it is trying to work with.
Good Luck. this is an astounding package. considering I used to do all of this years ago in C and C++ before TALIB existed.