Anchored Relative Strength
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Amphibiantrading

//@version=5
indicator("Anchored RS", overlay = true)

//----------settings----------//
date     = input.time(timestamp('Jan 01 23'), 'Anchor Date', confirm = true)
sym      = input.symbol('SPX', 'Symbol to Compare')
rsCol    = input.color(color.blue, 'RS Line Color')
showComp = input.bool(true, 'Show Comparative Symbol Line', inline = '1')
spxCol   = input.color(color.red, '', inline = '1')
showMa   = input.bool(true, 'Show RS Moving Average', inline = '2')
maCol    = input.color(color.fuchsia, '', inline = '2')
maLen    = input.int(10, 'Length', inline = '2', tooltip = 'Simple moving average of the RS line.')
offSet   = input.int(20, 'Vertical Offset', minval = 1, tooltip = 'Adjusts the vertical offset of the lines. \nThis has no effect on calculations, adjust as needed for optimal viewing.')

//----------functions----------//
getComp(x)=>
    comp = request.security(sym, timeframe.period, close[x], gaps = barmerge.gaps_off)

//----------variables----------//
var closeArr = array.new<float>()
var spxArr   = array.new<float>()
rsArr        = array.new<float>()
float avg    = na
float sum    = 0.0
float rs     = 0.0
float comp   = 0.0

//----------get data----------//
if time >= date
    closeArr.unshift(close)
barsBack = closeArr.size()

if barstate.isfirst
    spxArr.unshift(getComp(0))
else if not barstate.isfirst
    spxArr.unshift(getComp(0))

//----------calculate RS----------//
if barsBack > 0 
    for i = barsBack-1 to 0
        rsArr.unshift(close[i] / spxArr.get(i) * 100)

if rsArr.size() > maLen-1
    for i = 0 to maLen-1
        sum := sum + rsArr.get(i) 

avg     := rsArr.size() > maLen-1 ?(sum / maLen) * offSet : na
rs      := rsArr.size() > 0 ? rsArr.get(0) : na
comp    := spxArr.size() > 0 ? spxArr.get(0) : na
mult    = rsArr.size() > 0 ? comp[barsBack-1] / (rs[barsBack-1] * offSet) : na

//----------draw RS line----------//
plot(rsArr.size() > maLen-1 and showMa ? avg : na, 'MA', maCol, 2, plot.style_linebr)
plot(time >= date ? rs*offSet : na, 'rs', rsCol, 2, plot.style_linebr)
plot(time >= date and showComp ? comp/mult : na, 'Comp', spxCol, 2, plot.style_linebr)

