Monday, 6 November 2017

Mdfa Forex


Esta última entrada de Chris es particular en el sentido de que se basa en mi paquete de código abierto MDFA (en lugar de en iMetrica) para generar señales de comercio, ver 1. Por lo tanto, los resultados son reproducibles. Chris hizo un gran esfuerzo de replicación, vea a continuación: Miércoles 20: He añadido el código R modificado por Chris para proceder a la replicación. Lo que sigue es Chris8217email, cortado y pegado de mi servidor: quotSo acabo de terminar el tutorial de introducción muy esperado sobre cómo construir señales comerciales usando MDFA y R para datos de alta frecuencia. No hay demasiados secretos para esconderme aquí, como lo que hice en R con tu código es principalmente la misma rutina que uso para construir mis señales comerciales en iMetrica (excepto que puedo hacer cosas mucho mucho más rápido en el segundo8230 y ok, allí Son sólo algunas pequeñas salsas secretas que usan y que todavía no están dispuestas a salirse hasta que yo trabajo. Pero en lo que respecta a este ejemplo con el Yen, todo (debe) ser reproducible en casa usando una versión (ligeramente modificada) de su código. Aquí está el artículo 1. Un desafío que enfrenté en la construcción de estos ejemplos vino de compararlos con mis resultados que consigo en iMetrica. Desafortunadamente, al principio los resultados no eran los mismos. Después de estar un poco frustrado, tomé el esfuerzo minucioso de descubrir por qué mis rutinas MDFA en C son diferentes a las suyas en R. Mine están codificadas de una manera mucho más optimizada y eficiente para lograr la velocidad más rápida posible (gracias a una rápida apophenia optimizando Paquete para ensamblar las matrices y resolver los coeficientes). Sin embargo, los resultados finales deben ser equivalentes. Después de un día de navegación a través de ambas o nuestras implementaciones MDFA, descubrí por qué no son equivalentes (y las cambié en su código). Aquí están las diferencias (que puedo recordar) de mi implementación y la suya (a partir de su lanzamiento de noviembre): 8211 Computing the DFTs. Por alguna razón, a la frecuencia cero, no usa la media de los datos. Usted acaba de ponerlo a cero. No estoy seguro si dejó esto en accidente o de propósito, pero yo uso el medio. Además, divido los valores de DFT por la constante (pin) donde n es el número de observaciones en series de tiempo. 8211 En la definición del parámetro decay1, don8217t parece utilizar el mapeado de la función tan. Yo si. 8211 La mayor diferencia está en la definición de la función de suavizado (definida por peso). En primer lugar, dividir expweight por 2, dividir por 10. No es un gran negocio. El gran trato es esto. Mi definición de la función de potencia desplazada es una función del valor de frecuencia (así de 0 a 3.14). La suya es una función de la ubicación del índice de valores de frecuencia, entre 0 y K. Esto hace una gran diferencia. Prefiero definir la función de potencia con respecto al valor de frecuencia y no al índice. Después de haber cambiado estos los resultados fueron más o menos lo mismo, pero no es exacto. Al examinar la matriz final (al resolver Axb para los coeficientes) después de aplicar la regularización y la personalización, parece que los valores dentro de la matriz A están fuera de un factor de aproximadamente 10. Mi intuición es que las complejas funciones de exp en R y C se calculan ligeramente diferentes (mejor / peor precisión, no lo sé). Así que no estoy seguro si esto es algo que nunca podremos resolver. Pero no estoy preocupado, ya que los resultados finales están tan cerca. De hecho, no afectó a ninguno de los oficios en mis ejemplos que demuestran, que eran los mismos en iMetrica. Y eso es lo más importante. De todos modos, puedo enviarle mi versión de su código si lo desea, para que la gente pueda descargarlo para probar los ejemplos. O puede considerar estos cambios y hacerlos permanentes en futuras versiones de MDFA. Déjame saber, y disfruta el artículo. Trabajas demasiado, viejo. Su cabello ha sido R de color R-tejer y R-cepillado viene a la mente también. Por cierto, la consistencia se mide al revés: iMetrica debe ser capaz de replicar I-MDFA que es la referencia. Mi código MDFA modificado por Chris (ver comentarios anteriores) DFT. r. I8217m trabajando siempre con la serie centrada por lo tanto el DFT en la frecuencia cero es cero (it8217s proporcional a la media). Chris no parece trabajar con series centradas: su DFT es diferente de cero en freq. cero. I-MDFAnew. r. Parece que la ponderación de amplitud de peso ha sido alterada y supongo que el término lambda-decaimiento también ha sido modificado. Ten en cuenta que no modifico mi última versión de I-MDFA: las modificaciones anteriores son útiles si quieres replicar los resultados de Chris8217 (pero me quedo con mi versión). A fin de realizar la replicación you8217ll tienen que requerir los datos de él. Deja un comentario Cancelar respuestaFigura 1: En la muestra (observaciones 1-250) y fuera de la muestra de rendimiento de la señal de comercio construido en este tutorial con MDFA. (Arriba) El precio de registro del Yen (FXY) en intervalos de 15 minutos y los oficios generados por la señal comercial. Aquí la línea negra es una compra (larga), el azul es la venta (posición corta). (Inferior) Los rendimientos acumulados (efectivo) generados por la negociación, en porcentaje ganado o perdido. En mi artículo anterior sobre comercio de alta frecuencia en iMetrica en el FOREX / GLOBEX. Introduje algunas estrategias robustas de extracción de señales en iMetrica utilizando el enfoque de filtro directo multidimensional (MDFA) para generar señales de alto rendimiento para negociar en el mercado de divisas y futuros. En este artículo tomo una breve ausencia de mi mundo de desarrollo de señales de comercio financiero en iMetrica y emigrar a un lenguaje muy popular utilizado en finanzas debido a su exuberante gama de paquetes, gestión de datos rápida y manejo de gráficos y de Por supuesto, el hecho de que sea libre (como en el habla y la cerveza) en casi cualquier plataforma de computación en el mundo. Este artículo ofrece un tutorial introductorio sobre el uso de R para el comercio de alta frecuencia en el mercado FOREX utilizando el paquete R para MDFA (ofrecido por Herr Doktor Marc Wildi von Bern) y algunas estrategias que se desarrollaron para generar señales de comercio financieramente robusto. Para este tutorial, considero el segundo ejemplo dado en mi artículo anterior en el que diseñé una señal de comercio para los log-returns de 15 minutos del yen japonés (desde la apertura de la campana al cierre del mercado EST). Esto presentó desafíos ligeramente nuevos como antes, ya que las variaciones de salto cercano a abierto son mucho mayores que las generadas por las devoluciones horarias o diarias. Pero como demostré, estas variaciones más grandes en precio cercano a abierto no plantearon problemas para el MDFA. De hecho, explotó estos saltos e hizo grandes ganancias al predecir la dirección del salto. La figura 1 en la parte superior de este artículo muestra el desempeño de la muestra (observaciones 1-250) y fuera de la muestra (observaciones 251 en adelante) del filtro que se va a construir en la primera parte de este tutorial. A lo largo de este tutorial, intento replicar estos resultados que construí en iMetrica y expandirlos un poco usando el lenguaje R y la implementación del MDFA disponible aquí. Los datos que consideramos son log-returns de 15 minutos del Yen del 4 de enero al 17 de enero y los he guardado como un archivo. RData dado por ldfxyinsamp. Tengo una serie explicativa adicional incrustada en el archivo. RData que utiliza I8217m para predecir el precio del yen. Además, también voy a utilizar pricefxyinsamp que es el precio de registro de Yen, utilizado para calcular el rendimiento (compra / venta) de la señal de comercio. El ldfxyinsamp se utilizará como datos de la muestra para construir el filtro y la señal de trading para FXY. Para obtener estos datos para que pueda realizar estos ejemplos en su casa, envíeme un correo electrónico y le enviaré todos los archivos. RData necesarios (los datos en la muestra y fuera de la muestra) en un archivo. zip. Haciendo un vistazo rápido a los datos de ldfxyinsamp, vemos log-returns del Yen cada 15 minutos comenzando en el mercado abierto (zona horaria UTC). Los datos objetivo (Yen) están en la primera columna junto con las dos series explicativas (Yen y otro activo integrado con el movimiento de Yen). Gt head (ldfxyinsamp), 1, 2, 3 2013-01-04 13:30:00 0.000000e00 0.000000e00 0.0000000000 2013-01-04 13:45:00 4.763412e-03 4.763412e-03 0.0033465833 2013-01-04 14:00:00 -8.966599e-05 -8.966599e-05 0.0040635638 2013-01-04 14:15:00 2.597055e-03 2.597055e-03 -0.0008322064 2013-01-04 14:30:00 -7.157556e - 04 -7.157556e-04 0.0020792190 2013-01-04 14:45:00 -4.476075e-04 -4.476075e-04 -0.0014685198 Siguiendo adelante, para empezar a construir la primera señal comercial para el Yen, comenzamos por subir los datos en Nuestro entorno R, define algunos parámetros iniciales para la llamada a la función MDFA, y luego calcula los DFT y el periodograma para el Yen. Como he mencionado en mis artículos anteriores, mi estrategia paso a paso para construir señales comerciales siempre comienza con un análisis rápido del periodograma del activo que se negocia. Sosteniendo la llave para proporcionar la penetración en las características de cómo el activo negocia, el periodogram es una herramienta esencial para navegar cómo el extractor es elegido. Aquí, busco los picos espectrales principales que corresponden en el dominio del tiempo a cómo y dónde mi señal activará las operaciones de compra / venta. La Figura 2 muestra el periodograma de los log-returns de 15 minutos del yen japonés durante el período de la muestra del 4 de enero al 17 de enero de 2013. Las flechas apuntan a los principales picos espectrales que busco y proporcionan una guía de cómo Definirá mi función. Las líneas punteadas negras indican los dos puntos de corte de frecuencia que consideraré en este ejemplo, el primero y el segundo en. Observe que ambos puntos de corte se establecen directamente después de un pico espectral, algo que recomiendo encarecidamente. En el comercio de alta frecuencia en el FOREX usando MDFA, como veremos, el truco es buscar el pico espectral que explica la variación cercana a abrir en el precio de la moneda extranjera. Queremos aprovechar este pico espectral, ya que aquí es donde las grandes ganancias en el comercio de divisas usando MDFA se producirá. Figura 2: Periodograma de FXY (Yen japonés) junto con picos espectrales y dos puntos de corte de frecuencia diferentes. En nuestro primer ejemplo, consideramos la frecuencia más grande como el punto de corte para establecerla en (la línea más a la derecha en la figura del periodograma). A continuación, inicialmente establecer los parámetros de puntualidad y suavidad, y expweight a 0 junto con la configuración de todos los parámetros de regularización a 0 también. Esto me dará un barómetro para dónde y cuánto ajustar los parámetros del filtro. En la selección de la longitud del filtro, mis estudios empíricos sobre numerosos experimentos en la construcción de señales de comercio utilizando iMetrica han demostrado que una 8216good8217 elección es en cualquier lugar entre 1/4 y 1/5 de la longitud total de la muestra de la serie temporal de datos. Por supuesto, la longitud depende de la frecuencia de las observaciones de los datos (es decir, 15 minutos, hora, día, etc.), pero en general es muy probable que nunca necesite más de 1/4 del tamaño de la muestra. De lo contrario, la regularización puede llegar a ser demasiado engorrosa para manejar eficazmente. En este ejemplo, la longitud total de la muestra es 335 y, por lo tanto, establezco lo que seguirá durante el resto de este tutorial. En cualquier caso, la longitud del filtro no es el parámetro más importante a considerar en la construcción de buenas señales comerciales. Para una buena selección robusta de los parámetros de filtro pareja con las series explicativas adecuadas, los resultados de la señal de comercio en comparación con, digamos, difícilmente difieren. Si lo hacen, entonces la parametrización no es lo suficientemente robusta. Después de cargar tanto los datos de regreso de registro de la muestra junto con el precio de registro correspondiente del Yen para calcular el rendimiento de negociación, procedemos a establecer ajustes de filtro iniciales para la rutina MDFA y luego calcular el filtro utilizando la función IMDFAcomp. Esto devuelve los coeficientes de retención de objetos imdfaamp, funciones de respuesta de frecuencia y estadísticas de filtro, junto con la señal producida para cada serie explicativa. Combinamos estas señales para obtener la señal de comercio final en la muestra. Todo esto se hace en R como sigue: Las funciones de respuesta de frecuencia resultantes del filtro y los coeficientes se representan en la figura siguiente. Figura 3: Las funciones de respuesta de frecuencia del filtro (arriba) y los coeficientes de filtro (abajo) Obsérvese la abundancia de ruido que sigue presente tras la frecuencia de corte. Esto se suaviza aumentando el parámetro de suavidad de expweight. Los coeficientes de cada serie explicativa muestran cierta correlación en su movimiento a medida que aumentan los retrasos. Sin embargo, la suavidad y la decadencia de los coeficientes deja mucho que desear. Solucionaremos esto introduciendo parámetros de regularización. Las gráficas de la se~nal de negociación de la muestra y el rendimiento de la muestra en la muestra se muestran en las dos figuras siguientes. Observe que la señal comercial se comporta muy bien en la muestra. Sin embargo, las miradas pueden ser engañosas. Este rendimiento estelar se debe en gran parte a un fenómeno de filtración llamado overfitting. Se puede deducir que la superposición es el culpable aquí, simplemente mirando la no uniformidad de los coeficientes junto con el número de grados congelados de libertad, que en este ejemplo es aproximadamente 174 (de 174), demasiado alto. Nos gustaría obtener este número en alrededor de la mitad de la cantidad total de grados de libertad (número de series explicativas x L). Figura 4: La señal de negociación y los datos de log-return del Yen. El rendimiento en la muestra de este filtro demuestra el tipo de resultados que nos gustaría ver después de la regularización se aplica. Pero ahora viene para los efectos de sobriedad de overfitting. Aplicamos estos coeficientes de filtro a 200 observaciones de 15 minutos del yen ya las series explicativas del 18 de enero al 1 de febrero de 2013 y se comparan con las características de la muestra. Para ello en R, primero cargan los datos fuera de muestra en el entorno R y, a continuación, aplicamos el filtro a los datos fuera de muestra que definí como xout. El diagrama de la figura 5 muestra la señal de comercio fuera de la muestra. Observe que la señal no es tan suave como en la muestra. También es obvio que se superan los datos en algunas áreas. Aunque las características de sobreejecución fuera de la muestra de la señal no son horriblemente sospechosas, no confiaría en este filtro para producir retornos estelares a largo plazo. Figura 5. Filtro aplicado a 200 observaciones de 15 minutos de Yen fuera de muestra para producir señal de trading (mostrada en azul) Después del análisis previo de la solución de cuadrado medio (sin personalización ni regularización), ahora procedemos a limpiar el Problema de overfitting que era aparente en los coeficientes junto con mollifying el ruido en el stopband (frecuencias después). Para elegir los parámetros de suavizado y regularización, una aproximación es aplicar primero el parámetro de suavidad, ya que esto suavizará generalmente los coeficientes mientras actúa como regularizador 8216pre8217, y luego avanzará a la selección de controles de regularización apropiados. Al observar los coeficientes (Figura 3), podemos ver que es necesaria una buena cantidad de suavizado, con un ligero toque de decaimiento. Para seleccionar estos dos parámetros en R, una opción es usar el optimizador Troikaner (encontrado aquí) para encontrar una combinación adecuada (Tengo un enfoque algorítmico de salsa secreta que desarrollé para iMetrica para elegir combinaciones óptimas de parámetros dado un extractor y un indicador de rendimiento , Aunque it8217s largo (incluso en GNU C) y engorroso de usar, por lo que normalmente prefieren la estrategia discutida en este tutorial). En este ejemplo, empecé por establecer el lambdasmooth a .5 y el decaimiento a (.1, .1) junto con un parámetro de suavidad de expweight establecido en 8.5. Después de ver los coeficientes, todavía no era suficiente suavidad, así que procedí a añadir más finalmente alcanzando .63, que hizo el truco. Entonces elegí lambda para equilibrar los efectos de la suavidad expweight (lambda es siempre el último ajuste de ajuste del parámetro). La Figura 6 muestra la función de respuesta de frecuencia resultante para ambas series explicativas (Yen en rojo). Observe que el mayor pico espectral encontrado directamente antes del corte de frecuencia en está enfatizado y ligeramente atenuado (valor cercano a 0,8 en lugar de 1,0). Los otros picos espectrales a continuación están también presentes. Para los coeficientes, se aplicó suficiente suavizado y decaimiento para mantener intacta la estructura lag, cíclica y correlacionada de los coeficientes, pero ahora se ven mucho más agradables en su forma suavizada. El número de grados de libertad congelados se ha reducido a aproximadamente 102. Figura 6: Se han aplicado las funciones de respuesta en frecuencia y los coeficientes después de la regularización y el alisamiento (arriba). Los coeficientes suavizados con ligera caries al final (fondo). El número de grados de libertad congelados es de aproximadamente 102 (de 172). Junto con una mejora de los grados de libertad freezed y sin aparente estrago de overfitting, aplicamos este filtro fuera de la muestra a las 200 observaciones fuera de la muestra con el fin de verificar la mejora en la estructura de los coeficientes de filtro (se muestra a continuación en Figura 7). Observe la tremenda mejoría en las propiedades de la señal comercial (en comparación con la Figura 5). La superación de los datos se ha eliminado y la suavidad general de la señal ha mejorado significativamente. Esto se debe al hecho de que hemos erradicado la presencia de sobreequipamiento. Figura 7: Señal de comercio fuera de la muestra con regularización. Con todas las indicaciones de un filtro dotado de exactamente las características que necesitamos para la robustez, ahora aplicamos la señal comercial tanto en la muestra como fuera de la muestra para activar las operaciones de compra / venta y ver el rendimiento de la cuenta de negociación en valor en efectivo. Cuando la señal cruza por debajo de cero, vendemos (entra en posición corta) y cuando la señal sube por encima de cero, compramos (entramos en posición larga). El diagrama superior de la figura 8 es el precio de registro del yen para los intervalos de 15 minutos y las líneas de puntos representan exactamente donde la señal de negociación generó operaciones (cruce cero). Las líneas punteadas negras representan una compra (posición larga) y las líneas azules indican una venta (y posición corta). Observe que la señal predijo todos los saltos cercanos a abrir para el Yen (en parte gracias a las series explicativas). Esto es exactamente lo que estaremos luchando para cuando agregamos regularización y personalización al filtro. La cuenta de efectivo de las operaciones durante el período de la muestra se muestra a continuación, donde los costos de transacción se fijaron en 0,05 por ciento. En la muestra, la señal ganó aproximadamente un 6 por ciento en 9 días de negociación y una proporción de éxito de negociación del 76 por ciento. Figura 8: Rendimiento en la muestra del nuevo filtro y los oficios que se generan. Ahora para la prueba final para ver qué tan bien el filtro realiza en la producción de una señal ganadora de comercio, aplicamos el filtro a la 200 15 minutos de observación fuera de muestra del yen y las series explicativas del 18 de enero al 1 de febrero y hacer Operaciones basadas en el cruce por cero. Los resultados se muestran a continuación en la Figura 9. Las líneas negras representan las compras y las líneas azules que se venden (shorts). Observe que el filtro todavía es capaz de predecir los saltos cercanos a abrir incluso fuera de la muestra gracias a la regularización. El filtro sucumbe a sólo tres diminutas pérdidas a menos del 0,08 por ciento cada una entre las observaciones 160 y 180 y una pequeña pérdida al principio, con una proporción de éxito comercial fuera de la muestra alcanzando el 82 por ciento y un ROI de poco más del 4 por ciento sobre El intervalo de 9 días. Figura 9: Rendimiento fuera de muestra del filtro regularizado en 200 retornos de 15 minutos fuera de muestra del Yen. El filtro alcanzó un ROI del 4 por ciento sobre las 200 observaciones y una proporción de éxito del comercio del 82 por ciento. Compare esto con los resultados obtenidos en iMetrica usando la misma configuración de parámetros MDFA. En la Figura 10, se muestra tanto el rendimiento dentro de la muestra como fuera de la muestra. El rendimiento es casi idéntico. Figura 10: Rendimiento dentro y fuera de muestra del filtro Yen en iMetrica. Casi idéntico al rendimiento obtenido en R. Ejemplo 2 Ahora tomamos una puñalada en la producción de otro filtro de comercio para el Yen, sólo que esta vez queremos identificar sólo las frecuencias más bajas para generar una señal comercial que negocia menos a menudo, sólo buscando los ciclos más grandes . Al igual que con el rendimiento del filtro anterior, todavía deseamos orientar las frecuencias que podrían ser responsables a las grandes variaciones cercanas a abrir en el precio del yen. Para ello, seleccionamos nuestro punto de corte para que mantenga efectivamente los tres picos espectrales más grandes intactos en la banda de paso bajo de. Para este nuevo filtro, mantenemos las cosas simples al seguir utilizando los mismos parámetros de regularización elegidos en el filtro anterior, ya que parecían producir buenos resultados fuera de la muestra. Sin embargo, los parámetros de personalización de expweight deben ajustarse para tener en cuenta los nuevos requisitos de supresión de ruido en la banda de parada y las propiedades de fase en la banda de paso más pequeña. Por lo tanto, aumento el parámetro de suavizado y disminuye el parámetro de oportunidad (que sólo afecta a la banda de paso) para explicar este cambio. Las nuevas funciones de respuesta en frecuencia y coeficientes de filtro para este diseño de paso bajo más pequeño se muestran a continuación en la Figura 11. Obsérvese que el segundo pico espectral se contabiliza y sólo se suaviza ligeramente bajo los nuevos cambios. Los coeficientes todavía tienen la suavidad y decadencia notable en los retrasos más grandes. Figura 11: Funciones de respuesta en frecuencia de los dos filtros y sus correspondientes coeficientes. Para probar la efectividad de este nuevo diseño de frecuencia de transacción menor, aplicamos los coeficientes de filtro a las 200 observaciones fuera de muestra de los logs de retorno de Yen de 15 minutos. El rendimiento se muestra a continuación en la Figura 12. En este filtro, vemos claramente que el filtro todavía logra predecir correctamente los grandes saltos cercanos a abrir en el precio del Yen. Sólo se observan tres pérdidas totales durante el período de 9 días. El rendimiento general no es tan atractivo como el anterior diseño del filtro, ya que se produce menos cantidad de operaciones, con un ROI cercano al 2 por ciento y una proporción de éxito del comercio del 76 por ciento. Sin embargo, este diseño podría encajar las prioridades para un comerciante mucho más sensible a los costos de transacción. Figura 12: Rendimiento fuera de muestra del filtro con corte inferior. Conclusión La verificación y la validación cruzada es importante, tal como lo dirá el hombre más interesante del mundo. El objetivo de este tutorial fue mostrar algunos de los principales conceptos y estrategias que experimento al abordar el problema de construir una señal de comercio robusta y altamente eficiente para cualquier activo dado en cualquier frecuencia. También quería ver si podía lograr resultados similares con el paquete R MDFA como mi paquete de software iMetrica. Los resultados terminaron siendo casi paralelos a excepción de algunas diferencias menores. Los principales puntos que trataba de destacar fueron, en primer lugar, analizar el periodograma para buscar los picos espectrales importantes (como los que se asocian con las variaciones cercanas a las abiertas) y para demostrar cómo la elección del corte afecta el comercio sistemático. Here8217s un resumen rápido sobre las buenas estrategias y hacks a tener en cuenta. Resumen de las estrategias para la construcción de comercio de señal utilizando MDFA en R: Como he mencionado antes, el periodograma es su mejor amigo. Aplique el corte inmediatamente después de cualquier rango de picos espectrales que desee considerar. Estos picos son los que generan los oficios. Utilice una opción de longitud de filtro no mayor de 1/4. Nada más grande es innecesario. Comience por calcular el filtro en el sentido medio-cuadrado, es decir, sin utilizar ninguna personalización o regularización y ver exactamente lo que necesita ser aprobado mediante la visualización de las funciones de respuesta de frecuencia y coeficientes para cada serie explicativa. Un buen rendimiento de la señal de comercio en la muestra (e incluso fuera de la muestra en la mayoría de los casos) carece de sentido a menos que los coeficientes tengan sólidas características robustas tanto en el dominio de la frecuencia como en el dominio del retraso. Recomiendo comenzar con ajustar el parámetro de personalización smoothness expweight y los parámetros de regularización lambdasmooth primero. A continuación, proceda con sólo ligeros ajustes a los parámetros de lambdadecay. Finalmente, como último recurso, la personalización lambda. Realmente nunca me molesto en mirar a lambdacross. Rara vez ha ayudado de manera significativa. Dado que los datos que estamos utilizando para orientar y construir señales comerciales son log-returns, no hay necesidad de preocuparse nunca con i1 e i2. Éstos son para los extractores de señales verdaderamente avanzados y pacientes, y sólo deben dejarse para aquellos dotados de iMetrica. Si tiene alguna pregunta o desea los datos de Yen de alta frecuencia que he utilizado en estos ejemplos, no dude en ponerse en contacto conmigo e I8217ll enviar Ellos a usted. Hasta la próxima vez, feliz extracción 8220 Tomando una rápida mirada a los datos ldfxyinsamp, vemos log-devoluciones del Yen cada 15 minutos a partir de mercado abierto (zona horaria UTC). Los datos de destino (Yen) están en la primera columna junto con las dos series explicativas (Yen y otro activo cointegrado con el movimiento de Yen) .8221 Por lo tanto, en su archivo en entrada, utilice el registro (close-returns) Y 2) y otro activo ¿Puede decirme más sobre este otro activo cointegred. Cómo lo encuentras Si bien no es tan obvio determinar un conjunto de variables explicativas que mejorarán el rendimiento de la señal (y el comercio), he desarrollado una herramienta llamada análisis de componentes de frecuencia fundamental que me ayuda a elegir series con fuertes lag s correlaciones en ciertas frecuencias interesadas I8217m In. El método parece funcionar bastante bien hasta ahora en mi experiencia. Gracias Chris, ¿has planeado otro hilo en las próximas semanas? Sí, tengo muchas ideas nuevas para artículos y escribiré una en breve. He estado ocupado en los últimos dos meses mejorando aún más la metodología, haciéndola aún más robusta para el comercio financiero. El problema es que empiezo a regalar muchos de mis secretos y eventualmente perderé mi ventaja competitiva, así que necesito seguir siendo un poco críptico. 15 minutos creo que 15 minutos es un buen rango, cuanto menor sea la frecuencia, mejor y más robusta será la señal. Sin embargo, en la práctica I8217m que actualmente utiliza 5 minutos vuelve con una firma comercial propietaria en Chicago en Index Futures. Filtra la hora en sus datos. Usted comercio sólo de 13:30 pm hasta las 20:00 You overnight Tagged with FOREX Figura 1: En la muestra (observaciones 1-250) y fuera de la muestra de rendimiento de la señal de comercio construido en este tutorial utilizando MDFA. (Arriba) El precio de registro del Yen (FXY) en intervalos de 15 minutos y los oficios generados por la señal comercial. Aquí la línea negra es una compra (larga), el azul es la venta (posición corta). (Inferior) Los rendimientos acumulados (efectivo) generados por la negociación, en porcentaje ganado o perdido. En mi artículo anterior sobre comercio de alta frecuencia en iMetrica en el FOREX / GLOBEX. Introduje algunas estrategias robustas de extracción de señales en iMetrica utilizando el enfoque de filtro directo multidimensional (MDFA) para generar señales de alto rendimiento para negociar en el mercado de divisas y futuros. En este artículo tomo una breve ausencia de mi mundo de desarrollo de señales de comercio financiero en iMetrica y emigrar a un lenguaje muy popular utilizado en finanzas debido a su exuberante gama de paquetes, gestión de datos rápida y manejo de gráficos y de Por supuesto, el hecho de que sea libre (como en el habla y la cerveza) en casi cualquier plataforma de computación en el mundo. Este artículo ofrece un tutorial introductorio sobre el uso de R para el comercio de alta frecuencia en el mercado FOREX utilizando el paquete R para MDFA (ofrecido por Herr Doktor Marc Wildi von Bern) y algunas estrategias que se desarrollaron para generar señales de comercio financieramente robusto. Para este tutorial, considero el segundo ejemplo dado en mi artículo anterior en el que diseñé una señal de comercio para los log-returns de 15 minutos del yen japonés (desde la apertura de la campana al cierre del mercado EST). Esto presentó desafíos ligeramente nuevos como antes, ya que las variaciones de salto cercano a abierto son mucho mayores que las generadas por las devoluciones horarias o diarias. Pero como demostré, estas variaciones más grandes en precio cercano a abierto no plantearon problemas para el MDFA. De hecho, explotó estos saltos e hizo grandes ganancias al predecir la dirección del salto. La figura 1 en la parte superior de este artículo muestra el desempeño de la muestra (observaciones 1-250) y fuera de la muestra (observaciones 251 en adelante) del filtro que se va a construir en la primera parte de este tutorial. A lo largo de este tutorial, intento replicar estos resultados que construí en iMetrica y expandirlos un poco usando el lenguaje R y la implementación del MDFA disponible aquí. Los datos que consideramos son log-returns de 15 minutos del Yen del 4 de enero al 17 de enero y los he guardado como un archivo. RData dado por ldfxyinsamp. Tengo una serie explicativa adicional incrustada en el archivo. RData que utiliza I8217m para predecir el precio del yen. Además, también voy a utilizar pricefxyinsamp que es el precio de registro de Yen, utilizado para calcular el rendimiento (compra / venta) de la señal de comercio. El ldfxyinsamp se utilizará como datos de la muestra para construir el filtro y la señal de trading para FXY. Para obtener estos datos para que pueda realizar estos ejemplos en su casa, envíeme un correo electrónico y le enviaré todos los archivos. RData necesarios (los datos en la muestra y fuera de la muestra) en un archivo. zip. Haciendo un vistazo rápido a los datos de ldfxyinsamp, vemos log-returns del Yen cada 15 minutos comenzando en el mercado abierto (zona horaria UTC). Los datos objetivo (Yen) están en la primera columna junto con las dos series explicativas (Yen y otro activo integrado con el movimiento de Yen). Gt head (ldfxyinsamp), 1, 2, 3 2013-01-04 13:30:00 0.000000e00 0.000000e00 0.0000000000 2013-01-04 13:45:00 4.763412e-03 4.763412e-03 0.0033465833 2013-01-04 14:00:00 -8.966599e-05 -8.966599e-05 0.0040635638 2013-01-04 14:15:00 2.597055e-03 2.597055e-03 -0.0008322064 2013-01-04 14:30:00 -7.157556e - 04 -7.157556e-04 0.0020792190 2013-01-04 14:45:00 -4.476075e-04 -4.476075e-04 -0.0014685198 Siguiendo adelante, para empezar a construir la primera señal de comercio para el Yen, comenzamos por subir los datos en Nuestro entorno R, define algunos parámetros iniciales para la llamada a la función MDFA, y luego calcula los DFT y el periodograma para el Yen. Como he mencionado en mis artículos anteriores, mi estrategia paso a paso para construir señales comerciales siempre comienza con un análisis rápido del periodograma del activo que se negocia. Sosteniendo la llave para proporcionar la penetración en las características de cómo el activo negocia, el periodogram es una herramienta esencial para navegar cómo el extractor es elegido. Aquí, busco los picos espectrales principales que corresponden en el dominio del tiempo a cómo y dónde mi señal activará las operaciones de compra / venta. La Figura 2 muestra el periodograma de los log-returns de 15 minutos del yen japonés durante el período de la muestra del 4 de enero al 17 de enero de 2013. Las flechas apuntan a los principales picos espectrales que busco y proporcionan una guía de cómo Definirá mi función. Las líneas punteadas negras indican los dos puntos de corte de frecuencia que consideraré en este ejemplo, el primer ser y el segundo en. Tenga en cuenta que ambos puntos de corte se establecen directamente después de un pico espectral, algo que recomiendo encarecidamente. In high-frequency trading on the FOREX using MDFA, as we8217ll see, the trick is to seek out the spectral peak which accounts for the close-to-open variation in the price of the foreign currency. We want to take advantage of this spectral peak as this is where the big gains in foreign currency trading using MDFA will occur. Figure 2: Periodogram of FXY (Japanese Yen) along with spectral peaks and two different frequency cutoffs. In our first example we consider the larger frequency as the cutoff for by setting it to (the right most line in the figure of the periodogram). I then initially set the timeliness and smoothness parameters, and expweight to 0 along with setting all the regularization parameters to 0 as well. This will give me a barometer for where and how much to adjust the filter parameters. In selecting the filter length , my empirical studies over numerous experiments in building trading signals using iMetrica have demonstrated that a 8216good8217 choice is anywhere between 1/4 and 1/5 of the total in-sample length of the time series data. Of course, the length depends on the frequency of the data observations (i. e. 15 minute, hourly, daily, etc.), but in general you will most likely never need more than being greater than 1/4 the in-sample size. Otherwise, regularization can become too cumbersome to handle effectively. In this example, the total in-sample length is 335 and thus I set which I8217ll stick to for the remainder of this tutorial. In any case, the length of the filter is not the most crucial parameter to consider in building good trading signals. For a good robust selection of the filter parameters couple with appropriate explanatory series, the results of the trading signal with compared with, say, should hardly differ. If they do, then the parameterization is not robust enough. After uploading both the in-sample log-return data along with the corresponding log price of the Yen for computing the trading performance, we the proceed in R to setting initial filter settings for the MDFA routine and then compute the filter using the IMDFAcomp function. This returns both the imdfaamp object holding coefficients, frequency response functions, and statistics of filter, along with the signal produced for each explanatory series. We combine these signals to get the final trading signal in-sample. All this is all done in R as follows: The resulting frequency response functions of the filter and the coefficients are plotted in the figure below. Figure 3: The Frequency response functions of the filter (top) and the filter coefficients (below) Notice the abundance of noise still present passed the cutoff frequency. This is mollified by increasing the expweight smoothness parameter. The coefficients for each explanatory series show some correlation in their movement as the lags increase. However, the smoothness and decay of the coefficients leaves much to be desired. We will remedy this by introducing regularization parameters. Plots of the in-sample trading signal and the performance in-sample of the signal are shown in the two figures below. Notice that the trading signal behaves quite nicely in-sample. However, looks can be deceiving. This stellar performance is due in large part to a filtering phenomenon called overfitting. One can deduce that overfitting is the culprit here by simply looking at the nonsmoothness of the coefficients along with the number of freezed degrees of freedom, which in this example is roughly 174 (out of 174), way too high. We would like to get this number at around half the total amount of degrees of freedom (number of explanatory series x L). Figure 4: The trading signal and the log-return data of the Yen. The in-sample performance of this filter demonstrates the type of results we would like to see after regularization is applied. But now comes for the sobering effects of overfitting. We apply these filter coeffcients to 200 15-minute observations of the Yen and the explanatory series from January 18 to February 1 2013 and compare with the characteristics in-sample. To do this in R, we first load the out-of-sample data into the R environment, and then apply the filter to the out-of-sample data that I defined as xout. The plot in Figure 5 shows the out-of-sample trading signal. Notice that the signal is not nearly as smooth as it was in-sample. Overshooting of the data in some areas is also obviously present. Although the out-of-sample overfitting characteristics of the signal are not horribly suspicious, I would not trust this filter to produce stellar returns in the long run. Figure 5. Filter applied to 200 15 minute observations of Yen out-of-sample to produce trading signal (shown in blue) Following the previous analysis of the mean-squared solution (no customization or regularization), we now proceed to clean up the problem of overfitting that was apparent in the coefficients along with mollifying the noise in the stopband (frequencies after ). In order to choose the parameters for smoothing and regularization, one approach is to first apply the smoothness parameter first, as this will generally smooth the coefficients while acting as a 8216pre8217-regularizer, and then advance to selecting appropriate regularization controls. In looking at the coefficients (Figure 3), we can see that a fair amount of smoothing is necessary, with only a slight touch of decay. To select these two parameters in R, one option is to use the Troikaner optimizer (found here ) to find a suitable combination (I have a secret sauce algorithmic approach I developed for iMetrica for choosing optimal combinations of parameters given an extractor and a performance indicator, although it8217s lengthy (even in GNU C) and cumbersome to use, so I typically prefer the strategy discussed in this tutorial). In this example, I began by setting the lambdasmooth to .5 and the decay to (.1,.1) along with an expweight smoothness parameter set to 8.5. After viewing the coefficients, it still wasn8217t enough smoothness, so I proceeded to add more finally reaching .63, which did the trick. I then chose lambda to balance the effects of the smoothing expweight (lambda is always the last resort tweaking parameter). Figure 6 shows the resulting frequency response function for both explanatory series (Yen in red). Notice that the largest spectral peak found directly before the frequency cutoff at is being emphasized and slightly mollified (value near .8 instead of 1.0). The other spectral peaks below are also present. For the coefficients, just enough smoothing and decay was applied to keep the lag, cyclical, and correlated structure of the coefficients intact, but now they look much nicer in their smoothed form. The number of freezed degrees of freedom has been reduced to approximately 102. Figure 6: The frequency response functions and the coefficients after regularization and smoothing have been applied (top). The smoothed coefficients with slight decay at the end (bottom). Number of freezed degrees of freedom is approximately 102 (out of 172). Along with an improved freezed degrees of freedom and no apparent havoc of overfitting, we apply this filter out-of-sample to the 200 out-of-sample observations in order to verify the improvement in the structure of the filter coefficients (shown below in Figure 7). Notice the tremendous improvement in the properties of the trading signal (compared with Figure 5). The overshooting of the data has be eliminated and the overall smoothness of the signal has significantly improved. This is due to the fact that we8217ve eradicated the presence of overfitting. Figure 7: Out-of-sample trading signal with regularization. With all indications of a filter endowed with exactly the characteristics we need for robustness, we now apply the trading signal both in-sample and out of sample to activate the buy/sell trades and see the performance of the trading account in cash value. When the signal crosses below zero, we sell (enter short position) and when the signal rises above zero, we buy (enter long position). The top plot of Figure 8 is the log price of the Yen for the 15 minute intervals and the dotted lines represent exactly where the trading signal generated trades (crossing zero). The black dotted lines represent a buy (long position) and the blue lines indicate a sell (and short position). Notice that the signal predicted all the close-to-open jumps for the Yen (in part thanks to the explanatory series). This is exactly what we will be striving for when we add regularization and customization to the filter. The cash account of the trades over the in-sample period is shown below, where transaction costs were set at .05 percent. In-sample, the signal earned roughly 6 percent in 9 trading days and a 76 percent trading success ratio. Figure 8: In-sample performance of the new filter and the trades that are generated. Now for the ultimate test to see how well the filter performs in producing a winning trading signal, we applied the filter to the 200 15-minute out-of-sample observation of the Yen and the explanatory series from Jan 18th to February 1st and make trades based on the zero crossing. The results are shown below in Figure 9. The black lines represent the buys and blue lines the sells (shorts). Notice the filter is still able to predict the close-to-open jumps even out-of-sample thanks to the regularization. The filter succumbs to only three tiny losses at less than .08 percent each between observations 160 and 180 and one small loss at the beginning, with an out-of-sample trade success ratio hitting 82 percent and an ROI of just over 4 percent over the 9 day interval. Figure 9: Out-of-sample performance of the regularized filter on 200 out-of-sample 15 minute returns of the Yen. The filter achieved 4 percent ROI over the 200 observations and an 82 percent trade success ratio. Compare this with the results achieved in iMetrica using the same MDFA parameter settings. In Figure 10, both the in-sample and out-of-sample performance are shown. The performance is nearly identical. Figure 10: In-sample and out-of-sample performance of the Yen filter in iMetrica. Nearly identical with performance obtained in R. Example 2 Now we take a stab at producing another trading filter for the Yen, only this time we wish to identify only the lowest frequencies to generate a trading signal that trades less often, only seeking the largest cycles. As with the performance of the previous filter, we still wish to target the frequencies that might be responsible to the large close-to-open variations in the price of Yen. To do this, we select our cutoff to be which will effectively keep the largest three spectral peaks intact in the low-pass band of . For this new filter, we keep things simple by continuing to use the same regularization parameters chosen in the previous filter as they seemed to produce good results out-of-sample. The and expweight customization parameters however need to be adjusted to account for the new noise suppression requirements in the stopband and the phase properties in the smaller passband. Thus I increase the smoothing parameter and decreased the timeliness parameter (which only affects the passband) to account for this change. The new frequency response functions and filter coefficients for this smaller lowpass design are shown below in Figure 11. Notice that the second spectral peak is accounted for and only slightly mollified under the new changes. The coefficients still have the noticeable smoothness and decay at the largest lags. Figure 11: Frequency response functions of the two filters and their corresponding coefficients. To test the effectiveness of this new lower trading frequency design, we apply the filter coefficients to the 200 out-of-sample observations of the 15-minute Yen log-returns. The performance is shown below in Figure 12. In this filter, we clearly see that the filter still succeeds in predicting correctly the large close-to-open jumps in the price of the Yen. Only three total losses are observed during the 9 day period. The overall performance is not as appealing as the previous filter design as less amount of trades are made, with a near 2 percent ROI and 76 percent trade success ratio. However, this design could fit the priorities for a trader much more sensitive to transaction costs. Figure 12: Out-of-sample performance of filter with lower cutoff. Conclusion Verification and cross-validation is important, just as the most interesting man in the world will tell you. The point of this tutorial was to show some of the main concepts and strategies that I undergo when approaching the problem of building a robust and highly efficient trading signal for any given asset at any frequency. I also wanted to see if I could achieve similar results with the R MDFA package as my iMetrica software package. The results ended up being nearly parallel except for some minor differences. The main points I was attempting to highlight were in first analyzing the periodogram to seek out the important spectral peaks (such as ones associate with close-to-open variations) and to demonstrate how the choice of the cutoff affects the systematic trading. Here8217s a quick recap on good strategies and hacks to keep in mind. Summary of strategies for building trading signal using MDFA in R: As I mentioned before, the periodogram is your best friend. Apply the cutoff directly after any range of spectral peaks that you want to consider. These peaks are what generate the trades. Utilize a choice of filter length no greater than 1/4. Anything larger is unnecessary. Begin by computing the filter in the mean-square sense, namely without using any customization or regularization and see exactly what needs to be approved upon by viewing the frequency response functions and coefficients for each explanatory series. Good performance of the trading signal in-sample (and even out-of-sample in most cases) is meaningless unless the coefficients have solid robust characteristics in both the frequency domain and the lag domain. I recommend beginning with tweaking the smoothness customization parameter expweight and the lambdasmooth regularization parameters first. Then proceed with only slight adjustments to the lambdadecay parameters. Finally, as a last resort, the lambda customization. I really never bother to look at lambdacross. It has seldom helped in any significant manner. Since the data we are using to target and build trading signals are log-returns, no need to ever bother with i1 and i2. Those are for the truly advanced and patient signal extractors, and should only be left for those endowed with iMetrica If you have any questions, or would like the high-frequency Yen data I used in these examples, feel free to contact me and I8217ll send them to you. Until next time, happy extracting Animation 1: Click to see animation of the Japanese Yen filter in action on 164 hourly out-of-sample observations. I recently acquired over 300 GBs of financial data that includes tick data for over 7000 financial assets traded on multiple markets for the past 5 years up until February 1st 2013. This USB drive packed with nearly every detail of world financial markets coupled with iMetrica gave me an opportunity to explore at any fashion to my desire the ability of multivariate direct filtering to produce high performance financial trading signals on nearly any high-frequency. Let me begin this article with saying that I am more than ecstatic with the results, as I hope you will too after reading this article. In this first article in a series of high-frequency trading with MDFA and iMetrica that I plan to write, I provide some initial experiments with building and extracting financial trading signals for high-frequency intraday observations on foreign exchange (FOREX) data, and by high-frequency in the context of this article, I mean higher frequencies than the daily log-returns I8217ve been working with in my previous articles. In the first part of this high-frequency series, I begin by exploring hourly, 30 minute, and 15 minute log-returns, and test different strategies, mostly using low-pass and the recently introduced multi-bandpass (MBP) filter to deduce the best approach to tackle the problem of building successful trading signals in higher frequency data. In my previous articles, I was working uniquely with daily log-return data from different time spans from a year to a year and a half. This enabled the in-sample period of computing the filter coefficients for the signal extraction to include all the most recent annual phases and seasons of markets, from holiday effects, to the transitioning period of August to September that is regularly highly influential on stock market prices and commodities as trading volume increases a significant amount. One immediate question that is raised in migrating to higher-frequency intraday data is what kind of in-sample/out-of-sample time spans should be used to compute the filter in-sample and then for how long do we apply the filter out-of-sample to produce the trades Another question that is raised with intraday data is how do we account for the close-to-open variation in price Certainly, after close, the after-hour bids and asks will force a jump into the next trading day. How do we deal with this jump in an optimal manner As the observation frequency gets higher, say from one hour to 30 minutes, this close-to-open jump/fall should most likely be larger. I will start by saying that, as you will see in the results of this article, with a clever choice of the extractor and explanatory series, MDFA can handle these jumps beautifully (both aesthetically and financially). In fact, I would go so far as to say that the MDFA does a superb job in predicting the overnight variation. One advantage of building trading signals for higher intraday frequencies is that the signals produce trading strategies that are immediately actionable. Namely one can act upon a signal to enter a long or short position immediately when they happen. In building trading signals for the daily log-return, this is not the case since the observations are not actionable points, namely the log difference of today8217s ending price with yesterday8217s ending price are produced after hours and thus not actionable during open market hours and only actionable the next trading day. Thus trading on intraday observations can lead to better efficiency in trading. In this first installment in my series on high-frequency financial trading using multivariate direct filtering in iMetrica, I consider building trading signals on hourly returns of foreign exchange currencies. I8217ve received a few requests after my recent articles on the Frequency Effect in seeing iMetrica and MDFA in action on the FOREX sector. So to satisfy those curiosities, I give a series of (financially) satisfying and exciting results in combining MDFA and the FOREX. I won8217t give all my secretes away into building these signals (as that would of course wipe out my competitive advantage), but I will give some of the parameters and strategies used so any courageously curious reader may try them at home (or the office). In the conclusion, I give a series of even more tricks and hacks. The results below speak for themselves So without further ado, let the games begin. Japanese Yen Frequency: One hour returns 30 day out-of-sample ROI: 12 percent Trade success ratio: 92 percent Yen Filter Parameters: 9.2 13.2, Regularization : smooth .918, decay .139, decay2 .79, cross 0 In the first experiment, I consider hourly log-returns of a ETF index that mimics the Japanese Yen called FXY. As for one of the explanatory series, I consider the hourly log-returns of the price of GOLD which is traded on NASDAQ. The out-of-sample results of the trading signal built using a low-pass filter and the parameters above are shown in Figure 1. The in-sample trading signal (left of cyan line) was built using 400 hourly observations of the Yen during US market hours dating back to 1 October 2012. The filter was then applied to the out-of-sample data for 180 hours, roughly 30 trading days up until Friday, 1 February 2013. Figure 1: Out-of-sample results for the Japanese Yen. The in-sample trading signal was built using 400 hourly observations of the Yen during US market hours dating back to October 1st, 2012. The out-of-sample portion passed the cyan line is on 180 hourly observations, about 30 trading days. This beauty of this filter is that it yields a trading signal exhibiting all the characteristics that one should strive for in building a robust and successful trading filter. Consistency: The in-sample portion of the filter performs exactly as it does out-of-sample (after cyan line) in both trade success ratio and systematic trading performance. Dropdowns: One small dropdown out-of-sample for a loss of only .8 percent (nearly the cost of the transaction). Detects the cycles as it should: Although the filter is not able to pinpoint with perfect accuracy every local small upturn during the descent of the Yen against the dollar, it does detect them nonetheless and knows when to sell at their peaks (the magenta lines). Self-correction: What I love about a robust filter is that it will tend to self-correct itself very quickly to minimize a loss in an erroneous trade. Notice how it did this in the second series of buy-sell transactions during the only loss out-of-sample. The filter detects momentum but quickly sold right before the ensuing downfall. My intuition is that only frequency-based methods such as the MDFA are able to achieve this consistently. This is the sign of a skillfully smart filter. The coefficients for this Yen filter are shown below. Notice the smoothness of the coefficients from applying the heavy smooth regularization and the strong decay at the very end. This is exactly the type of smooth/decay combo that one should desire. There is some obvious correlation between the first and second explanatory series in the first 30 lags or so as well. The third explanatory series seems to not provide much support until the middle lags . Figure 2: Coefficients of the Yen filter. Here we use three different explanatory series to extract the trading signal. One of the first things that I always recommend doing when first attempting to build a trading signal is to take a glance at the periodogram. Figure 2 shows the periodogram of the log-return data of the Japanese Yen over 580 hours. Compare this with the periodogram of the same asset using log-returns of daily data over 580 days, shown in Figure 3. Notice the much larger prominent spectral peaks at the lower frequencies in the daily log-return data. These prominent spectral peaks renders multibandpass filters much more advantageous and to use as we can take advantage of them by placing a band-pass filter directly over them to extract that particular frequency (see my article on multibandpass filters). However, in the hourly data, we don8217t see any obvious spectral peaks to consider, thus I chose a low-pass filter and set the cutoff frequency at pi/5, a standard choice, and good place to begin. Figure 3: Periodogram of hourly log-returns of the Japanese Yen over 580 hours. Figure 4: Periodogram of Japanese Yen using 580 daily log-return observations. Many more spectral peaks are present in the lower frequencies. Japanese Yen Frequency: 15 minute returns 7 day out-of-sample ROI: 5 percent Trade success ratio: 82 percent Yen Filter Parameters: 3.7 13, Regularization : smooth .90, decay .11, decay2 .09, cross 0 In the next trading experiment, I consider the Japanese Yen again, only this time I look at trading on even high-frequency log-return data than before, namely on 15 minute log-returns of the Yen from the opening bell to market close. This presents slightly new challenges than before as the close-to-open jumps are much larger than before, but these larger jumps do not necessarily pose problems for the MDFA. In fact, I look to exploit these and take advantage to gain profit by predicting the direction of the jump. For this higher frequency experiment, I considered 350 15-minute in-sample observations to build and optimize the trading signal, and then applied it over the span of 200 15-minute out-of-sample observations. This produced the results shown in the Figure 5 below. Out of 17 total trades out-of-sample, there were only 3 small losses each less than .5 percent drops and thus 14 gains during the 200 15-minute out-of-sample time period. The beauty of this filter is its impeccable ability to predict the close-to-open jump in the price of the Yen. Over the nearly 7 day trading span, it was able to correctly deduce whether to buy or short-sell before market close on every single trading day change. In the figure below, the four largest close-to-open variation in Yen price is marked with a 8220D8221 and you can clearly see how well the signal was able to correctly deduce a short-sell before market close. This is also consistent with the in-sample performance as well, where you can notice the buys and/or short-sells at the largest close-to-open jumps (notice the large gain in the in-sample period right before the out-of-sample period begins, when the Yen jumped over 1 percent over night. This performance is most likely aided by the explanatory time series I used for helping predict the close-to-open variation in the price of the Yen. In this example, I only used two explanatory series (the price of Yen, and another closely related to the Yen). Figure 5: Out-of-sample performance of the Japanese Yen filter on 15 minute log-return data. We look at the filter transfer functions to see what frequencies they are being privileged in the construction of the filter. Notice that some noise leaks out passed the frequency cutoff at , but this is typically normal and a non-issue. I had to balance for both timeliness and smoothness in this filter using both the customization parameters and . Not much at frequency 0 is emphasized, with more emphasis stemming from the large spectral peak found right at . Figure 6: The filter transfer functions. British Pound Frequency: 30 minute returns 14 day out-of-sample ROI: 4 percent Trade success ratio: 76 percent British Pound Filter Parameters: 5 15, Regularization : smooth .109, decay .165, decay2 .19, cross 0 In this example we consider the frequency of the data to 30 minute returns and attempt to build a robust trading signal for a derivative of the British Pound (BP) on this higher frequency. Instead of using the cash value of the BP, I use 30 minute returns of the BP Futures contract expiring in March (BPH3). Although I don8217t have access to tick data from the FOREX, I do have tick data from GLOBEX for the past 5 years. Thus the futures series won8217t be an exact replication of the cash price series of the BP, but it should be quite close due to very low interest rates. The results of the out-of-sample performance of the BP futures filter are shown in Figure 7. I constructed the filter using an initial in-sample size of 390 30 minute returns dating back to 1 December 2012. After pinpointing a frequency cutoff in the frequency domain for the that yielded decent trading results in-sample, I then proceeded to optimize the filter in-sample on smoothness and regularization to achieve similar out-of-sample performance. Applying the resulting filter out-of-sample on 168 30-minute log-return observations of the BP futures series along with 3 explanatory series, I get the results shown below. There were 13 trades made and 10 of them were successful. Notice that the filter does an exquisite job at triggering trades near local optimums associated with the frequencies inside the cutoff of the filter. Figure 7: The out-of-sample results of the British Pound using 30-minute return data. In looking at the coefficients of the filter for each series in the extraction, we can clearly see the effects of the regularization: the smoothness of the coefficients the fast decay at the very end. Notice that I never really apply any cross regularization to stress the latitudinal likeliness between the 3 explanatory series as I feel this would detract from the predicting advantages brought by the explanatory series that I used. Figure 8: The coefficients for the 3 explanatory series of the BP futures, Euro Frequency: 30 min returns 30 day out-of-sample ROI: 4 percent Trade success ratio: 71 percent Euro Filter Parameters: 0, 6.4, Regularization : smooth .85, decay .27, decay2 .12, cross .001 Continuing with the 30 minute frequency of log-returns, in this example I build a trading signal for the Euro futures contract with expiration on 18 March 2013 (UROH3 on the GLOBEX). My in-sample period, being the same as my previous experiment, is from 1 December 2012 to 4 January 2013 on 30 minute returns using three explanatory time series. In this example, after inspecting the periodogram, I decided upon a low-pass filter with a frequency cutoff of . After optimizing the customization and applying the filter to one month of 30 minute frequency return data out-of-sample (month of January 2013, after cyan line) we see the performance is akin to the performance in-sample, exactly what one strives for. This is due primarily to the heavy regularization of the filter coefficients involved. Only four very small losses of less than .02 percent are suffered during the out-of-sample span that includes 10 successful trades, with the losses only due to the transaction costs. Without transaction costs, there is only one loss suffered at the very beginning of the out-of-sample period. Figure 9. Out-of-sample performance on the 30-min log-returns of Euro futures contract UROH3. As in the first example using hourly returns, this filter again exhibits the desired characteristics of a robust and high-performing financial trading filter. Notice the out-of-sample performance behaves akin to the in-sample performance, where large upswings and downswings are pinpointed to high-accuracy. In fact, this is where the filter performs best during these periods. No need for taking advantage of a multibandpass filter here, all the profitable trading frequencies are found at less than . Just as with the previous two experiments with the Yen and the British Pound, notice that the filter cleanly predicts the close-to-open variation (jump or drop) in the futures value and buys or sells as needed. This can be seen from many of the large jumps in the out-of-sample period (after cyan line). One reason why these trading signals perform so well is due to their approximation power of the symmetric filter. In comparing the trading signal (green) with a high-order approximation of the symmetric filter (gray line) transfer function shown in Figure 10, we see that trading signal does an outstanding job at approximating the symmetric filter uniformly. Even at the latest observation (the right most point), the asymmetric filter hones in on the symmetric signal (gray line) with near perfection. Most importantly, the signal crosses zero almost exactly where required. This is exactly what you want when building a high-performing trading signal. Figure 10: Plot of approximation of the real-time trading signal for UROH3 with a high order approximation of the symmetric filter transfer function. In looking at the periodogram of the log-return data and the output trading signal differences (colored in blue), we see that the majority of the frequencies were accounted for as expected in comparing the signal with the symmetric signal. Only an inconsequential amount of noise leakage passed the frequency cutoff of is found. Notice the larger trading frequencies, the more prominent spectral peaks, are located just after . These could be taken into account with a smart multibandpass filter in order to manifest even more trades, but I wanted to keep things simple for my first trials with high-frequency foreign exchange data. I8217m quite content with the results that I8217ve achieved so far. Figure 11: Comparing the periodogram of the signal with the log-return data. Conclusion I must admit, at first I was a bit skeptical of the effectiveness that the MDFA would have in building any sort of successful trading signal for FOREX/GLOBEX high frequency data. I always considered the FOREX market rather 8216efficient8217 due to the fact that it receives one of the highest trading volumes in the world. Most strategies that supposedly work well on high-frequency FOREX all seem to use some form of technical analysis or charting (techniques I8217m particularly not very fond of), most of which are purely time-domain based. The direct filter approach is a completely different beast, utilizing a transformation into the frequency domain and a 8216bending and warping8217 of the metric space for the filter coefficients to extract a signal within the noise that is the log-return data of financial assets. For the MDFA to be very effective at building timely trading signals, the log-returns of the asset need to diverge from white noise a bit, giving room for pinpointing intrinsically important cycles in the data. However, after weeks of experimenting, I have discovered that building financial trading signals using MDFA and iMetrica on FOREX data is as rewarding as any other. As my confidence has now been bolstered and amplified even more after my experience with building financial trading signals with MDFA and iMetrica for high-frequency data on foreign exchange log-returns at nearly any frequency, I8217d be willing to engage in a friendly competition with anyone out there who is certain that they can build better trading strategies using time domain based methods such as technical analysis or any other statistical arbitrage technique. I strongly believe these frequency based methods are the way to go, and the new wave in financial trading. But it takes experience and a good eye for the frequency domain and periodograms to get used to. I haven8217t seen many trading benchmarks that utilize other types of strategies, but i8217m willing to bet that they are not as consistent as these results using this large of an out-of-sample to in-sample ratio (the ratios in these experiments were between .50 and .80). If anyone would like to take me up on my offer for a friendly competition (or know anyone that would), feel free to contact me. After working with a multitude of different financial time series and building many different types of filters, I have come to the point where I can almost eyeball many of the filter parameter choices including the most important ones being the extractor along with the regularization parameters, without resorting to time consuming, and many times inconsistent, optimization routines. Thanks to iMetrica, transitioning from visualizing the periodogram to the transfer functions and to the filter coefficients and back to the time domain to compare with the approximate symmetric filter in order to gauge parameter choices is an easy task, and an imperative one if one wants to build successful trading signals using MDFA. Here are some overall tips and tricks to build your own high performance trading signals on high-frequency data at home: Pay close attention to the periodogram. This is your best friend in choosing the extractor . The best performing signals are not the ones that trade often, but trade on the most important frequencies found in the data. Not all frequencies are created equal. This is true when building either low-pass or multibandpass frequencies. When tweaking customization, always begin with , the parameter for smoothness. for timeliness should be the last resort. In fact, this parameter will most likely be next to useless due to the fact that the log-return of financial data is stationary. You probably won8217t ever need it. You don8217t need many explanatory series. Like most things in life, quality is superior to quantity. Using the log-return data of the asset you8217re trading along with one and maybe two explanatory series that somewhat correlate with the financial asset you8217re trading on is sufficient. Anymore than that is ridiculous overkill, probably leading to over-fitting (even the power of regularization at your fingertips won8217t help you). In my next article, I will continue with even more high-frequency trading strategies with the MDFA and iMetrica where I will engage in the sector of Funds and ETFs. If any curious reader would like even more advice/hints/comments on how to build these trading signals on high-frequency data for the FOREX (or the coefficients built in these examples), feel free to get in contact with me via email. I8217ll be happy to help. Categories Email

No comments:

Post a Comment