我开始研究从SMA Crossover策略的其他代码中提取的代码。我想要完成的是: 假设发生了交叉信号(上方交叉)并进入了LONG位置。价格上涨,但随后触发另一个交叉信号(下行交叉)后,出现了一些沉重的抛售。我想平仓多头头寸,第二天,输入空头头寸。当发生下一个交叉事件(向上交叉)时,我想平仓短仓,第二天输入长仓。
代码如下:
# parameters
params = (
# period for the fast Moving Average
('fast', 20),
# period for the slow moving average
('slow', 200),
# Exit Bar entry delay for flipped position
('exitbars', 1),
# moving average to use
('_movav', bt.ind.MovAv.SMA)
)
# Indicators
sma_fast = self.p._movav(period=self.p.fast)
sma_slow = self.p._movav(period=self.p.slow)
self.buysig = bt.ind.CrossOver(sma_fast, sma_slow)
self.sellsig = bt.ind.CrossOver(sma_slow, sma_fast)
# order logic
if not self.position:
# buy signal
if self.buysig > 0:
# BUY
self.log('BUY CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.buy()
elif self.sellsig > 0:
#if len(self) >= (self.bar_executed + self.params.exitbars):
# Sell
self.log('SELL CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.sell(size=1000)
#else:
#return
else:
return
else: # in a position
if self.buysig < 0:
# Buy Closed
self.log('BUY CLOSE, %.2f' % self.dataclose[0])
self.order = self.close()
# elif ignore zero case
elif self.sellsig < 0:
# Sell Closed
self.log('SELL CLOSE, %.2f' % self.dataclose[0])
self.order = self.close()
else:
return