AlexD Market annual seasonality
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Aleksey Demchenko / AlexD 

//@version=5
indicator(title="AlexD Market annual seasonality", shorttitle="MAS", timeframe="D", 
          format=format.price, precision=2, max_bars_back=5000)

YearsN = input.int(10, title="Number of years", minval=1, maxval=16)
Depth  = input.int(1, title="Depth", minval=0, maxval=16)
Smooth = input.int(8, title="Smooth", minval=1, maxval=64)

var int Offset = (Smooth == 1) ? 0 : math.round(Smooth/2.0)

hline(50, "Middle Band", color=color.gray)

i = Depth
k = 0.0
DayVal = 0.0
timestampI = 0
step = 0

for YearI = 1 to YearsN
    //Finding a day in previous years
    timestampI := timestamp(year-YearI,month,dayofmonth,00,00,00) + Offset*24*60*60*1000
    
    step := 200
    while timestamp(year[i],month[i],dayofmonth[i],00,00,00) > timestampI
        i := i + step
        if (step > 1) and (timestamp(year[i],month[i],dayofmonth[i],00,00,00) < timestampI)
            i := i - step
            step := math.round(step / 2)
    
    if na(close[i])
        DayVal := -1
        break

    //Bullish day probability calculation
    k := 0
    if close[i] > close[i+1]
        k := 2
    else if close[i] == close[i+1]
        k := 1
    
    if Depth > 0
        for j=1 to Depth
            if close[i+j] > close[i+j+1]
                k := j < Depth ? k + 2 : k + 1
            else if close[i+j] == close[i+j+1]
                k := j < Depth ? k + 1 : k + 0.5
            
            if close[i-j] > close[i-j+1]
                k := j < Depth ? k + 2 : k + 1
            else if close[i-j] == close[i-j+1]
                k := j < Depth ? k + 1 : k + 0.5
        k := k/(Depth*4)
    else
        k := k/2
    
    DayVal := DayVal+k

//Final smoothing of indicator
MAS = ta.sma(DayVal / YearsN * 100,Smooth)
if DayVal == -1
    MAS := na

plot(MAS, title="MAS", color = MAS >= 50 ? color.rgb(0, 255, 0) : color.rgb(255, 0, 0))