MS Market Timing Model
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © waynem59
// This script uses subtle sentiment analysis to try to reduce the risk of positioning in assets. 
// By "assets" I mean: the QQQ ETF as a synonym for positioning in Nasdaq-100 stocks and the TLT ETF 
// as a placeholder for US government bonds with very long maturity and that as a risk-averse 
// alternative. 
// The coloring of the pseudo capital curve means: 
// green = 100% QQQ, 
// red = 100% TLT, 
// yellow = 50% QQQ/50% TLT. 

//@version=4
study("MS Market Timing Model", overlay=false)

pds1 =  input(title="CTM MA periods", type=input.integer, defval=20, minval=2, maxval=400)
pds2 =  input(title="CMM MA short periods", type=input.integer, defval=15, minval=2, maxval=400)
pds3 =  input(title="STM MA short periods", type=input.integer, defval=10, minval=2, maxval=400)
pds4 =  input(title="STM MA long periods", type=input.integer, defval=20, minval=5, maxval=400)
pds5 =  input(title="SPY trend periods", type=input.integer, defval=10, minval=5, maxval=400)

rcd = security("XLY", "D", close)
rhs = security("XLP", "D", close)
spy = security("QQQ", "D", close)
qqq = security("QQQ", "D", close)
tlt = security("TLT", "D", close)
hyg = security("LQD", "D", close)
ief = security("NASDAQ:IEF", "D", close)
smh = security("SMH", "D", close)

thrs = 2
// Consumer Trend Model
ctm = rcd/rhs
ctm_ma = sma(ctm, pds1)
score_ctm = iff(ctm > ctm_ma, 1, -1)

// Credit Market Model
cmm = hyg/ief
cmm_ma = ema(cmm, pds2)
score_cmm = iff(cmm > cmm_ma, 1, -1)

// Semiconductor Trend Model
stm = smh/spy
stm_mak = sma(stm, pds3)
stm_mal = sma(stm, pds4)
score_stm = iff(stm_mak > stm_mal, 1, -1)

// Momentum
spy_ma = sma(spy, pds5)
score_mom = iff(spy > spy_ma, 1, -1)

float eq = na, eq := nz(eq[1], 100000.0)
float cash = na, cash := nz(cash[1], 0.0)
n_spy    = 0.0
n_tlt    = 0.0

score = score_ctm + score_cmm + score_stm + score_mom

n_spy := iff(score[1] != score and score > 1, eq/spy, 
         iff(score[1] != score and score < -1, 0, 
         iff(score[1] != score and score >= -1 and score <=1, eq/(2*spy), n_spy[1]))) 
n_tlt := iff(score[1] != score and score > 1, 0, 
         iff(score[1] != score and score < -1, eq/tlt, 
         iff(score[1] != score and score >= -1 and score <=1, eq/(2*tlt), n_tlt[1]))) 
cash  := iff(score[1] != score and score > 1, 0, 
         iff(score[1] != score and score < -1, eq, 
         iff(score[1] != score and score >= -1 and score <=1, eq/2, cash[1]))) 

eq := n_spy * spy + n_tlt * tlt
//eq := n_spy * spy + cash

bgcol = if score > 1
    color.green
else if score < -1
    color.red
else 
    color.yellow

plot(eq, title="Equity", linewidth=2, style=plot.style_line,color=color.blue)
//hline(0)
bgcolor(bgcol, transp=70)
