Crear backtest en 2 marcos temporales

Viewing 9 posts - 1 through 9 (of 9 total)
  • Author
    Posts
  • #213829 quote
    mamees
    Participant
    New

    Buenas tardes y gracias por la ayuda de antemano.

    Estoy intentando hacer un backtest que cumpla condiciones en los 2 marcos temporales (semanal y diario).

    Basicamente lo que quiero es que cuando en el diario, la media 20 y 40 sean inferior a la media de 200, si el precio toca la media de 200, compre cuando cruce a la baja la media de 200 el precio.

    A su vez en el semanal, el precio de la vela semanal, debe de estar por debajo de la media 20 semanal.

    Este es el codigo:

    //Definir variables
    TIMEFRAME(weekly)
    mS20 = average[20](close)
    
    CondicionSemanal=close<mS20
    
    TIMEFRAME(default)
    avgv5 = average[5](volume)
    avgv20 = average[20](volume)
    avgv50 = average[50](volume)
    avgv100 = average[100](volume)
    avgv200 = average[200](volume)
    m200 = average[200](close)
    m1 = average[1](high)
    m20 = average[20](close)
    m40 = average[20](close)
    VolumenK=300
    minimoVolumen =  avgv5>VolumenK*1000 and avgv20>VolumenK*1000 and avgv50>VolumenK*1000 and avgv100>VolumenK*1000 and avgv200>VolumenK*1000
    
    //Condiciones a cumplir
    CondicionPrecioVol=close>1 and open>1 and minimoVolumen
    CondicionMedias=m200>m20 and m200>m40
    if CondicionPrecioVol and CondicionMedias then
    CondicionCortos=m1 crosses under m200
    endif
    
    //Condiciones take profit
    CondicionCompraCortos=m1 crosses under m40 and CondicionSemanal
    
    // Condiciones de entrada de posiciones cortas
    IF NOT ShortOnMarket AND CondicionCortos THEN
    SELLSHORT 1000 share AT MARKET
    ENDIF
    
    // Condiciones de salida de posiciones cortas
    IF ShortOnMarket AND CondicionCompraCortos THEN
    EXITSHORT AT MARKET
    ENDIF
    
    // Stops y targets: introduzca aquí sus stops de protección y targets de beneficios
    

     

    Y en la imagen, como vemos, compra cuando cumple la parte diaria, no las 2 a la vez.

    Y quiero que cumpla las 2 a la vez, como hace pocos dias.

    backtest.png backtest.png
    #213882 quote
    robertogozzi
    Moderator
    Master

    Reemplace la línea 31 con esto:

    IF NOT ShortOnMarket AND CondicionCortos AND CondicionSemanal THEN
    mamees thanked this post
    #213908 quote
    mamees
    Participant
    New

    Vaya! Cierto, se me escapo!

    Ahora al código de antes, quiero añadir un bucle FOR, que es el que usare para tener los máximos relevantes crecientes (te lo marco en la imagen).

    Que es para mi el máximo relevante?: es aquel máximo que es su high es mayor que los 3 de su derecha y los 3 de su izquierda (de ahí el bucle for).

    Una vez tenga identificados los máximos relevantes, quiero que sean crecientes por debajo de la media de 200 (serian los que te marco en la imagen).

    Ese bucle FOR, si lo pongo en un proscreener si me funciona (sustituyo barindex por 0) pero al ponerlo en backtest, imagino que el 0 lo deberé sustituir por barindex, pero no me funciona.

    Muchas Gracias por la ayuda de antes y con esto!

    //Definir variables
    TIMEFRAME(weekly)
    mS20 = average[20](close)
    CondicionSemanal=close<mS20
    
    TIMEFRAME(default)
    avgv5 = average[5](volume)
    avgv20 = average[20](volume)
    avgv50 = average[50](volume)
    avgv100 = average[100](volume)
    avgv200 = average[200](volume)
    m200 = average[200](close)
    m1 = average[1](high)
    m20 = average[20](close)
    m40 = average[40](close)
    VolumenK=300
    minimoVolumen =  avgv5>VolumenK*1000 and avgv20>VolumenK*1000 and avgv50>VolumenK*1000 and avgv100>VolumenK*1000 and avgv200>VolumenK*1000
    
    CondicionMaxCrecientesDebajoM200=0
    c1M200=0
    c2M200=0
    max1=0
    max2=0
    for maxi=barindex to barindex+251
    if maxi>=3 then
    maxRel=(high[maxi]>=high[maxi-3]) AND (high[maxi]>=high[maxi-2]) AND (high[maxi]>=high[maxi-1]) AND (high[maxi]>=high[maxi+1]) AND (high[maxi]>=high[maxi+2]) AND (high[maxi]>=high[maxi+3])
    if maxRel then
    if max1=0 then
    max1=high[maxi]
    c1M200=high[maxi]<m200
    elsif max2=0 then
    max2=high[maxi]
    c2M200=high[maxi]<m200
    break
    endif
    endif
    endif
    next
    
    if (max1>max2 and c1M200 and c2M200) then
    CondicionMaxCrecientesDebajoM200=1
    endif
    
    //Condiciones a cumplir
    CondicionPrecioVol=close>1 and open>1 and minimoVolumen and CondicionMaxCrecientesDebajoM200
    CondicionMedias=m200>m20 and m200>m40
    if CondicionPrecioVol and CondicionMedias then
    CondicionCortos=m1 crosses under m200
    endif
    
    //Condiciones take profit
    CondicionCompraCortos=m1 crosses under m40
    
    // Condiciones de entrada de posiciones cortas
    IF NOT ShortOnMarket AND CondicionCortos AND CondicionSemanal THEN
    SELLSHORT 1000 share AT MARKET
    ENDIF
    
    // Condiciones de salida de posiciones cortas
    IF ShortOnMarket AND CondicionCompraCortos THEN
    EXITSHORT AT MARKET
    ENDIF
    
    // Stops y targets: introduzca aquí sus stops de protección y targets de beneficios
    
    backtestFOR.png backtestFOR.png
    #213932 quote
    robertogozzi
    Moderator
    Master

    No está muy claro lo que quieres hacer.
    ¿Puedes explicar mejor cuáles son las condiciones para entrar en una operación?

    #213939 quote
    mamees
    Participant
    New

    No se como usar el bucle FOR, en un proscreener si, pero en backtest no.
    En el proscreener le suelo poner de 0 a 251. En el backtest como seria? BarIndex?

    Las condiciones que quiero hacer es:
    Quiero detectar que las medias de 20 y 40 esten por debajo de la media de 200.
    Antes de que el precio cruce la media de 200, quiero que tenga 2 maximos relevantes crecientes (lo que te marco con las flechas rojas).
    Una vez, el precio cruza la media de 200, en el momento que la cruza hacia abajo es cuando buscaria la compra.

    En la imagen, las flechas rosas, es un indicador que me cree para detectar los maximos relevantes (que los 3 maximos a su izquierda sean menor y que los 3 maximos de su derecha tambien).
    Te añado el codigo del indicador por si sirve.

    Te adjuntare el codigo proscreener que uso.

    //maximo mimino relevante.
    m20 = average[20]
    centro=3
    maximo = high[centro]
    minimo = low [centro]
    maxrelevante= 1
    minrelevante= 1
    
    
    //vela verde max y roja inhalacion
    rangoCuerpoME2=close[centro]-open[centro]
    rangoCuerpoE2=open[2]-close[2]
    cumpleE2Inhalacion=rangoCuerpoME2>0 and rangoCuerpoE2>0
    rcE2=0
    
    if (close[2] < close[centro] and cumpleE2Inhalacion) then
    rcE2=1
    endif
    //vela verde y roja max y inhalacion
    rangoCuerpoME2=close[centro+1]-open[centro+1]
    rangoCuerpoE2=open[centro]-close[centro]
    cumpleE2Inhalacion=rangoCuerpoME2>0 and rangoCuerpoE2>0
    rcE2a=0
    if (rcE2=0 and close[centro]<close[centro+1] and cumpleE2Inhalacion) then
    rcE2a=1
    endif
    
    
    //vela roja min y verde inhalacion
    rangoCuerpoME4=open[centro]-close[centro]
    rangoCuerpoE4=close[2]-open[2]
    cumpleE4Inhalacion=rangoCuerpoME4>0 and rangoCuerpoE4>0
    rcE4=0
    if (close[2] > close[centro] and cumpleE4Inhalacion) then
    rcE4=1
    endif
    
    //vela roja y verde min y inhalacion
    rangoCuerpoME4=open[centro+1]-close[centro+1]
    rangoCuerpoE4=close[centro]-open[centro]
    cumpleE4Inhalacion=rangoCuerpoME4>0 and rangoCuerpoE4>0
    rcE4a=0
    if (rcE4=0 and close[centro]>close[centro+1] and cumpleE4Inhalacion) then
    rcE4a=1
    endif
    
    for i=0 to centro*2
    if i<>centro then
    if low[i] < minimo then
    minrelevante=0
    endif
    if high[i] > maximo then
    maxrelevante=0
    endif
    endif
    next
    
    IF minrelevante=1 THEn
    DRAWARROWUP (barindex-centro,minimo-(minimo*0.01)) coloured(231, 155, 208)
    m20bajista=(m20[centro]-m20)>0
    if rcE4 and m20bajista then
    //DRAWELLIPSE(barindex-centro-1, low[centro]-(low[centro]*0.01), barindex-1, high[centro-1]+(high[centro-1]*0.01)) coloured(102, 178, 255)
    endif
    if rcE4a and m20bajista then
    //DRAWELLIPSE(barindex-centro-2, high[centro+1]+(high[centro+1]*0.01), barindex-centro+1, low[centro]-(low[centro]*0.01)) coloured(102, 178, 255)
    endif
    ENDIF
    IF maxrelevante=1 THEn
    
    m20alcista=(m20-m20[centro])>0
    DRAWARROWDOWN (barindex-centro,maximo+(maximo*0.01)) coloured(231, 155, 208)
    if rcE2 and m20alcista then
    //DRAWELLIPSE(barindex-centro-1, maximo+(maximo*0.01), barindex-1, low[2]-(low[2]*0.01)) coloured(231, 155, 208)
    endif
    if rcE2a and m20alcista then
    //DRAWELLIPSE(barindex-centro-2, low[centro]-(low[centro]*0.01), barindex-centro+1, high[centro]+(high[centro]*0.01)) coloured(231, 155, 208)
    endif
    //if (open[2] > close[centro]) and  (range[2] > range[centro]*0.5) then
    //DRAWARROWDOWN (barindex-2,maximo+(maximo*0.01)) coloured(255, 255, 255)
    //endif
    ENDIF
    
    return
    
    patron=0
    TIMEFRAME(daily)
    avgv5 = average[5](volume)
    avgv20 = average[20](volume)
    avgv50 = average[50](volume)
    avgv100 = average[100](volume)
    avgv200 = average[200](volume)
    minimoVolumen =  avgv5>VolumenK*1000 and avgv20>VolumenK*1000 and avgv50>VolumenK*1000 and avgv100>VolumenK*1000 and avgv200>VolumenK*1000
    
    TIMEFRAME(weekly)
    if close>1 and open>1 and minimoVolumen then
    min1=0
    min2=0
    for mini=0 to 251
    if mini>=3 then
    EsMini=(low[mini]<=low[mini-3]) AND (low[mini]<=low[mini-2]) AND (low[mini]<=low[mini-1]) AND (low[mini]<=low[mini+1]) AND (low[mini]<=low[mini+2]) AND (low[mini]<=low[mini+3])
    
    
    if EsMini then
    if min1=0 then
    min1=low[mini]
    elsif min2=0 then
    min2=low[mini]
    break
    endif
    endif
    endif
    next
    if min1<min2 then
    distanciaRentabilidad=((close-min1)/close)*100
    if distanciaRentabilidad>rentabilidad then
    patron=1
    endif
    endif
    endif
    
    if patron then
    patron=0
    TIMEFRAME(daily)
    m200 = average[200](close)
    if close<m200 then
    c1M200=0
    c2M200=0
    c3M200=0
    max1=0
    max2=0
    for maxi=0 to 251
    if maxi>=3 then
    maxRel=(high[maxi]>=high[maxi-3]) AND (high[maxi]>=high[maxi-2]) AND (high[maxi]>=high[maxi-1]) AND (high[maxi]>=high[maxi+1]) AND (high[maxi]>=high[maxi+2]) AND (high[maxi]>=high[maxi+3])
    if maxRel then
    if max1=0 then
    max1=high[maxi]
    c1M200=high[maxi]<m200
    elsif max2=0 then
    max2=high[maxi]
    c2M200=high[maxi]<m200
    break
    endif
    endif
    endif
    next
    
    min1t=0
    min2t=0
    for minit=0 to 251
    if minit >=3 then
    EsMinit = (low[minit]<=low[minit-3]) AND (low[minit]<=low[minit-2]) AND (low[minit]<=low[minit-1]) AND (low[minit]<=low[minit+1]) AND (low[minit]<=low[minit+2]) AND (low[minit]<=low[minit+3])
    
    if EsMinit then
    if min1t=0 then
    min1t=low[minit]
    c3M200=low[minit]<m200
    elsif min2t=0 then
    min2t=low[minit]
    break
    endif
    endif
    endif
    next
    if (max1>max2 and c1M200 and c2M200 and min1t>min1t and c3M200) or (close>max1 and close>max2 and c1M200 and c2M200 and c3M200) then
    maximo=0
    minimo=9999
    for i=0 to 3
    if maximo<high[i] then
    maximo=high[i]
    endif
    if minimo>low[i] then
    minimo=low[i]
    endif
    next
    if m200>minimo and m200<maximo then
    patron=1
    endif
    endif
    endif
    endif
    screener[patron]
    
    #213970 quote
    mamees
    Participant
    New

    He solucionado lo del bucle for.

    Como podria poner el stop?

    En la imagen, la flecha roja seria la vela que quiero que haga de estop, en verde te marco la entrada en cortos.

    Para indicar la flecha roja, le digo que cuando haga la compra, coja el maximo de las ultimas 10 velas (highest[10](close), pero como ves en la imagen, no hace caso y se “compra” al dia siguiente.

    Como le puedo indicar que quiero el maximo del precio que estaba por encima de la m200?

    Muchas gracias!

    TIMEFRAME(default)
    avgv5 = average[5](volume)
    avgv20 = average[20](volume)
    avgv50 = average[50](volume)
    avgv100 = average[100](volume)
    avgv200 = average[200](volume)
    m200 = average[200](close)
    m1 = average[1](high)
    m20 = average[20](close)
    m40 = average[40](close)
    
    // Condicion  de minimo volumen
    VolumenK=300
    minimoVolumen =  avgv5>VolumenK*1000 and avgv20>VolumenK*1000 and avgv50>VolumenK*1000 and avgv100>VolumenK*1000 and avgv200>VolumenK*1000
    
    // Condicion de tener maximos crecientes o etapa 2
    CondicionMaxCrecientesDebajoM200=0
    c1M200=0
    c2M200=0
    max1=0
    max2=0
    for maxi=0 to 251
    if maxi>=3 then
    maxRel=(high[maxi]>=high[maxi-3]) AND (high[maxi]>=high[maxi-2]) AND (high[maxi]>=high[maxi-1]) AND (high[maxi]>=high[maxi+1]) AND (high[maxi]>=high[maxi+2]) AND (high[maxi]>=high[maxi+3])
    if maxRel then
    if max1=0 then
    max1=high[maxi]
    c1M200=high[maxi]<m200
    elsif max2=0 then
    max2=high[maxi]
    c2M200=high[maxi]<m200
    break
    endif
    endif
    endif
    next
    
    if ((max1>max2 or (close>max1 and close>max2)) and c1M200 and c2M200 ) then
    CondicionMaxCrecientesDebajoM200=1
    endif
    
    //Condiciones de que la m200 este por encima de la m20 y m40
    CondicionMedias=m200>m20 and m200>m40
    
    // Condicion para comprar
    CondicionCortosCondicionesMinimas=close>1 and open>1 and minimoVolumen and CondicionMaxCrecientesDebajoM200 and CondicionMedias
    
    if CondicionCortosCondicionesMinimas then
    if m1 crosses under m200 then
    CondicionCortos=m1 crosses under m200
    // Ponemos el stoploss
    Stoploss=highest[10](close)
    endif
    endif
    
    
    
    //Condiciones take profit
    CondicionCompraCortos=max2
    
    // Condiciones de entrada de posiciones cortas
    IF NOT ShortOnMarket AND CondicionCortos THEN
    SELLSHORT 1000 share AT MARKET
    ENDIF
    
    // Condiciones de salida de posiciones cortas
    IF ShortOnMarket AND close>Stoploss THEN
    EXITSHORT AT MARKET
    ENDIF
    
    // Stops y targets: introduzca aquí sus stops de protección y targets de beneficios
    
    stoploss.png stoploss.png
    #213973 quote
    robertogozzi
    Moderator
    Master

    No puedo entender muy bien lo que hace tu código, si no me escribes tus condiciones no puedo ayudarte.

    #214023 quote
    mamees
    Participant
    New

    No importa, lo he conseguido hacer funcionar. Empiezo a entender que es muy parecido al proscreener.

    Una ultima duda, en el backtest, cuando tengo puesto que compre o venda, lo hace en la vela siguiente, como puedo hacer que sea cuando toque el precio? Y no esperar a que se ejecute en la siguiente vela?

     

    Y muchas gracias por todo.

    #214032 quote
    robertogozzi
    Moderator
    Master

    Debe usar órdenes pendientes (STOP o LIMIT) para colocar órdenes a un precio exacto.
    Pero necesita saber cuándo colocar una orden pendiente por adelantado, lo cual, en la mayoría de los casos, no es posible. En este escenario, debe usar varios marcos de tiempo, el que usa actualmente y uno más pequeño que reacciona rápidamente cuando se detecta una señal.

Viewing 9 posts - 1 through 9 (of 9 total)
  • You must be logged in to reply to this topic.

Crear backtest en 2 marcos temporales


ProOrder: Trading Automático y Backtesting

New Reply
Author
author-avatar
mamees @mamees Participant
Summary

This topic contains 8 replies,
has 2 voices, and was last updated by robertogozzi
2 years, 10 months ago.

Topic Details
Forum: ProOrder: Trading Automático y Backtesting
Language: Spanish
Started: 04/28/2023
Status: Active
Attachments: 3 files
Logo Logo
Loading...