Strategy
This is a long-only daily strategy. The indicator is computed from the completed bar, and the order fills at the next bar’s open. Each fill pays 0.10% commission. There is no extra slippage, and the strategy does not sell short.
Metrics below are one index at a time, not a portfolio of them. Where a parameter search is available, it picks the Sharpe-maximizing grid point on the S&P 500. That search sees the same sample it reports, so the best cell is an in-sample peak.
The signal logic and indicator code for this strategy is shown in the methodology code section below.
Keltner Width Breakout waits for the channel width to narrow (low volatility), then enters long on a close above the upper Keltner band. Exits when price falls 2% below the upper band.
class KeltnerWidthBreakout(Strategy):
n = 20; atr_n = 10; mult = 2; width_n = 50
def init(self):
atr = _atr(self.data.High, self.data.Low, self.data.Close, self.atr_n)
ema = _ema(self.data.Close, self.n)
self.upper = self.I(lambda: ema + self.mult * atr, name="Upper")
width = (ema + self.mult*atr - (ema - self.mult*atr)) / ema.replace(0,1e-10)
self.width = self.I(lambda: width, name="Width")
self.width_min = self.I(lambda: width.rolling(self.width_n).min(), name="WidthMin")
def next(self):
if self.width[-1] < self.width_min[-1]*1.1 and self.data.Close[-1] > self.upper[-2] and not self.position: self.buy()
elif self.data.Close[-1] < self.upper[-1]*0.98 and self.position: self.position.close()