Estrategia de pruebas de retroceso dinámicas de varios marcos de tiempo

El autor:¿ Qué pasa?, Fecha: 2023-11-21 17:07:17
Las etiquetas:

img

Resumen general

Esta estrategia emplea un mecanismo de backtesting dinámico de varios marcos de tiempo para determinar las tendencias de los precios mediante la comparación de los precios más altos y más bajos en diferentes períodos de tiempo, logrando así un arbitraje de bajo riesgo.

Estrategia lógica

La estrategia recupera el precio más alto (nhigh) y el precio más bajo (nlow) a través de diferentes marcos de tiempo llamando a la función personalizada f_get_htfHighLow. Específicamente, basada en entradas definidas por el usuario como resolución de período de tiempo, multiplicador de período de tiempo HTFMultiplier, parámetros de backtesting lookhead y gaps, y offset, invoca la función de seguridad para obtener los precios más altos y más bajos en diferentes marcos de tiempo.

Por ejemplo, un desplazamiento de 0 recupera los precios más altos y más bajos de la barra actual, mientras que un desplazamiento de 1 recupera esos precios de la barra anterior.

Si los precios más altos y más bajos suben, se identifica una tendencia alcista. Si ambos precios caen, se ve una tendencia bajista. Se toman posiciones de largo o corto plazo en función de la dirección de la tendencia para implementar operaciones de arbitraje.

Ventajas

  1. Mejora de la precisión mediante análisis de marcos de tiempo múltiples
  2. Evita la repintura a través de backtesting dinámico
  3. Parámetros flexibles para adaptarse a los cambios del mercado
  4. En el caso de las posiciones de tendencias claras, el riesgo reducido

Los riesgos

  1. Equivocos en varios marcos de tiempo
  2. Repintado a partir de parámetros de backtesting incorrectos
  3. Los altos costes y el deslizamiento por operaciones excesivas

Soluciones:

  1. Optimizar los períodos de tiempo para la precisión
  2. Los parámetros de ensayo deben ser rigurosos para evitar la repintura
  3. Condiciones de entrada moderadas para controlar la frecuencia

Oportunidades de mejora

  1. Añadir ML para aprovechar la IA para las tendencias
  2. Incorporar filtros de volatilidad para el dimensionamiento dinámico de las posiciones
  3. Introducir paradas para limitar eficazmente las pérdidas

Conclusión

La lógica de la estrategia es clara, utilizando backtesting dinámico de múltiples marcos de tiempo para determinar tendencias y minimizar el sesgo humano.


/*backtest
start: 2022-11-14 00:00:00
end: 2023-11-20 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed

//@version=4
strategy("HTF High/Low Repaint Strategy", overlay=true, initial_capital = 20000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)

i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time)
inDateRange = true

resolution = input("3M", type=input.resolution)
HTFMultiplier = input(22, minval=1, step=1)
offset = input(0, minval=0, step=1)
lookahead = input(true)
gaps = false

f_secureSecurity_on_on(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
f_secureSecurity_on_off(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_off)
f_secureSecurity_off_on(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_off, gaps=barmerge.gaps_on)
f_secureSecurity_off_off(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_off, gaps=barmerge.gaps_off)

f_multiple_resolution(HTFMultiplier) => 
    target_Res_In_Min = timeframe.multiplier * HTFMultiplier * (
      timeframe.isseconds   ? 1. / 60. :
      timeframe.isminutes   ? 1. :
      timeframe.isdaily     ? 1440. :
      timeframe.isweekly    ? 7. * 24. * 60. :
      timeframe.ismonthly   ? 30.417 * 24. * 60. : na)

    target_Res_In_Min     <= 0.0417       ? "1S"  :
      target_Res_In_Min   <= 0.167        ? "5S"  :
      target_Res_In_Min   <= 0.376        ? "15S" :
      target_Res_In_Min   <= 0.751        ? "30S" :
      target_Res_In_Min   <= 1440         ? tostring(round(target_Res_In_Min)) :
      tostring(round(min(target_Res_In_Min / 1440, 365))) + "D"

f_get_htfHighLow(resolution, HTFMultiplier, lookahead, gaps, offset)=>
    derivedResolution = resolution == ""?f_multiple_resolution(HTFMultiplier):resolution
    nhigh_on_on = f_secureSecurity_on_on(syminfo.tickerid, derivedResolution, high, offset) 
    nlow_on_on = f_secureSecurity_on_on(syminfo.tickerid, derivedResolution, low, offset)
    
    nhigh_on_off = f_secureSecurity_on_off(syminfo.tickerid, derivedResolution, high, offset) 
    nlow_on_off = f_secureSecurity_on_off(syminfo.tickerid, derivedResolution, low, offset)
    
    nhigh_off_on = f_secureSecurity_off_on(syminfo.tickerid, derivedResolution, high, offset) 
    nlow_off_on = f_secureSecurity_off_on(syminfo.tickerid, derivedResolution, low, offset)
    
    nhigh_off_off = f_secureSecurity_off_off(syminfo.tickerid, derivedResolution, high, offset) 
    nlow_off_off = f_secureSecurity_off_off(syminfo.tickerid, derivedResolution, low, offset)
    
    nhigh = lookahead and gaps ? nhigh_on_on :
             lookahead and not gaps ? nhigh_on_off :
             not lookahead and gaps ? nhigh_off_on :
             not lookahead and not gaps ? nhigh_off_off : na
    nlow = lookahead and gaps ? nlow_on_on :
             lookahead and not gaps ? nlow_on_off :
             not lookahead and gaps ? nlow_off_on :
             not lookahead and not gaps ? nlow_off_off : na
    [nhigh, nlow]
    
[nhigh, nlow] = f_get_htfHighLow(resolution, HTFMultiplier, lookahead, gaps, offset)
[nhighlast, nlowlast] = f_get_htfHighLow(resolution, HTFMultiplier, lookahead, gaps, offset+1)
plot(nhigh , title="HTF High",style=plot.style_circles, color=color.green, linewidth=1) 
plot(nlow , title="HTF Low",style=plot.style_circles, color=color.red, linewidth=1)

buyCondition = nhigh > nhighlast and nlow > nlowlast
sellCondition = nhigh < nhighlast and nlow < nlowlast

strategy.entry("Buy", strategy.long, when= buyCondition and inDateRange, oca_name="oca_buy")
strategy.entry("Sell", strategy.short, when= sellCondition and inDateRange, oca_name="oca_sell")


Más.