Autoregressive Covariance Oscillator by Tenozen
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Tenozen

//@version=5
indicator("Autoregressive Covariance Oscillator", overlay=false, precision = 4, max_bars_back = 5000)

time_lag = input.int(10, "Time Lag of 'Auto-covariance'", minval = 1)
average_len = input.int(100, "Average Length", minval = 1)
sym = input.symbol("XAUUSD","Symbol")
src = request.security(sym,timeframe.period,close)
on = input.bool(false, "Use PVMA?")
on_invert = input.bool(false, "Invert Value?")
on_money = input.bool(false, "Times with source?")
inv_arg = on_invert? -1 : 1
money_arg = on_money? src: 1
/////////////////////

var bool calculate = na //var for calculate in a specified time.

isNew = timeframe.isintraday? ta.change(time('12M')) : timeframe.isdaily? ta.change(time('12M')) : timeframe.isdwm? barstate.isfirst: na

if isNew
    calculate := true
else
    calculate := na

//////////////////////

count = nz(ta.barssince(calculate)) //Count the bars
linreg_count = count+1 //current count + 1
val_count = 1/count //count value for devision

//////////////////////

var float val_x = na //sum(x) x = current price

val_x := count > count[1]? val_x + src : 0

/////////////////////

linreg = ta.linreg(src, linreg_count,1) //LSM

var float lsm = na //sum(linreg)

lsm := count > count[1]? lsm + linreg : 0

/////////////////////

val_mu = val_count*val_x //(1/mean)*math.sum(val) --> mean of the time series/mu

/////////////////////

mu_plus_lsm = val_mu + lsm //mu + LSM (for error)

/////////////////////

et = src - mu_plus_lsm

/////////////////////

arm_vald = val_mu + mu_plus_lsm + et //Auto Regressive Model

/////////////////////

average = ta.rma(arm_vald, average_len) //average of ARM

/////////////////////

acv = (arm_vald - average)-(arm_vald[time_lag] - average[time_lag])

/////////////////////

aco = acv/arm_vald

/////////////////////
//PVMA (Post Value Moving Average)
pvma_len = input.int(25, "PVMA Length")
off = input.int(1, "bars back", minval = 1)
price_t = (aco - aco[off])+aco
price_t2 = (aco - aco[off*2])+aco
price_t3 = (aco - aco[off*3])+aco
price_t4 = (aco - aco[off*4])+aco
price_t5 = (aco - aco[off*5])+aco
price_t6 = (aco - aco[off*6])+aco
price_t7 = (aco - aco[off*7])+aco
price_t8 = (aco - aco[off*8])+aco
price_t9 = (aco - aco[off*9])+aco
price_t10 = (aco - aco[off*10])+aco

price_val = (price_t + price_t2 + price_t3 + price_t4 + price_t5 + price_t6 + price_t7 + price_t8 + price_t9 + price_t10)/10
pvma = ta.rma(price_val, pvma_len)

/////////////////////

plot(aco*money_arg*inv_arg,"ACO", color.new(color.white,50), style= plot.style_linebr)
plot(on? pvma*money_arg*inv_arg: na,"PVMA", color.new(#ffff39, 50), style= plot.style_linebr)
hline(0, "Zero Line", color.new(color.white,50),linestyle = hline.style_solid)
