Parametric VaR
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=5
indicator("VaR", timeframe = "D", max_bars_back = 5000)

import loxx/norminv/1 as lib

percentile = input(1.0 , title = "Percentile Threshold")
length = input(4000, title = "Length")
in_percent = input(true, title = "Result in Percentage")

length := bar_index > length ? math.min(length, bar_index) : bar_index + 1

rt_formula = close/close[1] - 1
return_ = in_percent ? rt_formula * 100 : rt_formula

mu = ta.sma(return_, length)
std = ta.stdev(return_, length)

norm = lib.norminv(percentile/100, mu, std)

// VaR = ta.percentile_linear_interpolation(return_, length, percentile)

//Plots
cColor = return_ >= 0 ? color.green : color.red
plot(return_, style = plot.style_histogram, title = "Return", color=cColor)
// plot(VaR, style = plot.style_stepline, title = "VaR")
plot(norm, style = plot.style_stepline, title = "Parametric VaR", color=color.blue)

