D-VaR position sizing
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © shardison

//The D-VaR position sizing method was created by David Varadi.
//It's based on the concept of Value at Risk (VaR) - a widely used measure of the risk of
//loss in a portfolio based on the statistical analysis of historical price trends and volatilities.

//The PosSizer will:

//Take the "rolling" daily returns for an instrument, according to the specified sample period
//Calculate the 5th percentile of returns (aka "max tail loss")
//Accept a risk level expressed as a maximum daily loss. The default value is 1% (conservative), risk seekers can enter higher values e.g. 1.5% (aggressive)
//Calculate the position size as the risk level divided by the absolute value of the "max tail loss"
//Position may not exceed 200%

//@version=5
indicator("D-VaR position sizing")
alength = input(defval=100, title="Average Returns Period", tooltip="Averege Returns Period and Length of Max Tail Calc--Max Tail Calc should be >= 100 to get accurate percentile")
returns = ((close - close[1]) / close[1])*100
a = array.new_float(0)
for i = 0 to alength
	array.push(a, returns[i])
avgreturns = array.avg(a)
//plot(avgreturns, title="Avg Returns", color=color.new(color.red, 0))

pctilecalc = input(defval=true, title="Max tail loss calc method", tooltip="max tail loss caculation using 'Percentile_nearest_rank' or 'Percentile_linear_interpolation' -- default is nearest_rank")
pctile = pctilecalc ? ta.percentile_nearest_rank(avgreturns, alength, 5) : ta.percentile_linear_interpolation(avgreturns, alength, 5)
//plot(pctile, title="Max Tail Loss", color=color.new(color.teal, 0))

pctrisk = input.float(defval = 1.0, title="Percent Risk", step=0.1, tooltip="Accept a risk level expressed as a maximum daily loss. The default value is 1% (conservative), risk seekers can enter higher values e.g. 1.5% (aggressive)")
possize = pctrisk / math.abs(pctile)
maxplot = math.min(possize,200)
plot(maxplot, title="Uncapped Position Size", color=color.new(color.blue, 0))

possizecap = input(defval=25, title="Cap Postion at X% of Equity")
dvarPositionSize = math.min(possize, possizecap)
plot(dvarPositionSize, title="Capped Position Size", color=color.new(color.orange, 0))
