Historical Volatility
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © micikulev

//@version=5
indicator('Historical Volatility', overlay=false, format=format.volume, shorttitle='Historical Volatility')

// Get user input 
lenght = input(title='Lookback', defval=20)
vl = input(title='Volatility SMA', defval=30)
vx = input(title='VIX SMA', defval=30)
source = input(title='Source', defval=close)
vix = input.symbol(title='Reference Market', defval='TVC:VIX')
annualized = input(title='working days in 1 year', defval=250)



// Declare arrays
var currentArray = array.new_float(lenght)
var referenceArray1 = array.new_float(lenght)


// Get % change of current market
currentData = source
currentChange = (currentData - currentData[1]) / currentData[1] * 100

if bar_index > lenght  // acumulate at lest "lenght" number of elements
    array.shift(currentArray)  // Shift (remove) the last (first entered) value from our arrays (FIFO)
array.push(currentArray, currentChange)  // Add the current values to our arrays

lrm = ta.lowest(currentChange, lenght)  // lowest return of market
hrm = ta.highest(currentChange, lenght)  // highest return of market
mmr = ta.sma(currentChange, lenght)  // mean of market returns
mlmr = mmr - lrm  // mean - lowest of market returns
mhmr = mmr + hrm  // mean + highest of market returns

currentDev = array.stdev(currentArray)  // Determine the standard deviation of our arrays
msigma = ta.stdev(currentChange, lenght)  // msigma = market standard deviation
variance = msigma * msigma  // variance = ticker(standard deviation^2)
daily_volatility = math.sqrt(variance)
annualized_volatility = math.sqrt(annualized) * math.sqrt(variance)
vix_val = nz(request.security(vix, timeframe.period, close))
vix_discounted = vix_val

smal = ta.lowest(annualized_volatility,1)
smaav = ta.sma(smal,vl)
smavix = ta.sma(vix_discounted,vx)


plot(daily_volatility, title='Volatility', style=plot.style_line, color=color.new(color.olive, 0), display=display.none)
plot(vix_discounted, title='VIX', style=plot.style_line, color=color.new(color.black, 0), display=display.none)
plot(annualized_volatility, title='Annualized Volatility', style=plot.style_line, color=color.new(color.olive, 0))
plot(smaav, title='Volatility SMA', style=plot.style_line, color=color.new(color.maroon, 0))
plot(smavix, title='VIX SMA', style=plot.style_line, color=color.new(color.maroon, 0), display = display.none)

