Hello and thank you for your time.
I'm currently trying to apply a single strategy (buy and sell with a signal of a ratio value) to mutltiple csv (each csv have info from different tickers).
This was made following the examples in:
https://backtest-rookies.com/2017/08/22/backtrader-multiple-data-feeds-indicators/
https://www.backtrader.com/docu/extending-a-datafeed/
All the test files look the same:
date,close,volume,ratio
31/01/2000,10,50,0.2
29/02/2000,20,100,0.2
31/03/2000,30,150,0.2
28/04/2000,40,200,0.5
I'm getting a data error as it does not recognize the format inside the params.
ValueError: time data '31/01/2000' does not match format '%Y-%m-%d %H:%M:%S'
Here is the complete code, I will gladly appreciate your help in order to make it work.
import backtrader as bt
from datetime import datetime
class hopeitworks(bt.Strategy):
def __init__(self):
self.inds = dict()
for i, d in enumerate(self.datas):
self.inds[d] = dict()
self.inds[d]['ratio'] = d.ratio
def next(self):
for i, d in enumerate(self.datas):
dt, dn = self.datetime.date(), d._name
pos = self.getposition(d).size
if not pos:
if self.inds[d]['ratio'][0] <= .2 and self.inds[d]['ratio'][0] > 0:
self.buy(data=d, size=1)
else:
if self.inds[d]['ratio'][0] >= .5:
self.sell(data=d, size=1)
#Variable for our starting cash
startcash = 10000
#Create an instance of cerebro
cerebro = bt.Cerebro()
#Add our strategy
cerebro.addstrategy(hopeitworks)
class DataCSV(bt.feeds.GenericCSVData):
params = (
('dtformat', '%d/%m/%Y'),
('datetime', 0),
('time', -1),
('open', -1),
('high', -1),
('low', -1),
('close', 1),
('volume', 2),
('openinterest', -1),
('ratio', 3),
)
from backtrader.feeds import GenericCSVData
class DataCSV(GenericCSVData):
# Add a line to the inherited ones from the base class
lines = ('ratio',)
# openinterest in GenericCSVData has index 7 ... add 1
# add the parameter to the parameters inherited from the base class
params = (
('ratio', 8),
)
#create our data list
datalist = [
('data/aaadata.csv', 'TICKERAAA'), #[0] = Data file, [1] = Data name
('data/bbbdata.csv', 'TICKERBBB'),
('data/cccdata.csv', 'TICKERCCC'),
]
#Loop through the list adding to cerebro.
for i in range(len(datalist)):
data = DataCSV(dataname=datalist[i][0])
cerebro.adddata(data, name=datalist[i][1])
# Set our desired cash start
cerebro.broker.setcash(startcash)
#Run Cerebro Engine
cerebro.run()
# #Get final portfolio Value
portvalue = cerebro.broker.getvalue()
pnl = portvalue - startcash
# #Print out the final result
print('Final Portfolio Value: ${}'.format(portvalue))
print('P/L: ${}'.format(pnl))
#Finally plot the end results
cerebro.plot()