CONVERSION INDICADOR TRADINGVIEW:Árbol de Decisión

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #236167 quote
    Fr7
    Participant
    Master

    ¿Qué es un Árbol de Decisión?

    Un árbol de decisión es una herramienta de modelado predictivo que se utiliza en estadísticas, minería de datos y aprendizaje automático. Se llama “árbol” porque su estructura se asemeja a un árbol con ramas. Aquí tienes una explicación básica:

    1. Nodos: Cada nodo del árbol representa una pregunta o condición sobre los datos.
    2. Ramas: Cada rama representa una posible respuesta o resultado de la pregunta.
    3. Hojas: Las hojas son los nodos finales que representan la decisión o clasificación final.

    ¿Cómo Funciona?

    1. Inicio: Comienza en el nodo raíz (la primera pregunta).
    2. Decisiones: En cada nodo, se hace una pregunta y se sigue la rama correspondiente según la respuesta.
    3. Resultado: Se continúa hasta llegar a una hoja, que da la decisión final.

    ¿Qué Hace el Código Anterior?

    El código anterior crea un indicador en TradingView que utiliza un árbol de decisión para generar señales de compra y venta basadas en varios indicadores técnicos (RSI, MACD, medias móviles) y los caminos de decisión generados por la librería FunctionDecisionTree.

    Desglose del Código:

    1. Importar Librería: Importa la librería FunctionDecisionTree que contiene la función para generar caminos de decisión.
    2. Parámetros de Entrada: Define los parámetros de entrada como la profundidad del árbol, el número de caminos y el número de pesos.
    3. Inicialización de Pesos: Crea un array de pesos que se utilizarán en el árbol de decisión.
    4. Generación de Caminos de Decisión: Utiliza la función decision_tree para generar caminos de decisión basados en los pesos y la profundidad especificada.
    5. Indicadores Técnicos: Calcula varios indicadores técnicos como las medias móviles, RSI y MACD.
    6. Generar Señales: Genera señales de compra y venta basadas en los caminos de decisión y los indicadores técnicos.
    7. Plotear Señales: Muestra las señales de compra y venta en el gráfico con flechas hacia arriba (BUY) y hacia abajo (SELL).
    #236168 quote
    Fr7
    Participant
    Master
    // © RicardoSantos
    
    //@version=5
    
    // @description Method to generate decision tree based on weights.
    library(title='FunctionDecisionTree')
    
    // @function Method to generate decision tree based on weights.
    // @param weights float array, weights for decision consideration.
    // @param depth int, depth of the tree.
    // @returns int array
    export decision_tree(float[] weights, int depth) => //{
        int _size_w = array.size(id=weights)
        //
        int[] _path = array.new_int(size=0, initial_value=0)
        int _sumweights = math.ceil(array.sum(id=weights))
        if _size_w > 0 and depth > 0 and _sumweights == 1
            for _d = 1 to depth by 1
                for _w = 0 to 999 by 1
                    int _select_weight_index = int(math.random(max=_size_w))
                    float _rng = math.random(max=1.0)
                    float _weight = array.get(id=weights, index=_select_weight_index)
                    if _weight >= _rng
                        array.push(id=_path, value=_select_weight_index)
                        break
        _path
    //{ usage:
    // Input Parameters:
    int depth = input.int(defval=1, minval=1)
    int paths = input.int(defval=2, minval=1)
    int number_of_weights = input.int(defval=2, minval=1)
    // Array to contain weights, sum of array values must be 1.
    var float[] node_weights = array.new_float(size=number_of_weights, initial_value=0)
    if barstate.isfirst
        float _weight = 1.0 / number_of_weights
        for _i=1 to number_of_weights
            array.set(node_weights, _i-1, _weight)
        string t = ''
        for _p = 1 to paths by 1
            _path = decision_tree(node_weights, depth)
            t := t + '\nPath ' + str.tostring(_p, '#') + ': ' + str.tostring(_path)
            t
        var label la = label.new(bar_index, 0.0, t)
    //{ remarks:
    //}}}
    //@version=5
    indicator("Decision Tree Indicator with Technical Indicators and Signals", overlay=true)
    
    // Importar la librería
    import RicardoSantos/FunctionDecisionTree/1 as dt
    
    // Parámetros de entrada
    depth = input.int(defval=3, minval=1, title="Depth of the Tree")
    paths = input.int(defval=2, minval=1, title="Number of Paths")
    number_of_weights = input.int(defval=2, minval=1, title="Number of Weights")
    
    // Array para contener los pesos, la suma de los valores del array debe ser 1.
    var float[] node_weights = array.new_float(size=number_of_weights, initial_value=0)
    if barstate.isfirst
        float _weight = 1.0 / number_of_weights
        for _i=0 to number_of_weights - 1
            array.set(node_weights, _i, _weight)
    
    // Generar caminos de decisión
    string t = ''
    var int[] decision_paths = na
    if barstate.islast
        decision_paths := array.new_int(0)
        for _p = 1 to paths by 1
            _path = dt.decision_tree(node_weights, depth)
            for val in _path
                array.push(decision_paths, val)
            t := t + '\nPath ' + str.tostring(_p, '#') + ': ' + str.tostring(_path)
    
    // Mostrar los caminos en el gráfico
    var label la = na
    if barstate.islast
        la := label.new(bar_index, na, t, color=color.blue, textcolor=color.white, style=label.style_label_down, size=size.small)
        label.set_xy(la, bar_index, high)
    
    // Indicadores técnicos
    sma_short = ta.sma(close, 14)
    sma_long = ta.sma(close, 50)
    rsi = ta.rsi(close, 14)
    [macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)
    
    // Plotear indicadores técnicos
    plot(sma_short, color=color.green, title="SMA 14")
    plot(sma_long, color=color.red, title="SMA 50")
    hline(70, "RSI Overbought", color=color.red)
    hline(30, "RSI Oversold", color=color.green)
    plot(rsi, color=color.blue, title="RSI")
    plot(macdLine, color=color.orange, title="MACD Line")
    plot(signalLine, color=color.purple, title="Signal Line")
    
    // Generar señales de compra y venta basadas en indicadores técnicos y caminos de decisión
    buy_signal = (not na(decision_paths)) and (array.size(decision_paths) > 0) and (array.get(decision_paths, 0) == 1) and (rsi < 30) and (macdLine > signalLine) and (sma_short > sma_long)
    sell_signal = (not na(decision_paths)) and (array.size(decision_paths) > 0) and (array.get(decision_paths, 0) == 0) and (rsi > 70) and (macdLine < signalLine) and (sma_short < sma_long)
    
    // Plotear señales de compra y venta
    plotshape(series=buy_signal, location=location.belowbar, color=color.green, style=shape.labelup, title="Buy Signal", text="BUY")
    plotshape(series=sell_signal, location=location.abovebar, color=color.red, style=shape.labeldown, title="Sell Signal", text="SELL")
    #236169 quote
    Fr7
    Participant
    Master

    Iván, puedes pasar la librería y el indicador a PRT?

    GRACIAS

    #236186 quote
    Fr7
    Participant
    Master
    // Function Decision Tree Indicator with Technical Indicators and Signals
    // Input Parameters
    DepthOfTree = 3
    NumberOfPaths = 2
    NumberOfWeights = 2
    
    // Array to contain weights, sum of array values must be 1.
    NodeWeights = []
    for i = 1 to NumberOfWeights do
        NodeWeights[i] = 1.0 / NumberOfWeights
    next
    
    // Function to generate decision tree based on weights
    decisionTree = []
    sizeW = 0
    sumWeights = 0
    
    if arraySize(NodeWeights) > 0 and DepthOfTree > 0 then
        sizeW = arraySize(NodeWeights)
        sumWeights = round(arraySum(NodeWeights))
        if sumWeights == 1 then
            for d = 1 to DepthOfTree do
                for w = 0 to 999 do
                    selectWeightIndex = round(random * (sizeW - 1)) + 1
                    rng = random
                    weight = NodeWeights[selectWeightIndex]
                    if weight >= rng then
                        decisionTree[size(decisionTree)+1] = selectWeightIndex
                        break
                    endif
                next
            next
        endif
    endif
    
    // Generate decision paths
    DecisionPaths = []
    pathStr = ""
    for p = 1 to NumberOfPaths do
        path = decisionTree
        for val = 1 to size(path) do
            DecisionPaths[size(DecisionPaths)+1] = path[val]
        next
        pathStr = pathStr + "\nPath " + p + ": " + arrayToString(path)
    next
    
    // Technical Indicators
    SmaShort = Average[14](Close)
    SmaLong = Average[50](Close)
    Rsi = RSI[14](Close)
    MacdLine = MACDLine[12, 26, 9](Close)
    SignalLine = Signal[12, 26, 9](Close)
    
    // Generate Buy and Sell signals based on technical indicators and decision paths
    BuySignal = 0
    SellSignal = 0
    if size(DecisionPaths) > 0 then
        if DecisionPaths[1] == 1 and Rsi < 30 and MacdLine > SignalLine and SmaShort > SmaLong then
            BuySignal = 1
        endif
        if DecisionPaths[1] == 0 and Rsi > 70 and MacdLine < SignalLine and SmaShort < SmaLong then
            SellSignal = 1
        endif
    endif
    
    // Plot Buy and Sell signals
    if BuySignal then
        DRAWARROWUP(BarIndex, Low, "BUY", "", Plain, Green)
    endif
    if SellSignal then
        DRAWARROWDOWN(BarIndex, High, "SELL", "", Plain, Red)
    endif
    // Plot Technical Indicators 
    RETURN SmaShort AS "SMA 14", SmaLong AS "SMA 50"
    

    He intentado la traducción pero aún contiene varios errores…Espero que los foreros puedan corregirlo y mejorarlo.

    #236263 quote
    Iván González
    Moderator
    Master

    Sería una cosa así:

    // Inicialización de los parámetros de entrada
    Depth = 3
    Paths = 3
    NumberOfWeights = 5
    // Inicialización del array de pesos
    Weight = 1.0 / NumberOfWeights
    SumNodeWeights = 0
    FOR i = 0 TO NumberOfWeights - 1 DO
    $NodeWeights[i] = Weight
    SumNodeWeights = SumNodeWeights + Weight
    NEXT
    // Generación de los caminos
    FOR p = 0 TO Paths - 1 DO
    SizeW = NumberOfWeights
    SumWeights = CEIL(SumNodeWeights)
        
    IF SizeW > 0 AND Depth > 0 AND SumWeights = 1 THEN
    FOR d = 1 TO Depth DO
    FOUND = 0
    FOR w = 0 TO 999 DO
    SelectWeightIndex = ROUND(Random (0,SizeW))
    Rng = Random(0,1)
    Weight = $NodeWeights[SelectWeightIndex]
    IF Weight >= Rng THEN
    $Paths[p] = SelectWeightIndex
    FOUND = 1
    BREAK
    ENDIF
    NEXT
    IF FOUND = 0 THEN
    
    ENDIF
    NEXT
    ENDIF
    NEXT
    //Mostrar el resultado de path de la última vela en el gráfico
    if islastbarupdate then
    for i=0 to lastset($paths) do
    path=$paths[i]
    drawtext("path#i#: #path#",barindex+10,low-i*averagetruerange[14](close))
    next
    endif
    // Indicadores técnicos
    SMAShort = Average[14](Close)
    SMALong = Average[50](Close)
    myMACDLine = MACDLine[12,26,9](Close)
    SignalLine = MACDSignal[12,26,9](Close)
    // Generar señales de compra y venta basadas en indicadores técnicos y caminos de decisión
    BuySignal = ($Paths[0]>0 AND (myMACDLine > SignalLine) AND (SMAShort > SMALong))
    SellSignal = ($Paths[0]=0 AND (myMACDLine < SignalLine) AND (SMAShort < SMALong))
    
    // Plotear señales de compra y venta
    IF BuySignal THEN
    DrawArrowUp(BarIndex, Low)
    elsiF SellSignal THEN
    DrawArrowDown(BarIndex, High)
    ENDIF
    
    return
    Fr7 thanked this post
Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.

CONVERSION INDICADOR TRADINGVIEW:Árbol de Decisión


ProBuilder: Indicadores y Herramientas

New Reply
Author
author-avatar
Fr7 @fr7 Participant
Summary

This topic contains 4 replies,
has 2 voices, and was last updated by Iván González
1 year, 6 months ago.

Topic Details
Forum: ProBuilder: Indicadores y Herramientas
Language: Spanish
Started: 08/06/2024
Status: Active
Attachments: No files
Logo Logo
Loading...