Comparative Relative Strength(CRS), ARS,SRS,Beta,Roc
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mindsets
//@version=5

indicator('Comparative Relative Strength', shorttitle='CRS', precision=3)

//Input
comparativeTicker = input.symbol('NIFTY', title='Comparative Symbol', group='RS Parameters')
ARSDate = input.time(defval=timestamp('18 Oct 2021'), title='ARS Date', group='RS Parameters')
SRSLength = input.int(123, minval=1, title='SRS Period', group='RS Parameters')
XRSLength = input.int(55, title='XRS Period',tooltip = "EXtra RS Parameter", group='RS Parameters')
toggleSRS = input.bool(defval=true, title='Toggle CRS color on SRS +ve/-ve', group='RS Parameters')
SRS_up = input.color(color.new(color.teal, 30), 'SRS +Ve', inline='Colors', group='RS Parameters')
SRS_down = input.color(color.new(color.red, 30), 'SRS -Ve', inline='Colors', group='RS Parameters')
togglelabelbox = input.bool(defval=true, title='Toggle Label Box color on ARS +ve/-ve', group='Display Choices')
color_text = input.color(color.new(color.white, 20), 'Info Text', inline='Colors', group='Display Choices')
showRefLine = input.bool(defval=true, title='Show ARS Reference Line', group='Display Choices')
showMA = input.bool(defval=false, title='Show EMA of CRS', group='Additional Info')
lengthMA = input.int(34, minval=1, title='EMA Length', group='Additional Info')
//Input End

//Function
isRefDayBar(testTime) =>
    time[1] < testTime and testTime <= time

//Set up
var refTS = 0
var isRefDayOutOfRange = false
float maxCRS = 0.0
float bs_ref_c = 0.0
float cs_ref_c = 0.0


//Bar ahead refDay
isRefBar = isRefDayBar(ARSDate)
isBarAheadOfRef = time > ARSDate
isRefDayOutOfRange := bar_index == 0 and isBarAheadOfRef ? true : isRefDayOutOfRange[1]
refTS := isRefBar ? timestamp(syminfo.timezone, year(time), month(time), dayofmonth(time), hour(time), minute(time), second(time)) : refTS[1]

cs_c = request.security(comparativeTicker, timeframe.period, close)
crs = close / cs_c

//Ref CRS
bs_ref_c := isRefBar ? close : bs_ref_c[1]
cs_ref_c := isRefBar ? cs_c : cs_ref_c[1]

//CRS
refCRS = bs_ref_c / cs_ref_c
CRS_chng = (crs / refCRS - 1) * 100

//Price change from reference
price_chng = (close / bs_ref_c - 1) * 100
compTickerchng = (cs_c / cs_ref_c - 1) * 100
eq_price = cs_c * bs_ref_c / cs_ref_c

ARS = close / bs_ref_c / (cs_c / cs_ref_c) - 1
SRS = close / close[SRSLength] / (cs_c / cs_c[SRSLength]) - 1
XRS = close / close[XRSLength] / (cs_c / cs_c[XRSLength]) - 1
RoC = close / close[XRSLength] - 1

//Beta calculations   RicardoSantos
return_percent(src) =>
    ta.change(src) * 100 / src[1]

lengthx = 252
inst_return = return_percent(close)
bench_return = return_percent(cs_c)
avg_inst_return = ta.sma(inst_return, lengthx)
avg_bench_return = ta.sma(bench_return, lengthx)

sum = 0.0
for idx = lengthx to 0 by 1
    inst_variance = inst_return[idx] - avg_inst_return
    bench_variance = bench_return[idx] - avg_bench_return
    sum += inst_variance * bench_variance
    sum

covariance = sum / (lengthx - 1)
beta = covariance / ta.variance(bench_return, lengthx)

//----------------------------------------------------------------------------------------------------------------------

//Flip Color
CRSColor = toggleSRS ? SRS > 0 ? SRS_up : SRS_down : color.blue
labelboxColor = togglelabelbox ? ARS > 0 ? color.new(color.teal, 40) : color.new(color.red, 40) : color.new(color.blue, 40)

//SMA
CRS_MA = ta.ema(crs, lengthMA)

//Label Texts
refDateText = 'ARS Date: ' + str.tostring(dayofmonth(refTS), '#00') + '/' + str.tostring(month(refTS), '#00') + '/' + str.tostring(year(refTS)) + ' ' + str.tostring(hour(refTS), '#00') + ':' + str.tostring(minute(refTS), '#00')
labelText = isRefDayOutOfRange ? '\nSelected reference date not in view range.\nTry higher TF or more recent reference date\n' : refDateText + '\n' + 
     str.tostring(syminfo.ticker) + ' Chng = ' + str.tostring(price_chng, '#0.00') + '%' + '\n' + str.tostring(comparativeTicker) + 
         ' Chng = ' + str.tostring(compTickerchng, '#0.00') + '%'
labelToolTipText = 'ARS= ' + str.tostring(ARS, '#0.000') + '  SRS= ' + str.tostring(SRS, '#0.000') + '\nXRS(' + str.tostring(XRSLength) + '): ' + str.tostring(XRS, '#0.00') + ' RoC: ' + str.tostring(RoC, '#0.000') + '\nβ: ' + str.tostring(beta, '#0.00')

//Label
changePercentageLabel = barstate.islast ? label.new(bar_index + 5, crs, text=labelText, color=labelboxColor, textcolor=color_text, style=label.style_label_left, textalign=text.align_left, yloc=yloc.price) : na
label.set_tooltip(changePercentageLabel, labelToolTipText)
label.delete(changePercentageLabel[1])


//Plot
plot(crs, linewidth=3, color=CRSColor, title='CRS')  // CRS
plot(showRefLine ? refCRS : na, linewidth=2, color=color.new(color.yellow, 0), title='ARS Reference Line')  // Zero Line
plot(showMA ? CRS_MA : na, color=color.new(color.purple, 30), linewidth=2, title='EMA')  //Moving Average




