import backtrader.feeds as btfeeds
class PandasDataSource(bt.feeds.PandasData):
lines = ('Strategy_GoldenCross_Signal',)
params=(
('Strategy_GoldenCross_Signal', -1),
('Strategy_MACDDiff', -1),
('dtformat', ('%Y-%m-%d')),
('datetime', None),
('time', -1),
('high', 2),
('low', 3),
('open', 1),
('close', 4),
('volume', 5),
('openinterest', -1),)
Hi,
I want to use my custom column in the dataframe which is Strategy_GoldenCross_Signal
.
After adding the data:
st_date = datetime.datetime(2021,1,1)
ed_date = datetime.datetime(2021,12,20)
cerebro = bt.Cerebro()
datafeed1 = PandasDataSource(dataname=data1, fromdate=st_date, todate=ed_date)
I then define the strategy class:
class TestStrategy(bt.Strategy):
def next(self):
if not self.position:
if self.data.Strategy_GoldenCross ==1:
self.buy()
elif self.data.Strategy_GoldenCross ==-1:
self.close()
So basically, when the customized signal is 1 -> buy, -1 -> sell Adding into the strategy:
cerebro.addstrategy(TestStrategy)
cerebro.broker.setcash(1000)
cerebro.addsizer(bt.sizers.PercentSizer, percents=20)
print(cerebro.broker.getvalue())
result = cerebro.run()
end_cash = cerebro.broker.getvalue()
print(end_cash)
I want to ask if this is the right way to use the columns in the dataframe? And what do you recommend for using the indicators? Would you engineer the dataframe first and use the engnieered columns rather than using the existing indicators inside the backtrader package? Thanks.