将backtrader导入为bt将backtrader.feeds导入为btfeed将backtrader.anallyzer导入为btanalyzer以ta形式进口talib将numpy导入为np进口熊猫作为pd
从日期时间导入日期时间
类别MACross(bt.策略(:
def __init__(self):
ma_fast = bt.ind.SMA(period = 10)
ma_slow = bt.ind.SMA(period = 50)
self.crossover = bt.ind.CrossOver(ma_fast, ma_slow)
def next(self):
if not self.position:
if self.crossover >0:
self.buy()
elif self.crossover <0:
self.close()
class dataFeed(btfeed.GenericCSVData):
params = (
('dtformat', '%m/%d/%Y %H:%M'),
('datetime', 0),
('open', 1),
('high', 2),
('low', 3),
('close', 4),
('volume', 5),
('openinterest', -1)
)
cerebro = bt.Cerebro()
data = dataFeed(dataname='data.csv')
cerebro.addstrategy(MACross)
cerebro.adddata(data)
back = cerebro.run()
cerebro.broker.getvalue()
back[0].analyzers.sharpe.get_analysis()
cerebro.plot()
[[<Figure size 640x480 with 5 Axes>]]
假设代码都是正确的(不是发布的格式(
要检查值是否已更改,请使用:
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
如果这一点没有改变,看看发布的原始示例,这也是一种交叉策略,看看它的不同之处
摘录:
def __init__(self): #indicators created here
sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average
sma2 = bt.ind.SMA(period=self.p.pslow) # slow moving average
self.crossover = bt.ind.CrossOver(sma1, sma2) # crossover signal
#--init--
def next(self):
if not self.position: # not in the market
if self.crossover > 0: # if fast crosses slow to the upside
self.order = self.buy() #go long
elif self.crossover < 0: # in the market & cross to the downside
self.order = self.sell()
else:
if len(self) >= (self.bar_executed + 5):
self.close() # close long position
https://www.backtrader.com/docu/quickstart/quickstart/