This is Vlad's Version, I'll try to convert later if someone doesn't by then.

# Intersection of ROC comparison using OUT_DAY approach

**import** numpy **as** np

# ------------------------------------------------------------------------------------------------------

STOCKS = symbols('QQQ'); BONDS = symbols('TLT','IEF'); LEV = 1.00; wt = {};

SLV = symbol('SLV'); GLD = symbol('GLD'); XLI = symbol('XLI'); XLU = symbol('XLU'); SHY = symbol('SHY');

MKT = symbol('QQQ'); VOLA = 126; BULL = 1; COUNT = 0; OUT_DAY = 0; BASE_RET = 85;

# ------------------------------------------------------------------------------------------------------

**def** initialize(context):

schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes = 140))

schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())

**def** trade(context,data):

**global** BULL, COUNT, OUT_DAY

vola = data.history(MKT, 'price', VOLA + 1, '1d').pct_change().std() * np.sqrt(252)

WAIT_DAYS = int(vola * BASE_RET)

RET = int((1.0 - vola) * BASE_RET)

prices = data.history([SLV, GLD, XLI, XLU, SHY], 'price', RET + 2, '1d').iloc[:-1].dropna()

r = prices.pct_change(RET).iloc[-1]

exit = r[SLV] < r[GLD] **and** r[XLI] < r[XLU] **and** r[XLI] < r[SHY]

**if** exit: BULL = 0; OUT_DAY = COUNT;

**elif** (COUNT >= OUT_DAY + WAIT_DAYS): BULL = 1

COUNT += 1

wt_stk = LEV **if** BULL **else** 0;

wt_bnd = 0 **if** BULL **else** LEV;

**for** sec **in** STOCKS: wt[sec] = wt_stk / len(STOCKS);

**for** sec **in** BONDS: wt[sec] = wt_bnd / len(BONDS)

**for** sec, weight **in** wt.items():

cond1 = sec **in** context.portfolio.positions **and** weight == 0

cond2 = (sec **not** **in** context.portfolio.positions) **and** (weight > 0)

**if** cond1 **or** cond2:

order_target_percent(sec, weight)

record( wt_bnd = wt_bnd, wt_stk = wt_stk)

**def** record_vars(context, data):

record(leverage = context.account.leverage)

'''

Based on:

Peter Guenther's OUT_DAY approach.

Vladimir's "Price relative ratios (intersection) with wait days".

Thomas Chang changed BASE_RET parameter and reduced number of "unnecessary" trades.

Dan Whitnable added another pair and changed Price relative ratios (intersection) with intersection of ROC comparison what removed one more constant.

Many a little makes a mickle.

'''