Estrategia EMV de volatilidad simple

El autor:La bondad, Creado: 2020-07-01 10:39:17, Actualizado: 2023-10-28 15:26:49

img

Resumen de las actividades

A diferencia de otros indicadores técnicos, Ease of Movement Value refleja cambios en el precio, volumen y popularidad. Es una tecnología que combina los precios y los cambios de volumen. Mide el cambio de precio del volumen unitario, formando un indicador de volatilidad de precios. Cuando el mercado gana popularidad y la transacción está activa, solicita una señal de compra; cuando el volumen de negociación es bajo y la energía del mercado está a punto de agotarse, solicita una señal de venta.

La EMV de volatilidad simple está diseñada de acuerdo con el principio de gráfico de volumen igual y gráfico comprimido. Su concepto central es: el precio del mercado consumirá mucha energía solo cuando la tendencia gire o esté a punto de girar, y el rendimiento externo es que el volumen de negociación se vuelve más grande. Cuando el precio está subiendo, no consumirá demasiada energía debido al efecto de impulso. Aunque esta idea es contraria a la opinión de que tanto la cantidad como el aumento del precio, tiene sus propias características únicas.

Fórmula para el cálculo de la EMV

Paso 1: Calcular mov_mid

Entre ellos, TH representa el precio más alto del día, TL representa el precio más bajo del día, YH representa el precio más alto del día anterior y YL representa el precio más bajo del día anterior.

img

Paso 2: Calcular la proporción

Entre ellos, TVOL representa el volumen de operaciones del día, TH representa el precio más alto del día y TL representa el precio más bajo del día.

img

Paso 3: Calcular el valor de emisión

img

Uso de VEM

El autor de EMV cree que el gran aumento se acompaña de un rápido agotamiento de la energía, y el aumento a menudo no dura demasiado tiempo; por el contrario, el volumen moderado, que puede ahorrar cierta cantidad de energía, a menudo hace que el aumento dure más tiempo. Una vez que se forma una tendencia al alza, un menor volumen de negociación puede empujar los precios hacia arriba, y el valor de EMV aumentará. Una vez que se forma el mercado de tendencia bajista, a menudo se acompaña de un declive infinito o pequeño, y el valor de EMV disminuirá. Si el precio está en un mercado volátil o los aumentos y caídas de precios se acompañan de un gran volumen, el valor de EMV también estará cerca de cero.

El uso de EMV es bastante simple, solo mira si el EMV cruza el eje cero. Cuando el EMV está por debajo de 0, representa un mercado débil; cuando el EMV está por encima de 0, representa un mercado fuerte. Cuando el EMV cambia de negativo a positivo, debe comprarse; cuando el EMV cambia de positivo a negativo, debe venderse. Su característica es que no solo puede evitar el mercado de choque en el mercado, sino también entrar en el mercado a tiempo cuando comienza el mercado de tendencia. Sin embargo, debido a que el EMV refleja el cambio de volumen cuando los precios cambian, solo tiene un efecto en las tendencias a medio y largo plazo.

Realización de la estrategia

Paso 1: redactar un marco estratégico

# Strategy main function
def onTick():
     pass

# Program entry
def main():
     while True: # Enter infinite loop mode
         onTick() # execution strategy main function
         Sleep(1000) # sleep for 1 second

FMZ.COMEn primer lugar, es necesario definir unamainFunción yonTickLa funciónmainFunción es la función de entrada de la estrategia, y el programa ejecutará la línea de código por línea de lamainEn el caso de losmainFunción, escriba unwhileel bucle y ejecutar repetidamente elonTickTodo el código básico de la estrategia está escrito en elonTick function.

Paso 2: Obtener datos de posición

def get_position():
     position = 0 # The number of assigned positions is 0
     position_arr = _C(exchange.GetPosition) # Get array of positions
     if len(position_arr)> 0: # If the position array length is greater than 0
         for i in position_arr: # Traverse the array of positions
             if i['ContractType'] =='IH000': # If the position symbol is equal to the subscription symbol
                 if i['Type']% 2 == 0: # if it is long position
                     position = i['Amount'] # Assign a positive number of positions
                 else:
                     position = -i['Amount'] # Assign the number of positions to be negative
     return position # return position quantity

Porque en esta estrategia, sólo se utiliza el número de posiciones en tiempo real, con el fin de facilitar el mantenimiento,get_positionSi la posición actual es larga, devuelve un número positivo, y si la posición actual es corta, devuelve un número negativo.

Paso 3: Obtener datos de la línea K

exchange.SetContractType('IH000') # Subscribe to futures variety
bars_arr = exchange.GetRecords() # Get K-line array
if len(bars_arr) <10: # If the number of K lines is less than 10
     return

Antes de obtener datos específicos de la línea K, primero debe suscribirse a un contrato comercial específico, utilizar elSetContractTypeFunción deFMZ.COMSi desea saber otra información sobre el contrato, también puede utilizar una variable para recibir estos datos.GetRecordsfunción para obtener datos de línea K, porque el devuelto es una matriz, por lo que usamos la variablebars_arrpara aceptarlo.

Paso 4: Calcular el valor de emisión

bar1 = bars_arr[-2] # Get the previous K-line data
bar2 = bars_arr[-3] # get the previous K-line data
# Calculate the value of mov_mid
mov_mid = (bar1['High'] + bar1['Low']) / 2-(bar2['High'] + bar2['Low']) / 2
if bar1['High'] != bar1['Low']: # If the dividend is not 0
     # Calculate the value of ratio
     ratio = (bar1['Volume'] / 10000) / (bar1['High']-bar1['Low'])
else:
     ratio = 0
# If the value of ratio is greater than 0
if ratio> 0:
     emv = mov_mid / ratio
else:
     emv = 0

Aquí, no usamos el precio más reciente para calcular el valor de EMV, sino que usamos la línea K de corriente relativamente rezagada para emitir la señal y colocar una línea K para emitir una orden. El propósito de esto es hacer que la prueba posterior esté más cerca del comercio real. Sabemos que aunque el software de comercio cuantitativo ahora es muy avanzado, todavía es difícil simular completamente el entorno de tick de precio real, especialmente cuando se enfrenta a la prueba posterior de datos largos de nivel de barra, por lo que se utiliza este método de compromiso.

Paso 5: Posición de las órdenes

current_price = bars_arr[-1]['Close'] # latest price
position = get_position() # Get the latest position
if position> 0: # If you are holding long positions
    if emv <0: # If the current price is less than teeth
        exchange.SetDirection("closebuy") # Set the trading direction and type
        exchange.Sell(round(current_price-0.2, 2), 1) # close long position
if position <0: # If you are holding short positions
    if emv> 0: # If the current price is greater than the teeth
        exchange.SetDirection("closesell") # Set the trading direction and type
        exchange.Buy(round(current_price + 0.2, 2), 1) # close short position
if position == 0: # If there is no holding position
    if emv> 0: # If the current price is greater than the upper lip
        exchange.SetDirection("buy") # Set the trading direction and type
        exchange.Buy(round(current_price + 0.2, 2), 1) # open long position
    if emv <0: # if the current price is smaller than the chin
        exchange.SetDirection("sell") # Set the trading direction and type
        exchange.Sell(round(current_price-0.2, 2), 1) # open short position

Antes de colocar el pedido, necesitamos determinar dos datos, uno es el precio del pedido y el otro es el estado de la posición actual. El precio de colocar un pedido es muy simple, sólo utilizar el precio de cierre actual para agregar o restar el precio mínimo de cambio de la variedad.get_positionFinalmente, la posición se abre y cierra de acuerdo con la relación posicional entre el EMV y el eje cero.

Prueba posterior de la estrategia

Configuración de pruebas de retroceso

img

Registro de pruebas de retroceso

img img

Curva del capital

img

Estrategia completa

# Backtest configuration
'''backtest
start: 2019-01-01 00:00:00
end: 2020-01-01 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
'''


def get_position():
     position = 0 # The number of assigned positions is 0
     position_arr = _C(exchange.GetPosition) # Get array of positions
     if len(position_arr)> 0: # If the position array length is greater than 0
         for i in position_arr: # Traverse the array of positions
             if i['ContractType'] =='IH000': # If the position symbol is equal to the subscription symbol
                 if i['Type']% 2 == 0: # if it is long position
                     position = i['Amount'] # Assign a positive number of positions
                 else:
                     position = -i['Amount'] # Assign the number of positions to be negative
     return position # return position quantity


# Strategy main function
def onTick():
     # retrieve data
     exchange.SetContractType('IH000') # Subscribe to futures
     bars_arr = exchange.GetRecords() # Get K-line array
     if len(bars_arr) <10: # If the number of K lines is less than 10
         return

     # Calculate emv
     bar1 = bars_arr[-2] # Get the previous K-line data
     bar2 = bars_arr[-3] # get the previous K-line data
     # Calculate the value of mov_mid
     mov_mid = (bar1['High'] + bar1['Low']) / 2-(bar2['High'] + bar2['Low']) / 2
     if bar1['High'] != bar1['Low']: # If the dividend is not 0
          # Calculate the value of ratio
          ratio = (bar1['Volume'] / 10000) / (bar1['High']-bar1['Low'])
     else:
          ratio = 0
     # If the value of ratio is greater than 0
     if ratio> 0:
          emv = mov_mid / ratio
     else:
          emv = 0

     # Placing orders
     current_price = bars_arr[-1]['Close'] # latest price
     position = get_position() # Get the latest position
     if position> 0: # If you are holding long positions
          if emv <0: # If the current price is less than teeth
               exchange.SetDirection("closebuy") # Set the trading direction and type
               exchange.Sell(round(current_price-0.2, 2), 1) # close long position
     if position <0: # If you are holding short positions
          if emv> 0: # If the current price is greater than the teeth
               exchange.SetDirection("closesell") # Set the trading direction and type
               exchange.Buy(round(current_price + 0.2, 2), 1) # close short position
     if position == 0: # If there is no holding position
          if emv> 0: # If the current price is greater than the upper lip
               exchange.SetDirection("buy") # Set the trading direction and type
               exchange.Buy(round(current_price + 0.2, 2), 1) # open long position
     if emv <0: # if the current price is smaller than the chin
               exchange.SetDirection("sell") # Set the trading direction and type
               exchange.Sell(round(current_price-0.2, 2), 1) # open short position

# Program entry
def main():
     while True: # Enter infinite loop mode
         onTick() # execution strategy main function
         Sleep(1000) # sleep for 1 second

La estrategia completa se ha publicado en el cuadrado de estrategia de laFMZ.COMpágina web, y se puede utilizar haciendo clic en copiar.https://www.fmz.com/strategy/213636

En resumen

A través de este curso de estudio, podemos ver que EMV es contrario a los comerciantes ordinarios, pero no es irrazonable. Debido a que EMV introduce datos de volumen, es más eficaz que otros indicadores técnicos que utilizan cálculos de precios para averiguar qué hay detrás del precio. Cada estrategia tiene características diferentes. Solo al comprender completamente las ventajas y desventajas de diferentes estrategias y eliminar la escoria y extraer su esencia podemos ir más lejos del éxito.


Relacionados

Más.