// Downloaded From https://www.WiseStockTrader.com
/*
this afl Plots the historical volatility of a stock
and punts it against the Value At Risk: 
you can choose the percentile , the holding period and the lookback period


plotting is automatically adjusted against the stock price  

by Anastagi  june 2015

*/


SetChartOptions(0,chartShowArrows|chartShowDates); 

// Historical volatility
Lenperiod=20;
HV = 100 * StDev(log(C/Ref(C,-1)),lenPeriod) * sqrt(252);
Plot(LastValue(C) *(1+ HV/100*2)-LastValue(C)/3 , "HV("+lenPeriod+")", ParamColor( "Color", colorRed ), styleThick , styleOwnScale );


// percentile function
function PercentRank2( Data, Periods) // 
{
   Count = 0;
  for ( i = 1; i <= Periods ; i++ )
   {
   Count += Data > Ref( Data, -i );
   }
  return 100 * Count / Periods;
}


// VAR
perctil  = 0.01; // choose the percentile 
Lookback =100;   // time span for VAR
HP       = 5 ;   // holding period
ren=(log(C/Ref(C,-1))) ;
ren2=Sum(ren,HP);  
Maxexcurs= HHV(ren2,100);
VAR=Percentile(ren2,Lookback,perctil);



Plot(Maxexcurs * LastValue(C)+LastValue(C)/2, "max", colorBlue); 
Plot(Var *10000 + LastValue(C)  , "VAR", colorBrown);
Plot ( C, " Close", colorBlack,styleCandle );