Welcome to the BEST forum for traders

Did you know we're sharing tons of exclusive content here?
Our community is growing quickly. Take a look around and say "Hello".

Why mean value gives 0?

May 17, 2021 - 2:34 PM

Viewed 398 times

https://best-trading-indicator.com/community/bti/forums/4180/topics/24188 COPY
  • Hello everyone,

    This is the continuation of a study I was working on, and I already had some help in this similar topic:
    https://best-trading-indicator.com/community/bti/forums/4180-pinescript/topics/24131-why-mean-value-gives-nan

    But now I'm having trouble trying to calculate tMintMaxtCloseMEAN.

    tMintMaxtCloseMEAN means the volatility using the next parameters:
    tMin: Todays Min
    tMax: Todays Max
    tClose: Todays Close (for the denominator)
    MEAN: The mean value of this parameter over time
    So, it should be calculated as:
    tMintMaxtCloseMEAN = ( tMax - tMin ) / tClose
    And I calculate this mean value using an EMA multiplier.

    On the green labels you can see that the values for the Minimum of the day (which is stored in the array minimos[1]), as well as the maximum (in maximos[1]), are well stored. The calculation of the volatility of the day (Max-Min)/Close is also calculated correctly. The emaMultiplier is also shown on the label and it is correct.

    tMintMaxtCloseMEAN uses all of these variables, and all of them are correct, so I don't know why this value tMintMaxtCloseMEAN cannot be correctly calculated and gives 0.

    Thanks in advance!

    study("Volatility", overlay=true)
    
    // Inputs de volatilidades
    emaLength = input(20, title="EMA Length", type= input.float)
    i_tMintMaxtClose = input(true, title="(Max Hoy - Min Hoy) / Cierre Hoy")
    
    i_NumPos = input(close, title = "Numerador Positivo", type = input.source)
    i_NumPosDay = input(0, title = "Día numerador positivo (0=hoy, 1=ayer)", type = input.integer)
    i_NumNeg = input(close, title = "Numerador Positivo", type = input.source)
    i_NumNegDay = input(0, title = "Día numerador negativo (0=hoy, 1=ayer)", type = input.integer)
    i_Denom = input(close, title = "Denominador", type = input.source)
    i_DenomDay = input(0, title = "Día denominador (0=hoy, 1=ayer)", type = input.integer)
    float inputVolatility = 0.0
    var float inputMax = 0.0
    var float inputMean = 0.0
    
    // Inputs del filtro de tiempo
    filtrar_desde= input(false, title="aplicar filtro desde")
    filtrar_hasta= input(false, title="aplicar filtro hasta")
    fecha_desde = input(defval = timestamp("01 Sep 2020 00:00 +0000"),title = "Fecha Inicio", type = input.time)
    fecha_hasta = input(defval = timestamp("01 May 2021 23:59 +0000"), title = "Fecha Final", type = input.time)
    
    // Funciones de filtro de tiempo
    LastDayFiltro() =>
        hasta= time== fecha_hasta or not filtrar_hasta
        hasta
    
    FechaValida() =>
        //timestamp(syminfo.timezone, desde_a, desde_m, desde_d,0,0)
        desde= time>= fecha_desde or not filtrar_desde
        hasta= time<= fecha_hasta or not filtrar_hasta
        desde and hasta
    
    //CalculateMean(numpos, numposday, numneg, numnegday, den, denday) =>
    
    // Arrays
    var int maxDays = max(i_NumPosDay, i_NumNegDay, i_DenomDay) + 1
    var float[] maximos = array.new_float(maxDays + 1)
    var float[] minimos = array.new_float(maxDays + 1)
    var float[] cierres = array.new_float(maxDays + 1)
    
    // Variables
    var float todayMax=0.0
    var float todayMin=0.0
    var float yesterdayMax = 0.0
    var float yesterdayMin = 0.0
    
    float tMintMaxtClose=0.0
    var float tMintMaxtCloseMAX = 0.0
    var float tMintMaxtCloseMEAN = 0.0
    var float tMintMaxtCloseMEAN2 = 3.0
    
    var int day = 0
    var int lastBarDay = 0
    var float emaMultiplier = 2.0/(emaLength+1.0)
    
    var int today = 1
    var int yesterday = 2
    
    var bool isMarket=false
    var bool lastBarWasMarket=false
    var int lastMarketBar = 0
    
    var label1=label.new(bar_index, 0.0, text = "", color=color.yellow)
    label2=label.new(bar_index, high, text = "", color=color.green)
    
    // Cálculos    
    if(FechaValida())    
    
        // Update day and bars
        lastBarWasMarket := isMarket
        isMarket := session.ismarket
        lastBarDay := day
        day:= dayofweek
    
        if(isMarket and lastBarWasMarket and lastBarDay != day)
            lastMarketBar:= 1
    
        // Primero miramos si estamos fuera de mercado para almacenar la última vela del día
        if(not isMarket)
            if(lastBarWasMarket)
                lastMarketBar := 1
            else
                lastMarketBar += 1
    
        if(isMarket and day != lastBarDay) 
            for counter = maxDays to 1 by 1 // by 1 es por defecto pero para tenerlo claro
                array.set(maximos, counter, array.get(maximos,counter-1))
                array.set(minimos, counter, array.get(minimos,counter-1))
                array.set(cierres, counter, array.get(cierres,counter-1))
    
            yesterdayMin:=todayMin
            yesterdayMax:=todayMax
            todayMax := high
            todayMin := low
    
        if(isMarket)
            if(day == lastBarDay)
                todayMax := max(todayMax, high)
                todayMin := min(todayMin, low)
                array.set(maximos, 0, todayMax)
                array.set(minimos, 0, todayMin)
                array.set(cierres, 0, close)
                label.delete(label2)
    
            else //if(day != dayofweek)
                // CREAR FUNCION QUE HAGA ESTO CON TODAS
                tMintMaxtClose := 100*(array.get(maximos, today)-array.get(minimos, today))/array.get(cierres, today)         //close[lastMarketBar]
                tMintMaxtCloseMAX := tMintMaxtClose > tMintMaxtCloseMAX ? tMintMaxtClose : tMintMaxtCloseMAX
                tMintMaxtCloseMEAN := tMintMaxtClose * emaMultiplier + tMintMaxtCloseMEAN * (1.0 - emaMultiplier)
    
                label.set_text(label2, "Volatility= " + tostring(round(tMintMaxtClose,2))+"\nMax= "+tostring(round(array.get(maximos, 1), 2))+"\nMin= "+tostring(round(array.get(minimos, 1), 2)) + "\ntMintMaxtClose= "+tostring(round(tMintMaxtClose, 2))+ "\ntMintMaxtCloseMEAN= "+tostring(round(tMintMaxtCloseMEAN, 2)) + "\nEMA Multiplier: "+tostring(round(emaMultiplier, 5)))
        else 
            label.delete(label2)
    
    //label.delete(label2)
    
    lastCandle = barstate.islast or LastDayFiltro()
    
    if(lastCandle)
        label.set_text(label1, "Volatility\nInput mean: " + tostring(round(inputMean,2))+", Max = "+tostring(round(inputMax, 2)))
    
        if(i_tMintMaxtClose)
            text = label.get_text(label1)
            label.set_text(label1, text + "\n(TodayMax-TodayMin)/TodayClose \nMean = " + tostring(round(tMintMaxtCloseMEAN,2))+", Max = "+tostring(round(tMintMaxtCloseMAX, 2)))
    
        label.set_xy(label1, bar_index, high[0])
    
    0
  • Sorry, here is an image to show what happens

    Captura333.png

    0
  • I solved it!

    In case anybody wants to know the problem and the solution, here it goes:

    The mean value initiates correctly at 0.0, but since the very first day we dont have any data to calculate the DAILY volatility, this value is calculated as an error (NaN), therefore giving an error when it calculates the MEAN value. From the second day, the DAILY volatility is calculated correctly since we have all the data, but the MEAN value keeps gving error since it is caltulated using itself here:
    '''
    tMintMaxtCloseMEAN := tMintMaxtClose * emaMultiplier + tMintMaxtCloseMEAN * (1.0 - emaMultiplier)
    '''

    Captura333333.png

    1
  • Thank you for the update :)

    0
CONTENTS