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),)嗨,
我想在dataframe (即Strategy_GoldenCross_Signal )中使用我的自定义列。
在添加数据之后:
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)然后我定义了策略类:
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()因此,基本上,当定制的信号是1 ->买进,-1 -> sell添加到策略中时:
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)我想问一下,这是否是使用dataframe中列的正确方式?你对使用这些指标有什么建议?您会先设计dataframe并使用engineer列,而不是使用backtrader包中的现有指示符吗?谢谢。
发布于 2022-04-17 08:28:36
很简单,您似乎只想按日期(在用例中)触摸额外的数据,只需做:(为了使用self.datetime.date(),,请按照配置中的第3点。)
self.data._dataname.loc[self.datetime.date()]['extra_column']但是,如果您确实希望将额外的列更改为行对象或指示符,请参见此处:(首先创建一个hack wapper类,通过使用“next”方法将列数据更改为行对象,请相信我,只有这样,您不能通过使用'init‘方法来做到这一点):
class CMFLineWapper(bt.Indicator):
lines = ('cmf',)
params = dict(period=14)
def __init__(self, period, strategy ):
self.strategy = strategy
self.p.period = period
def next(self):
self.lines.cmf[0] = self.data._dataname.loc[self.strategy.datetime.date()]['cmf']然后,
def __init__(self):对于i,枚举中的数据( self.datas ):Sel.dataname‘’cmf‘= ta.volume.ChaikinMoneyFlowIndicator( auto.data._dataname’‘high’,auto.data._dataname‘’low‘,auto.data._dataname’‘close’,auto.data._dataname‘音量’,( self.p.cmf_period ).chaikin_money_flow() CMFVector = CMFLineWapper(data,self.p.cmf_period,self,plotname='CMF‘,subplot=True,plothline= self.p.cmf_low_line,self.p.cmf_top_line ) data.lines.cmf = CMFVector.cmf
其中cmf是额外的列。或者您可以使用._dataname来触摸额外的列。
cerebro.run(maxcpus=None, live=False, runonce=True, exactbars=False, optdatas=True, optreturn=True, stdstats=False, quicknotify=True)
好了,现在cmf变成了lins对象,您可以使用sma(1)或lineplotter指示器将lins对象更改为指示符。
祝你好运,我终于不再用后盾了。:)
https://stackoverflow.com/questions/70513798
复制相似问题