Estrategia cuantitativa de media móvil adaptativa


Fecha de creación: 2023-11-17 17:14:36 Última modificación: 2023-11-17 17:14:36
Copiar: 0 Número de Visitas: 713
1
Seguir
1617
Seguidores

Estrategia cuantitativa de media móvil adaptativa

Descripción general

Esta estrategia se basa en una media móvil, puede ajustar los parámetros automáticamente y se aplica en mercados con altos periodos de tiempo. Es capaz de encontrar automáticamente la combinación de parámetros óptima y generar una señal de negociación cuando el precio supera la media móvil.

Principio de estrategia

Esta estrategia utiliza una media móvil adaptativa como señal de negociación. Primero se calcula la media móvil simple para el período especificado de inicio. Luego se prueba una combinación de parámetros alrededor de la CMA para determinar qué combinación de líneas CMA son menos tocadas por la entidad de la línea K y la línea de sombra.

Concretamente, la estrategia prueba las líneas CMA, las líneas enteras estadísticas y las líneas de sombras después de los ciclos CMA más 1 ((CMA_P1) y menos 1 ((CMA_M1) de la frecuencia con la que se tocan. Si la CMA tiene menos frecuencias de contacto que CMA_P1 y CMA_M1, se mantiene el ciclo CMA actual; si la CMA_P1 tiene menos frecuencias de contacto, se agrega el ciclo CMA1; si la CMA_M1 tiene menos frecuencias de contacto, se reduce el ciclo CMA1. Así se puede encontrar un CMA relativamente liso como línea de señal.

Cuando el precio rompe el CMA de abajo hacia arriba, genera una señal de compra; cuando el precio rompe el CMA de arriba hacia abajo, genera una señal de venta.

Análisis de las ventajas

Esta estrategia de media móvil adaptativa tiene las siguientes ventajas:

  1. Busca automáticamente los parámetros óptimos. No es necesario seleccionar manualmente los períodos de las medias móviles. La estrategia prueba automáticamente los diferentes períodos para encontrar los parámetros óptimos.

  2. Reducción de falsas señales. En comparación con las medias móviles de período fijo, las medias móviles de adaptación pueden filtrar más ruido, lo que reduce muchas falsas señales.

  3. Adaptarse a los cambios en el mercado. Cuando el mercado entra en una tendencia desde la corrección, el ciclo de las medias móviles aumenta automáticamente para generar señales; cuando el mercado entra en una tendencia desde la corrección, el ciclo de las medias móviles se reduce automáticamente.

  4. Simplificación del sistema de transacciones. Esta forma de adaptación puede simplificar todo el sistema de transacciones sin la necesidad de parámetros de optimización manual.

  5. Escalable. La idea de la estrategia se puede extender a otros indicadores, diseñando estrategias como la adaptación a la banda de Brin, la adaptación a la KD.

Análisis de riesgos

La estrategia también tiene algunos riesgos a tener en cuenta:

  1. Riesgo de opciones de compra y venta. Cuando el mercado se presenta con una operación de opciones de compra y venta, la línea real no puede romper la media móvil, lo que puede causar una señal errónea. Se necesitan condiciones de filtración para reducir este tipo de riesgos.

  2. Riesgo de fracaso de la ruptura. La ruptura de la media móvil no siempre es continuation, existe el riesgo de fracaso parcial de la ruptura. Por lo tanto, se necesita una verificación de ruptura para garantizar la tasa de éxito de la ruptura.

  3. Riesgo de reversión de la tendencia. La reversión después de entrar en el mercado de tendencia requiere un cambio de dirección a tiempo, de lo contrario se producen pérdidas. Se pueden establecer condiciones de parada para controlar las pérdidas.

  4. Riesgo de optimización de parámetros. Los parámetros que se ajustan a sí mismos pueden caer en la optimización local, lo que produce un promedio móvil claramente redundante. Se necesita la introducción de métodos de evaluación de modelos para evitar este problema.

  5. Riesgo de optimización excesiva. Los parámetros de ajuste de adaptación pueden ser optimizados en exceso, mientras que se pierde la capacidad de generalización del modelo. Se requiere una verificación prolongada en diferentes entornos de mercado y no se puede depender excesivamente de los resultados de la retroalimentación.

Dirección de optimización

La estrategia de la media móvil adaptativa se puede optimizar en:

  1. Se añade un mecanismo de verificación de brechas de tendencia para filtrar las falsas brechas mediante brechas consecutivas.

  2. Aumentar la estrategia de stop loss cuando el precio regresa al otro lado de la media móvil.

  3. Se ha añadido un mecanismo de filtración de opciones para evitar señales erróneas en el mercado de opciones binarias.

  4. Introducir indicadores de evaluación para restringir el ajuste de parámetros, como IC, LIC, SIC, etc., para evitar que los parámetros sean excesivamente optimizados.

  5. Extensión a otros indicadores, diseño de estrategias adaptadas a la forca dorada, estrategias adaptadas a la franja de Brin, etc.

  6. Optimizar el cálculo de las medias móviles, utilizando medias móviles ponderadas, medias móviles de índices y medias móviles suavizadas.

Resumir

Esta estrategia se adapta a los ciclos de las medias móviles para buscar los parámetros óptimos y así generar señales comerciales. En comparación con los parámetros fijos, puede reducir muchas señales falsas y adaptarse a los cambios en el mercado. Pero también debemos tener en cuenta algunos riesgos potenciales que requieren verificación y optimización de la estrategia para obtener ganancias estables en el comercio real.

||

Overview

This strategy is based on moving average, can automatically adjust parameters, and is suitable for wavy markets at high timeframes. It can automatically find the optimal parameter combination and generate trading signals when price breaks through the moving average line.

Strategy Logic

This strategy uses an adaptive moving average as trading signal. First it calculates the simple moving average (CMA) of the specified period (start). Then it tests the CMA parameters around the period, judging which combination has the least touches by candlestick body and wick. Finally it uses the CMA with the least touches as the signal line.

Specifically, the strategy tests the CMA with period plus 1 (CMA_P1) and minus 1 (CMA_M1), counts the number of touches by body and wick. If CMA has less touches than CMA_P1 and CMA_M1, then keep the current period; if CMA_P1 has less touches, then increase the period by 1; if CMA_M1 has less touches, then decrease the period by 1. This finds a relatively smooth CMA as the signal line.

When price breaks through CMA upward, a buy signal is generated; when price breaks through CMA downward, a sell signal is generated.

Advantage Analysis

This adaptive moving average strategy has the following advantages:

  1. Automatically find optimal parameters. No need to manually select moving average period, the strategy will test different periods and find the optimum.

  2. Reduce false signals. Compared with fixed period MA, the adaptive MA can filter out more noise and reduce many false signals.

  3. Adapt to market changes. When market switches from range-bound to trending, the MA period will automatically increase to generate signals; when market switches from trending to range-bound, the MA period will automatically decrease. So the strategy can dynamically adapt to market changes.

  4. Simplify trading system. This adaptive method can simplify the whole trading system without manual parameter optimization.

  5. Good scalability. The concept can be applied to other indicators like adaptive Bollinger Bands, adaptive KD etc.

Risk Analysis

There are also some risks to note for this strategy:

  1. Call option risk. When market has a call option pattern, the candle body may fail to break the MA line, resulting in wrong signals. Filter conditions need to be added to reduce such risk.

  2. Failed breakout risk. MA breakout does not always continuation, some failed breakouts may occur. Breakout validation is needed to ensure high success rate.

  3. Trend reversal risk. Trend reversal after entering the trend needs to be switched timely, otherwise it may cause losses. Stop loss should be set to control the loss.

  4. Parameter optimization risk. Adaptive adjusted parameters may fall into local optimization, resulting in redundant MAs. Model evaluation methods need to be introduced to avoid this problem.

  5. Overfitting risk. Excessive parameter tuning may lead to overfitting and lose the model generalization ability. Prolonged verification in different market environments is needed, not just rely on backtest results.

Improvement Directions

Some directions to improve this adaptive MA strategy:

  1. Add trend breakout validation via consecutive breakouts to filter false breakouts.

  2. Increase stop loss strategy, stop loss when price moves back to the other side of MA.

  3. Add option filter to avoid wrong signals when call option appears.

  4. Introduce evaluation metrics like IC, LIC, SIC etc. to constrain parameter tuning and prevent overfitting.

  5. Expand to other indicators like adaptive golden cross strategy, adaptive Bollinger Bands etc.

  6. Optimize MA calculation by using weighted MA, exponential MA etc. to get smoother MA.

Summary

This strategy generates trading signals by adaptively adjusting the MA period to find optimal parameters. Compared with fixed parameters, it can reduce many false signals and adapt to market changes. But we also need to watch out for potential risks, and do verification and walk-forward optimization before applying it in live trading for steady profits.

[/trans]

Código Fuente de la Estrategia
/*backtest
start: 2022-11-10 00:00:00
end: 2023-11-16 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/
// © fondDealer96636

//@version=5

strategy('Automatic Moving Average', overlay=true, max_bars_back=201, pyramiding=0, currency=currency.USD, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000)

// input
start = 20
lookback = input(20, "Sensitivity", tooltip="Low (High Sensitivity), High (Low Sensitivity).\n\nAdjust according to timeframe and asset.")
smoothing = input(3, "Smoothing")
source = input(close, "Source")
startYear = input(2020, "Start year")
resp = 1

in_date_range = time >= timestamp(syminfo.timezone, startYear, 1, 1, 0, 0)

// global
var ix = -1
var mal = array.new_int(0)


// functions
avg(source, len) =>
    sum = 0.0
    for i = 0 to len-1
        sum += source[i]
    sum/len

bull = close > open

wick_touch(x) =>
    bull ? ((close <= x and x <= high) or (low <= x and x <= open)) : ((open <= x and x <= high) or (low <= x and x <= close))

body_touch(x) =>
    bull ? (open < x and x < close) : (close < x and x < open)

touches(t) =>
    touches = 0
    for i = 0 to lookback-1
        touches += t[i] ? 1 : 0
    touches


// local
ix := ix+1
prev_mal = ix >= 1 ? array.get(mal, ix-1) : start

cma = avg(source, prev_mal)
cma_p1 = avg(source, prev_mal+1)
cma_m1 = avg(source, prev_mal-1)

d = touches(wick_touch(cma))
d_p1 = touches(wick_touch(cma_p1))
d_m1 = touches(wick_touch(cma_m1))

d_b = touches(body_touch(cma))
d_p1_b = touches(body_touch(cma_p1))
d_m1_b = touches(body_touch(cma_m1))

any_body_touch = d_b > 0 or d_p1_b > 0 or d_m1_b > 0
no_wick_touch = d <= 0 and d_p1 <= 0 and d_m1 <= 0
wick_maximized = d >= d_p1 and d >= d_m1 ? prev_mal : (d_p1 >= d and d_p1 >= d_m1 ? prev_mal+resp : (d_m1 >= d and d_m1 >= d_p1 ? prev_mal-resp : na))

up = cma > cma[1]
down = cma < cma[1]
against_trend = (up and close < cma) or (down and close > cma)

new_mal = no_wick_touch or against_trend ? prev_mal-resp : (any_body_touch ? prev_mal+resp : wick_maximized)
next_mal = na(new_mal) ? prev_mal : new_mal

array.push(mal, next_mal < 2 ? 2 : (next_mal > 200 ? 200 : next_mal))


// graph
scma = ta.ema(cma, smoothing)

uptrend = scma > scma[1]
downtrend = scma < scma[1]

plot(scma, "Automatic MA", color=uptrend ? color.green : color.red)

uptrending = close > scma and uptrend
downtrending = close < scma and downtrend

defy = not uptrending and not downtrending
defy_cross = defy and body_touch(scma)

barcolor(uptrending ? color.lime : (downtrending ? color.red : (defy_cross ? color.black : color.white)))


// strategy
change_to_uptrend = uptrending and downtrend[1]
change_to_downtrend = downtrending and uptrend[1]

long = in_date_range and change_to_uptrend
short = in_date_range and change_to_downtrend

if long
    strategy.entry("Long", strategy.long)
if short
    strategy.entry("Short", strategy.short)