Returns Model 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("Returns Model by Tenozen", overlay= false, precision = 7)

true_log = input.bool(false, "Log on?")
ret_len = input.int(20, "Return Gap Length")
true_period = input.bool(false, "Use Array Period?")
n = input.int(20, "Array Period")
log_val = math.log(close)

//Returns

ret = true_log? (log_val[ret_len] - log_val)/log_val*-1 :(close[ret_len] - close)/close*-1 //

//MA 
ma_len = input.int(9, "MA Length")
smo_len = input.int(5, "Smoothing Length")
ma = ta.sma(ret, ma_len)
smoothing = ta.sma(ma, smo_len)

//Returns Array

var float [] ret_array = array.new_float()

array.push(ret_array, ret[1])


//Average Return

ret_av = array.avg(ret_array) //

//STD

t_ret = (ret[1] - ret_av)*(ret[1] - ret_av) //

var float [] array_t_ret = array.new_float()
array_p_ret = array.new_float()

if true_period
    for i = 0 to n - 1
        array.push(array_p_ret, t_ret[i])
else
    array.push(array_t_ret, t_ret)

dev_av = true_period? array.sum(array_p_ret)/(array.size(array_p_ret)-1): array.sum(array_t_ret)/(array.size(array_t_ret)-1)

pos_std_ret = math.sqrt(dev_av)
pos_std_ret_2 = math.sqrt(dev_av)*2
neg_std_ret = math.sqrt(dev_av)*-1
neg_std_ret_2 = math.sqrt(dev_av)*2*-1

//Plot

plot(ret, "Return", color.new(#ffffff, 0))
plot(ret_av, "Average Return", color.new(color.purple, 50))
plot(ma, "Moving Average", color=color.new(color.aqua, 0), linewidth=2)
plot(smoothing, "Smoothed Average", color=color.new(color.orange, 0), linewidth=1)
p1 = plot(pos_std_ret, "Standard Deviation +1", color.new(color.red, 50))
n2 = plot(neg_std_ret, "Standard Deviation -1", color.new(color.aqua, 50))
n1 = plot(pos_std_ret_2, "Standard Deviation +2", color.new(color.red, 50))
p2 = plot(neg_std_ret_2, "Standard Deviation -2", color.new(color.aqua, 50))

hline(0, "Zero Line", color.new(color.white, 50), linestyle = hline.style_dotted)
fill(p1,n1,color.new(color.aqua, 90))
fill(p2,n2,color.new(color.red, 90))
//