Sunday 15 October 2017

Trading Strategies With R


FINC 621 Matemáticas Financieras y Modelado II (FINC 621) es una clase de nivel de posgrado que actualmente se ofrece en la Universidad Loyola en Chicago durante el trimestre de invierno. FINC 621 explora temas de finanzas cuantitativas, matemáticas y programación. La clase es de naturaleza práctica y está compuesta por una conferencia y un componente de laboratorio. Los laboratorios utilizan el lenguaje de programación R y los estudiantes deben presentar sus asignaciones individuales al final de cada clase. El objetivo final de FINC 621 es proveer a los estudiantes con herramientas prácticas que pueden usar para crear, modelar y analizar estrategias comerciales simples. Algunos enlaces R útiles Acerca del Instructor Harry G. es un comerciante cuantitativo senior para una empresa comercial de HFT en Chicago. Él tiene un master8217s grado en Ingeniería Eléctrica y un master8217s grado en Matemáticas Financieras de la Universidad de Chicago. En su tiempo libre, Harry enseña un curso de posgrado en Finanzas Cuantitativas en la Universidad Loyola de Chicago. También es autor de Quantitative Trading con R. Trading Strategies Copyright copy 2016 MarketWatch, Inc. Todos los derechos reservados. Al usar este sitio, usted acepta los Términos de Servicio. Política de privacidad y política de cookies. Intraday Datos proporcionados por SIX Financial Information y sujeta a condiciones de uso. Datos históricos y actuales al final del día proporcionados por SIX Financial Information. Datos intradía retrasados ​​por necesidades de intercambio. SP / Dow Jones Indices (SM) de Dow Jones Company, Inc. Todas las cotizaciones son en tiempo de cambio local. Datos de última venta en tiempo real proporcionados por NASDAQ. Más información sobre los símbolos negociados de NASDAQ y su estado financiero actual. Los datos intradía retrasaron 15 minutos para el Nasdaq, y 20 minutos para otros intercambios. SP / Dow Jones Indices (SM) de Dow Jones Company, Inc. Los datos intradiarios de SEHK son proporcionados por SIX Financial Information y tienen al menos 60 minutos de retraso. Todas las cotizaciones son en tiempo de intercambio local. MarketWatch Principales historias Cuando se examinan estrategias de negociación, un enfoque común consiste en dividir el conjunto inicial de datos en datos de muestra: la parte de los datos diseñados para calibrar el modelo y fuera de los datos de muestra: la parte de los datos utilizados para validar la calibración y asegurar que El rendimiento creado en la muestra se reflejará en el mundo real. Como regla general, alrededor de 70 de los datos iniciales se pueden utilizar para la calibración (es decir, en la muestra) y 30 para la validación (es decir, fuera de la muestra). A continuación, una comparación de los datos de entrada y salida de la muestra ayuda a decidir si el modelo es lo suficientemente robusto. Este post tiene como objetivo dar un paso más y proporciona un método estadístico para decidir si los datos de la muestra están en línea con lo que se creó en la muestra. En el gráfico de abajo, el área azul representa el rendimiento de la muestra de una de mis estrategias. Una inspección visual simple revela un buen ajuste entre el dentro y fuera del rendimiento de la muestra, pero ¿qué grado de confianza que tengo en esto En esta etapa no mucho y este es el problema. Lo que realmente se necesita es una medida de similitud entre los conjuntos de datos de entrada y salida de la muestra. En términos estadísticos, esto podría traducirse como la probabilidad de que las cifras de rendimiento dentro y fuera de la muestra provengan de la misma distribución. Existe una prueba estadística no paramétrica que hace exactamente esto: la Prueba de Kruskall-Wallis. Una buena definición de esta prueba se puede encontrar en R-Tutor 8220A colección de muestras de datos son independientes si provienen de poblaciones no relacionadas y las muestras no se afectan mutuamente. Uso de la prueba de Kruskal-Wallis. Podemos decidir si las distribuciones de la población son idénticas sin suponer que sigan la distribución normal.8221 El beneficio adicional de esta prueba no está suponiendo una distribución normal. Existen otras pruebas de la misma naturaleza que podrían encajar en ese marco. La prueba de Mann-Whitney-Wilcoxon o las pruebas de Kolmogorov-Smirnov se adaptarían perfectamente al marco describe aquí sin embargo esto está más allá del alcance de este artículo para discutir los pros y los contras de cada una de estas pruebas. Una buena descripción junto con ejemplos R se puede encontrar aquí. Aquí el código utilizado para generar el gráfico anterior y el análisis: En el ejemplo anterior, el período de muestra es más largo que el período fuera de la muestra, por lo tanto, creé aleatoriamente 1000 subconjuntos de los datos de la muestra cada uno de ellos con la misma longitud que la salida De los datos de la muestra. Entonces probé cada uno en el subconjunto de la muestra contra el fuera de los datos de la muestra y registré los valores de p. Este proceso no crea un solo valor p para la prueba de Kruskall-Wallis sino una distribución que hace que el análisis sea más robusto. En este ejemplo, la media de los valores de p está muy por encima de cero (0.478), lo que indica que la hipótesis nula debe ser aceptada: existen fuertes evidencias de que los datos de entrada y salida provienen de la misma distribución. Como de costumbre, lo que se presenta en este post es un ejemplo de juguete que sólo rasca la superficie del problema y debe adaptarse a las necesidades individuales. Sin embargo, creo que propone un marco estadístico interesante y racional para evaluar los resultados de la muestra. Esta publicación está inspirada en los dos siguientes trabajos: Vigier Alexandre, Chmil Swann (2007), Efectos de diversas funciones de optimización en el rendimiento fuera de muestra de las estrategias de negociación genéticamente evolucionadas, Previsión de mercados financieros Conferencia Vigier Alexandre, Chmil Swann (2010), An Proceso de optimización para mejorar la coherencia de la muestra, un caso de Bolsa, JP Morgan Cazenove Equity Cuantitativa de la Conferencia, Londres Octubre 2010 fidlr es un complemento de RStudio diseñado para simplificar el proceso de descarga de datos financieros de varios proveedores. Esta versión inicial es un envoltorio alrededor de la función getSymbols en el paquete quantmod y solo se admiten Yahoo, Google, FRED y Oanda. Probablemente añadir funcionalidades en el tiempo. Como de costumbre con esas cosas sólo un amable recordatorio: 8220 EL SOFTWARE SE PROPORCIONA 8220AS IS8221, SIN GARANTÍA DE CUALQUIERA KIND82308221 Cómo instalar y utilizar fidlr Puede obtener el addin / package desde su repositorio Github aquí (lo registraré en CRAN más adelante) Instale el complemento. Hay un excelente tutorial para instalar RStudio Addins aquí. Una vez que el complemento se instala debe aparecer en el menú Addin. Sólo elija fidlr en el menú y una ventana como se muestra a continuación debe aparecer. Elija un proveedor de datos en el menú desplegable Fuente. Seleccione un intervalo de fechas en el menú Fecha Introduzca el símbolo que desea descargar en el cuadro de texto del instrumento. Para descargar varios símbolos simplemente ingrese los símbolos separados por comas. Utilice los botones de radio para elegir si desea descargar el instrumento en un archivo csv o en el entorno global. El archivo csv se guardará en el directorio de trabajo y habrá un archivo csv por cada instrumento. Pulse Ejecutar para obtener los datos o Cerrar para cerrar el complemento Los mensajes de error y las advertencias son manejados por los paquetes subyacentes (quantmod y Shiny) y se pueden leer desde la consola Esta es una primera versión del proyecto, así que no espere la perfección pero Esperemos que va a mejorar con el tiempo. Por favor, informe cualquier comentario, sugerencia, error etc8230 a: thertradergmail Hacer la investigación cuantitativa implica una gran cantidad de datos crujidos y uno necesita datos limpios y confiables para lograr esto. Lo que realmente se necesita son los datos limpios que son fácilmente accesibles (incluso sin conexión a Internet). La forma más eficiente de hacer esto para mí ha sido mantener un conjunto de archivos csv. Obviamente este proceso se puede manejar de muchas maneras, pero he encontrado tiempo extra muy eficiente y simple para mantener un directorio donde almacenar y actualizar los archivos csv. Tengo un archivo de csv por el instrumento y cada archivo se nombra después del instrumento que contiene. La razón por la que lo hago es doble: En primer lugar, no quiero descargar (precio) los datos de Yahoo, Google etc8230 cada vez que quiero probar una nueva idea, pero lo más importante una vez que identifiqué y arregló un problema, don8217t quiero tener que Hacerlo de nuevo la próxima vez que necesite el mismo instrumento. Sencillo pero muy eficiente hasta ahora. El proceso se resume en el siguiente cuadro. En todo lo que sigue, supongo que los datos provienen de Yahoo. El código tendrá que ser modificado para los datos de Google, Quandl etc8230 Además, presento el proceso de actualización de los datos de precios diarios. La configuración será diferente para los datos de mayor frecuencia y otro tipo de conjunto de datos (es decir, diferente de los precios). 1 8211 Descarga inicial de datos (listOfInstruments. R amp historicalData. R) El archivo listOfInstruments. R es un archivo que contiene sólo la lista de todos los instrumentos. Si un instrumento no forma parte de mi lista (es decir, ningún archivo csv en mi carpeta de datos) o si lo hace por primera vez tiene que descargar el conjunto de datos históricos iniciales. El ejemplo a continuación descarga un conjunto de precios diarios de ETFs de Yahoo Finance a enero de 2000 y almacena los datos en un archivo csv. 2 8211 Actualizar los datos existentes (updateData. R) El código a continuación se inicia a partir de los archivos existentes en la carpeta dedicada y los actualiza uno tras otro. Por lo general, ejecuto este proceso todos los días, excepto cuando I8217m de vacaciones. Para agregar un nuevo instrumento, simplemente ejecute el paso 1 anterior para este instrumento solo. 3 8211 Crear un archivo por lotes (updateDailyPrices. bat) Otra parte importante del trabajo es la creación de un archivo por lotes que automatiza el proceso de actualización anterior (I8217m un usuario de Windows). Esto evita abrir R / RStudio y ejecutar el código desde allí. El código siguiente se coloca en un archivo. bat (la ruta tiene que ser modificada con la configuración de reader8217s). Tenga en cuenta que he añadido un archivo de salida (updateLog. txt) para rastrear la ejecución. El proceso anterior es extremadamente simple porque sólo describe cómo actualizar los datos de precios diarios. He estado usando esto por un tiempo y ha estado trabajando muy bien para mí hasta ahora. Para obtener datos más avanzados y / o frecuencias más altas, las cosas pueden ser mucho más complicadas. Como de costumbre, cualquier comentario bienvenido La industria de Gestión de Activos está al borde de un cambio importante. Durante los dos últimos años Robots Advisors (RA) han surgido como nuevos jugadores. El término en sí es difícil de definir, ya que abarca una gran variedad de servicios. Algunos están diseñados para ayudar a los asesores tradicionales para asignar mejor el dinero de sus clientes y algunos son reales 8220black box8221. El usuario introduce algunos criterios (edad, ingresos, hijos, etc.8230) y el robot propone una asignación a medida. Entre estos dos extremos está disponible una gama completa de ofertas. Encontré la definición de Wikipedia bastante buena. 8220Son una clase de asesor financiero que proporciona la gestión de cartera en línea con una intervención humana mínima8221. Más precisamente, utilizan la gestión de cartera basada en algoritmos para ofrecer el espectro completo de servicios que un consejero tradicional ofrecería: reinversión de dividendos, informes de cumplimiento, reequilibrio de cartera, recolección de pérdidas fiscales, etc 8230 (esto es lo que la comunidad de inversión cuantitativa está haciendo durante décadas). La industria todavía está en su infancia con la mayoría de los jugadores todavía la gestión de una pequeña cantidad de dinero, pero sólo me di cuenta de lo profundo fue el cambio cuando estaba en Nueva York hace unos días. Cuando RA recibe sus nombres en la TV agrega o en el techo de la cabina de NYC usted sabe que algo grande está sucediendo8230 está consiguiendo más y más atención de los medios y sobre todo hace mucho sentido de una perspectiva del inversionista. En realidad, hay dos ventajas principales en el uso de RA: Las tasas significativamente más bajos de los asesores tradicionales La inversión se hace más transparente y más simple, que es más atractivo para las personas con conocimientos financieros limitados En este post R es sólo una excusa para presentar bien lo que es una tendencia importante en La industria de gestión de activos. El gráfico siguiente muestra las cuotas de mercado de la AR más popular a finales de 2014. El código utilizado para generar el gráfico de abajo se puede encontrar al final de este post y los datos están aquí. Esas cifras son un poco anticuadas, dada la rapidez con que evoluciona esta industria, pero siguen siendo muy informativas. No es sorprendente que el mercado esté dominado por proveedores estadounidenses como Wealthfront y Betterment, pero la RA emerge en todo el mundo: Asia (8Now), Suiza (InvestGlass), Francia (Marie Quantier) 8230. Está empezando a afectar significativamente la forma en que los gestores de activos tradicionales están haciendo negocios. Un ejemplo destacado es la asociación entre Fidelity y Betterment. Desde diciembre de 2014 Mejoramiento pasado la marca de 2 millones de AUM. A pesar de todo lo anterior, creo que el verdadero cambio está por delante de nosotros. Debido a que utilizan menos intermediarios y productos de comisiones bajas (como los ETF) cobran honorarios mucho más bajos que los asesores tradicionales. RA sin duda obtendrá cuotas de mercado significativas, pero también reducirá los cargos cobrados por la industria en su conjunto. En última instancia, afectará la forma en que las empresas de inversión tradicionales hacen negocios. La gestión activa de la cartera que está teniendo un momento difícil durante algunos años ahora sufrirá aún más. Las altas tarifas que cobra será aún más difícil de justificar a menos que se reinvente. Otro impacto potencial es el aumento de los ETFs y los productos financieros de comisiones bajas en general. Obviamente esto ha comenzado hace un tiempo, pero creo que el efecto será aún más pronunciado en los próximos años. Las nuevas generaciones de ETFs siguen índices más complejos y estrategias personalizadas. Esta tendencia se fortalecerá inevitablemente. Como de costumbre, cualquier comentario bienvenido Hay muchos tutoriales de series de tiempo R flotando en la web este post no está diseñado para ser uno de ellos. En cambio, quiero presentar una lista de los trucos más útiles que encontré cuando se trata de series de tiempo financiero en R. Algunas de las funciones presentadas aquí son increíblemente poderoso, pero por desgracia enterrado en la documentación de ahí mi deseo de crear un post dedicado. Sólo me dirijo a series diarias o de menor frecuencia. El tratamiento de datos de frecuencia más alta requiere herramientas específicas: los paquetes data. table o highfrequency son algunos de ellos. Xts. El paquete xts es el debe tener cuando se trata de serie de tiempos en R. El ejemplo siguiente carga el paquete y crea una serie de tiempo diario de 400 días normalizados distribuidos merge. xts (xts): Esto es increíblemente potente cuando se trata de Uniendo dos o más series de series si tienen la misma longitud o no. El argumento de unión hace la magia que determina cómo se realiza la vinculación apply. yearly / apply. monthly (package xts): Aplique una función especificada a cada período definido en un objeto de serie de tiempo dado. El ejemplo siguiente calcula los retornos mensuales y anuales de la segunda serie en el objeto tsInter. Tenga en cuenta que utilizo la suma de retornos (sin composición) puntos finales (paquete xts): Extrae valores de índice de un objeto xts dado correspondiente a las últimas observaciones dado un período especificado por on. El ejemplo proporciona el último día del mes para cada serie en el objeto tsInter que utiliza el punto final para seleccionar la fecha. Na. locf (package zoo): Función genérica para reemplazar cada NA con la más reciente no NA antes de ella. Extremadamente útil cuando se trata de una serie de tiempo con unos pocos 8220holes8221 y cuando esta serie de tiempo se utiliza posteriormente como entrada para una R funciones que no acepta los argumentos con NAs. En el ejemplo, creo una serie cronológica de precios al azar, entonces artificialmente incluye unos NA en ella y los reemplaza con el valor más reciente. Charts. PerformanceSummary (package PerformanceAnalytics): Para un conjunto de retornos, cree un gráfico de índice de riqueza, las barras para el rendimiento por período y el gráfico subacuático para la reducción. Esto es increíblemente útil, ya que muestra en una sola ventana toda la información relevante para una rápida inspección visual de una estrategia comercial. El ejemplo siguiente convierte la serie de precios en un objeto xts y luego muestra una ventana con las 3 cartas descritas anteriormente. La lista de arriba no es en absoluto exhaustiva, pero una vez que dominar las funciones describen en este post hace que la manipulación de series de tiempo financiero mucho más fácil, el código más corto y la legibilidad del código mejor. Como de costumbre cualquier comentario bienvenido Cuando se trata de gestionar una cartera de acciones frente a un benchmark el problema es muy diferente de definir una estrategia de retorno absoluto. En el primero se tiene que mantener más acciones que en el posterior, donde no se puede mantener ninguna acción si no hay una oportunidad lo suficientemente buena. La razón de ello es el error de seguimiento. Esto se define como la desviación estándar del rendimiento de la cartera menos el rendimiento de referencia. Cuanto menos acciones se mantenga frente a un punto de referencia, mayor será el error de seguimiento (por ejemplo, mayor riesgo). El análisis que sigue se inspira en gran medida en el libro 8220Active Portfolio Management8221 de Grinold amp Kahn. Ésta es la biblia para cualquier persona interesada en funcionar una lista contra un punto de referencia. Recomiendo encarecidamente a cualquiera que tenga interés en el tema que lea el libro desde el principio hasta el final. Está muy bien escrito y establece los fundamentos de la gestión sistemática de la cartera activa (no tengo ninguna afiliación al editor oa los autores). 1 8211 Análisis Factorial Aquí estamos tratando de clasificar con la mayor exactitud posible las existencias en el universo de inversión sobre una base de retorno hacia adelante. Muchas personas inventaron muchas herramientas y se han desarrollado innumerables variantes de esas herramientas para lograrlo. En este post me centraré en dos métricas simples y ampliamente utilizadas: Coeficiente de información (IC) y Quantiles Return (QR). 1.1 8211 Coeficiente de información El horizonte de la rentabilidad futura tiene que ser definido por el analista y es una función de la rotación de la estrategia y de la desintegración alfa (esto ha sido objeto de una extensa investigación). Obviamente, los CI deben ser lo más altos posible en términos absolutos. Para el lector entusiasta, en el libro de Grinold amp Kahn se da una fórmula que une la relación de información (IR) y la IC: con anchura el número de apuestas independientes (oficios). Esta fórmula se conoce como la ley fundamental de la gestión activa. El problema es que a menudo, definir amplitud con precisión no es tan fácil como suena. Para obtener una estimación más precisa de la potencia predictiva de los factores, es necesario ir un paso más allá y agrupar las existencias por cuantil de los valores de los factores, luego analizar la rentabilidad media (o cualquier otra métrica de tendencia central) de cada una de ellas Cuantiles. La utilidad de esta herramienta es sencilla. Un factor puede tener un buen CI, pero su poder predictivo podría limitarse a un pequeño número de acciones. Esto no es bueno, ya que un gestor de cartera tendrá que recoger acciones dentro del universo entero para cumplir con su limitación de error de seguimiento. Los buenos cuantiles de retorno se caracterizan por una relación monótona entre los cuantiles individuales y los retornos forward. Todas las acciones en el índice SampP500 (en el momento de la escritura). Obviamente hay un sesgo de supervivencia de buques: la lista de acciones en el índice ha cambiado significativamente entre el inicio y el final del período de muestreo, sin embargo es bastante buena sólo con fines ilustrativos. El código de abajo descarga los precios de las acciones individuales en el SampP500 entre enero de 2005 y hoy (toma un tiempo) y convierte los precios en bruto en los últimos 12 meses y el último mes. El primero es nuestro factor, este último será utilizado como la medida de retorno hacia adelante. A continuación se muestra el código para calcular el Coeficiente de Información y el Retorno de Quantiles. Tenga en cuenta que he utilizado quintiles en este ejemplo, pero cualquier otro método de agrupación (terciles, deciles etc8230) puede ser utilizado. Realmente depende del tamaño de la muestra, lo que desea capturar y si desea tener una amplia visión general o centrarse en las colas de distribución. Para estimar los rendimientos dentro de cada quintil, la mediana se ha utilizado como estimador de tendencia central. Esta medida es mucho menos sensible a los valores atípicos que la media aritmética. Y finalmente el código para producir el Cuadro de Retorno de Quantiles. 3 8211 Cómo explotar la información anterior En el gráfico anterior, Q1 es el más bajo en los últimos 12 meses y el Q5 más alto. Hay un aumento casi monotónico en el retorno de los cuantiles entre Q1 y Q5, lo que indica claramente que las existencias que caen en Q5 superan a las que caen en Q1 en aproximadamente 1 por mes. Esto es muy significativo y poderoso para un factor tan simple (no es realmente una sorpresa, aunque 8230). Por lo tanto, hay mayores posibilidades de superar el índice por sobreponderar las acciones caen en Q5 y ​​subponderar a los que caen en Q1 en relación con el punto de referencia. Un IC de 0,0206 podría no significar mucho en sí mismo, pero es significativamente diferente de 0 y indica un buen poder predictivo de los últimos 12 meses de retorno en general. Las pruebas de significación formal pueden ser evaluadas, pero esto está más allá del alcance de este artículo. 4 8211 Limitaciones prácticas El marco anterior es excelente para evaluar la calidad de las inversiones factor8217s sin embargo, hay una serie de limitaciones prácticas que tienen que ser abordados para la implementación de la vida real: Reequilibrio. En la descripción anterior, se suponía que al final de cada mes la cartera estaba totalmente reequilibrada. Esto significa que todas las acciones que caen en el primer trimestre están infraponderadas y todas las acciones que caen en el Q5 están sobreponderadas con respecto al índice de referencia. Esto no siempre es posible por razones prácticas: algunas poblaciones podrían ser excluidas del universo de inversión, hay restricciones en el peso de la industria o del sector, existen restricciones en el volumen de ventas, etc. Esto no ha sido tomado en cuenta en el análisis anterior y esto es un freno serio para la implementación de la vida real. Consideraciones de volumen de negocios se aplican generalmente en la vida real en una forma de pena sobre la calidad del factor. Coeficiente de transferencia. Esta es una extensión de la ley fundamental de la gestión activa y se relaja la asunción del modelo Grinold 8217s que los directivos no enfrentan restricciones que les impiden traducir sus inversiones directamente en apuestas de cartera. Y, por último, me sorprende lo que se puede lograr en menos de 80 líneas de código con R8230 Como de costumbre los comentarios bienvenidos me encuentro con un montón de estrategias en la blogosfera algunos son interesantes algunos son una pérdida de tiempo, pero la mayoría comparten una característica común : Las personas que desarrollan esas estrategias hacen su tarea en términos de analizar el retorno, pero se presta mucha menos atención al lado del riesgo de su naturaleza aleatoria. I8217ve visto comentar como 8220a 25 bajada en 2011 pero excelente rendimiento overall8221. Bueno, mi apuesta es que nadie en la tierra le permitirá experimentar una pérdida de 25 con su dinero (a menos que los acuerdos especiales están en su lugar). En el mundo de fondos de cobertura la gente tiene tolerancia muy baja para la reducción. Generalmente, como un nuevo operador en un fondo de cobertura, asumiendo que usted no tiene reputación, tiene muy poco tiempo para probarse a sí mismo. Usted debe ganar dinero desde el primer día y seguir haciéndolo durante unos meses antes de ganar un poco de credibilidad. Primero, digamos que usted tiene un mal comienzo y que pierde dinero al principio. Con una reducción de 10 you8217re sin duda fuera, pero incluso con una reducción de 5 las posibilidades de ver su asignación reducida son muy altos. Esto tiene implicaciones significativas en sus estrategias. Let8217s asumen que si pierdes 5 tu asignación se divide por 2 y vuelves a tu asignación inicial sólo cuando pasas de nuevo la marca de agua alta (por ejemplo, la reducción vuelve a 0). En el cuadro de abajo, he simulado el experimento con una de mis estrategias. Usted comienza a operar en 1 de junio de 2003 y todo va bien hasta el 23 de julio de 2003, donde su curva de reducción alcanza el umbral -5 (1). Su asignación es cortada por 50 y usted don8217t cruzar el nivel de la marca de agua hasta el 05 de diciembre 2003 (3). Si usted ha mantenido la asignación sin cambios, el nivel de la marea alta se habría cruzado el 28 de octubre de 2003 (2) y para el final del año usted habría hecho más dinero. Sin embargo, el razonamiento va un poco más allá. Aún en la tabla de arriba, asuma que usted consigue realmente mala suerte y comienza a operar hacia mediados de junio de 2003. Usted golpeó el límite de la retirada 10 para el principio de agosto y you8217re más probable fuera del juego. Usted habría comenzado a principios de agosto su asignación no se han cortado en absoluto y que terminan haciendo un buen año en sólo 4 meses completos de comercio. En esos dos ejemplos nada ha cambiado, pero su fecha de inicio8230. El éxito comercial de cualquier individuo tiene alguna forma de dependencia camino y no hay mucho que puede hacer al respecto. Sin embargo, usted puede controlar el tamaño de un drawdown estrategia y esto debe ser tratado con mucho cuidado. Una cartera debe diversificarse en todas las dimensiones posibles: clases de activos, estrategias de inversión, frecuencias de negociación, etc.8230. Desde esa perspectiva, el riesgo es su variable de supervivencia 8222. Si se gestiona adecuadamente, tiene la oportunidad de permanecer en el juego el tiempo suficiente para darse cuenta del potencial de su estrategia. De lo contrario, no estarás allí el próximo mes para ver qué pasa. Como de costumbre todos los comentarios bienvenidos Mi última experiencia con Linux fue en 2002/2003. En ese momento prácticamente todo en Linux se hacía en la consola. Me recuerdo luchando por días con una conexión Wifi sencilla porque los conductores no estaban disponibles. Las cosas han cambiado dramáticamente desde entonces. La semana pasada instalé Linux (Ubuntu 14.04) en una laptop vieja de Windows. Me tomó unos 20 minutos para borrar completamente Windows, instalar Linux y empezar a jugar con R / Rstudio: simplemente amazing8230. En este post te explico paso a paso lo que hice: ten en cuenta que I8217m un principiante absoluto de Linux. Vaya al sitio web de Ubuntu y descargue la versión que coincida con su sistema Cree una llave USB de arranque con el archivo descargado anteriormente. Utilicé una pequeña utilidad llamada Rufus para esto. Simplemente siga las instrucciones en el sitio web it8217s muy simple. Ubuntu 14.04 viene con R pero it8217s no es la última versión. La última versión se puede obtener de CRAN. Una entrada como. Ltmy. favorite. cran. mirrorgt / bin / linux / ubuntu trusty / tiene que ser agregado al archivo /etc/apt/sources. list, reemplazando ltmy. favorite. cran. mirrorgt por la URL real de su espejo CRAN favorito (ver Cran. r-project. org/mirrors para la lista de espejos CRAN). En realidad, esto es un poco complicado porque necesita derechos de administrador para modificar el archivo sources. list. Utilicé una pequeña utilidad llamada gksudo para abrir y modificar el archivo sources. list. En la línea de comandos escriba lo siguiente: Se abrirá el archivo sources. list en gedit. Sólo tienes que añadir el repositorio de arriba a continuación, guardar y cerrar A continuación, puede instalar el sistema completo R, escribiendo lo siguiente en la consola: Hay otras maneras de hacerlo, pero la adición de una entrada al archivo sources. list es aparentemente la preferida opción. Ubuntu utiliza apt para la administración de paquetes. Apt almacena una lista de repositorios (canales de software) en el archivo sources. list. Mediante la edición de este archivo desde la línea de comandos, los repositorios de software pueden agregarse o eliminarse. 3 8211 Instalar RStudio Ir a RStudio sitio web, elegir y descargar el paquete adecuado para su sistema Abra este archivo en Ubuntu Software Center Haga clic en instalar y you8217re hecho si desea tener RStudio icono en el lanzador (todos los iconos en el lado izquierdo de La pantalla) Vaya a Buscar y escriba RStudio, el ícono de RStudio debe aparecer Arrastre y suelte el ícono de RStudio al lanzador Todo esto no pudo ser perfecto pero trabajó para mí sin una interferencia. Quería compartir mi experiencia porque I8217m realmente sorprendido por las mejoras traídas a Linux en los últimos años. Como de costumbre, cualquier comentario bienvenido. Este es un seguimiento de mi post anterior 8220A Simple Shiny App para la supervisión de estrategias de comercio 8220. He añadido algunas mejoras que hacen que la aplicación un poco mejor (al menos para mí). A continuación se muestra la lista de nuevas características: Un archivo. csv de ejemplo (el que contiene los datos sin procesar) Un cuadro desplegable 8220EndDate8221 que permite especificar el final del período. Una página 8220Risk8221 que contiene un análisis de VaR y un gráfico de peor rendimiento en varios horizontes Una página 8220How To8221 explicando cómo usar y adaptar la aplicación a las necesidades individuales También hice la aplicación totalmente autocontenida. Ahora está disponible como un producto independiente y no hay necesidad de tener R / RStudio instalado en su computadora para ejecutarlo. Puede descargarse de la cuenta de unidad de Google R Trader. Esta versión de la aplicación se ejecuta utilizando portátil R y Chrome portátil. Para el lector interesado, este enlace explica en detalles completos cómo empaquetar una aplicación brillante en una aplicación de escritorio (sólo Windows ahora). 1 8211 Cómo instalar el amplificador ejecute la aplicación en su computadora Cree una carpeta específica Descomprima el contenedor del archivo. zip en esa nueva carpeta. Cambie las rutas en el archivo runShinyApp para que coincida con sus configuraciones Para ejecutar la aplicación, sólo tiene que ejecutar el archivo run. vbs. También incluí un icono (RTraderTradingApp. ico) si desea crear un acceso directo en su escritorio. La aplicación utiliza como entrada varios archivos csv (uno para cada estrategia). Cada archivo tiene dos columnas: fecha y retorno diario. Hay un ejemplo de dicho archivo en el repositorio de Github. El código se compone esencialmente de 3 archivos. Ui. R: controla el diseño y la apariencia de la aplicación server. R: contiene las instrucciones necesarias para crear la aplicación. Puede cargar tantas estrategias como desee, siempre y cuando el archivo csv correspondiente tenga el formato correcto (consulte a continuación). ShinyStrategyGeneral. R: carga los paquetes requeridos y lanza la aplicación poner ui. R y server. R archivo en un directorio separado En el archivo server. R cambie los parámetros inputPath, inputFile y keepColumns para que coincidan con su configuración. Los dos primeros se explican por sí mismos, el tercero es una lista de nombres de columnas dentro del archivo csv. Mantenga sólo la fecha y el retorno diario. 3 8211 Cómo agregar una estrategia de negociación Crear el archivo. csv correspondiente en el directorio derecho Crear una nueva entrada en la función de datos reactivos (dentro del archivo server. R) Agregar un elemento extra al parámetro choice en el primer selectInput en el sidebarPanel (Dentro del archivo ui. R). El nombre de element8217s debe coincidir con el nombre de la nueva entrada anterior. 4 8211 Cómo quitar una estrategia comercial Quite la entrada en la función de datos reactivos correspondiente a la estrategia que desea eliminar (dentro del archivo server. R) Quite el elemento en el parámetro choice en el primer selectInput en el sidebarPanel correspondiente a la estrategia Que desea eliminar (dentro del archivo ui. R). Por favor, no dude en ponerse en contacto si tiene alguna sugerencia. En un post anterior mostré cómo usar R, Knitr y LaTeX para construir un informe de estrategia de plantilla. Este post va un paso más allá, haciendo el análisis interactivo. Además de la interactividad, la aplicación Shiny también resuelve dos problemas: ahora puedo acceder a todas mis estrategias de negociación desde un único punto independientemente del instrumento que se negocia. Junto con la interactividad Shiny, permite una comparación más fácil. Puedo enfocarme en un período de tiempo específico. El código utilizado en este post está disponible en un repositorio Gist / Github. Hay esencialmente 3 archivos. Ui. R. Controla el diseño y la apariencia de la aplicación. Server. R. Contiene las instrucciones necesarias para crear la aplicación. Carga los datos y los formatea. Hay un archivo csv por estrategia que contiene al menos dos columnas: date y return con el siguiente formato: (82202010-12-228243,82210.048221). Puedes cargar tantas estrategias como quieras, siempre y cuando tengan el formato correcto. ShinyStrategyG eneral. R. Carga los paquetes requeridos y lanza la aplicación. Esta aplicación es, probablemente, lejos de ser perfecto y sin duda lo mejorará en el futuro. Siéntase libre de ponerse en contacto si tiene alguna sugerencia. Un gran agradecimiento al equipo de RStudio / Shiny por una herramienta tan grande. Mensajes recientes Archivos Categorías Blogroll 65 consultas. 0.824 seconds. Archive para la categoría Trading Strategies Al probar las estrategias de negociación un enfoque común es dividir el conjunto de datos iniciales en datos de muestra: la parte de los datos diseñados para calibrar el modelo y fuera de los datos de muestra: la parte de los datos utilizados Para validar la calibración y asegurar que el rendimiento creado en la muestra se reflejará en el mundo real. Como regla general, alrededor de 70 de los datos iniciales se pueden utilizar para la calibración (es decir, en la muestra) y 30 para la validación (es decir, fuera de la muestra). A continuación, una comparación de los datos de entrada y salida de la muestra ayuda a decidir si el modelo es lo suficientemente robusto. Este post tiene como objetivo dar un paso más y proporciona un método estadístico para decidir si los datos de la muestra están en línea con lo que se creó en la muestra. En el gráfico de abajo, el área azul representa el rendimiento de la muestra de una de mis estrategias. Una inspección visual simple revela un buen ajuste entre el dentro y fuera del rendimiento de la muestra, pero ¿qué grado de confianza que tengo en esto En esta etapa no mucho y este es el problema. Lo que realmente se necesita es una medida de similitud entre los conjuntos de datos de entrada y salida de la muestra. En términos estadísticos, esto podría traducirse como la probabilidad de que las cifras de rendimiento dentro y fuera de la muestra provengan de la misma distribución. Existe una prueba estadística no paramétrica que hace exactamente esto: la Prueba de Kruskall-Wallis. A good definition of this test could be found on R-Tutor 8220A collection of data samples are independent if they come from unrelated populations and the samples do not affect each other. Using the Kruskal-Wallis Test. we can decide whether the population distributions are identical without assuming them to follow the normal distribution.8221 The added benefit of this test is not assuming a normal distribution. It exists other tests of the same nature that could fit into that framework. The Mann-Whitney-Wilcoxon test or the Kolmogorov-Smirnov tests would perfectly suits the framework describes here however this is beyond the scope of this article to discuss the pros and cons of each of these tests. A good description along with R examples can be found here . Here8217s the code used to generate the chart above and the analysis: In the example above the in sample period is longer than the out of sample period therefore I randomly created 1000 subsets of the in sample data each of them having the same length as the out of sample data. Then I tested each in sample subset against the out of sample data and I recorded the p-values. This process creates not a single p-value for the Kruskall-Wallis test but a distribution making the analysis more robust. In this example the mean of the p-values is well above zero (0.478) indicating that the null hypothesis should be accepted: there are strong evidences that the in and out of sample data is coming from the same distribution. As usual what is presented in this post is a toy example that only scratches the surface of the problem and should be tailored to individual needs. However I think it proposes an interesting and rational statistical framework to evaluate out of sample results. This post is inspired by the following two papers: Vigier Alexandre, Chmil Swann (2007), Effects of Various Optimization Functions on the Out of Sample Performance of Genetically Evolved Trading Strategies, Forecasting Financial Markets Conference Vigier Alexandre, Chmil Swann (2010), An optimization process to improve in/out of sample consistency, a Stock Market case, JP Morgan Cazenove Equity Quantitative Conference, London October 2010 fidlr is an RStudio addin designed to simplify the financial data downloading process from various providers. This initial version is a wrapper around the getSymbols function in the quantmod package and only Yahoo, Google, FRED and Oanda are supported. I will probably add functionalities over time. As usual with those things just a kind reminder: 8220THE SOFTWARE IS PROVIDED 8220AS IS8221, WITHOUT WARRANTY OF ANY KIND82308221 How to install and use fidlr You can get the addin/package from its Github repository here (I will register it on CRAN later on) Install the addin. There is an excellent tutorial to install RStudio Addins here . Once the addin is installed it should appear in the Addin menu. Just chose fidlr in the menu and a window as pictured below should appear. Choose a data provider from the the Source dropdown menu. Select a date range from the Date menu Enter the symbol you wish to download in the instrument text box. To download several symbols just enter the symbols separated by commas. Use the Radio buttons to choose whether you want to download the instrument in a csv file or in the global environment. The csv file will be saved in the working directory and there will be one csv file per instrument. Press Run to get the data or Close to close down the addin Error messages and warnings are handled by the underlying packages (quantmod and Shiny) and can be read from the console This is a very first version of the project so do not expect perfection but hopefully it will get better over time. Please report any comment, suggestion, bug etc8230 to: thertradergmail Doing quantitative research implies a lot of data crunching and one needs clean and reliable data to achieve this. What is really needed is clean data that is easily accessible (even without an internet connection). The most efficient way to do this for me has been to maintain a set of csv files. Obviously this process can be handled in many ways but I found very efficient and simple overtime to maintain a directory where I store and update csv files. I have one csv file per instrument and each file is named after the instrument it contains. The reason I do so is twofold: First, I don8217t want to download (price) data from Yahoo, Google etc8230 every time I want to test a new idea but more importantly once I identified and fixed a problem, I don8217t want to have to do it again the next time I need the same instrument. Simple yet very efficient so far. The process is summarized in the chart below. In everything that follows, I assume that data is coming from Yahoo. The code will have to be amended for data from Google, Quandl etc8230 In addition I present the process of updating daily price data. The setup will be different for higher frequency data and other type of dataset (i. e. different from prices). 1 8211 Initial data downloading (listOfInstruments. R amp historicalData. R) The file listOfInstruments. R is a file containing only the list of all instruments. If an instrument isn8217t part of my list (i. e. no csv file in my data folder) or if you do it for the very first time you have to download the initial historical data set. The example below downloads a set of ETFs daily prices from Yahoo Finance back to January 2000 and store the data in a csv file. 2 8211 Update existing data (updateData. R) The below code starts from existing files in the dedicated folder and updates all of them one after the other. I usually run this process everyday except when I8217m on holiday. To add a new instrument, simply run step 1 above for this instrument alone. 3 8211 Create a batch file (updateDailyPrices. bat) Another important part of the job is creating a batch file that automates the updating process above (I8217m a Windows user). This avoids opening R/RStudio and run the code from there. The code below is placed on a. bat file (the path has to be amended with the reader8217s setup). Note that I added an output file (updateLog. txt) to track the execution. The process above is extremely simple because it only describes how to update daily price data. I8217ve been using this for a while and it has been working very smoothly for me so far. For more advanced data and/or higher frequencies, things can get much trickier. As usual any comments welcome When it comes to managing a portfolio of stocks versus a benchmark the problem is very different from defining an absolute return strategy. In the former one has to hold more stocks than in the later where no stocks at all can be held if there is not good enough opportunity. The reason for that is the tracking error . This is defined as the standard deviation of the portfolio return minus the benchmark return. The less stocks is held vs. a benchmark the higher the tracking error (e. g higher risk). The analysis that follows is largely inspired by the book 8220Active Portfolio Management8221 by Grinold amp Kahn. This is the bible for anyone interested in running a portfolio against a benchmark. I strongly encourage anyone with an interest in the topic to read the book from the beginning to the end. It8217s very well written and lays the foundations of systematic active portfolio management (I have no affiliation to the editor or the authors). 1 8211 Factor Analysis Here we8217re trying to rank as accurately as possible the stocks in the investment universe on a forward return basis. Many people came up with many tools and countless variant of those tools have been developed to achieve this. In this post I focus on two simple and widely used metrics: Information Coefficient (IC) and Quantiles Return (QR). 1.1 8211 Information Coefficient The horizon for the forward return has to be defined by the analyst and it8217s a function of the strategy8217s turnover and the alpha decay (this has been the subject of extensive research). Obviously ICs must be as high as possible in absolute terms. For the keen reader, in the book by Grinold amp Kahn a formula linking Information Ratio (IR) and IC is given: with breadth being the number of independent bets (trades). This formula is known as the fundamental law of active management . The problem is that often, defining breadth accurately is not as easy as it sounds. 1.2 8211 Quantiles Return In order to have a more accurate estimate of the factor predictive power it8217s necessary to go a step further and group stocks by quantile of factor values then analyse the average forward return (or any other central tendency metric) of each of those quantiles. The usefulness of this tool is straightforward. A factor can have a good IC but its predictive power might be limited to a small number of stocks. This is not good as a portfolio manager will have to pick stocks within the entire universe in order to meet its tracking error constraint. Good quantiles return are characterised by a monotonous relationship between the individual quantiles and forward returns. All the stocks in the SampP500 index (at the time of writing). Obviously there is a survival ship bias: the list of stocks in the index has changed significantly between the start and the end of the sample period, however it8217s good enough for illustration purposes only. The code below downloads individual stock prices in the SampP500 between Jan 2005 and today (it takes a while) and turns the raw prices into return over the last 12 months and the last month. The former is our factor, the latter will be used as the forward return measure. Below is the code to compute Information Coefficient and Quantiles Return. Note that I used quintiles in this example but any other grouping method (terciles, deciles etc8230) can be used. it really depends on the sample size, what you want to capture and wether you want to have a broad overview or focus on distribution tails. For estimating returns within each quintile, median has been used as the central tendency estimator. This measure is much less sensitive to outliers than arithmetic mean. And finally the code to produce the Quantiles Return chart. 3 8211 How to exploit the information above In the chart above Q1 is lowest past 12 months return and Q5 highest. There is an almost monotonic increase in the quantiles return between Q1 and Q5 which clearly indicates that stocks falling into Q5 outperform those falling into Q1 by about 1 per month. This is very significant and powerful for such a simple factor (not really a surprise though8230). Therefore there are greater chances to beat the index by overweighting the stocks falling into Q5 and underweighting those falling into Q1 relative to the benchmark. An IC of 0.0206 might not mean a great deal in itself but it8217s significantly different from 0 and indicates a good predictive power of the past 12 months return overall. Formal significance tests can be evaluated but this is beyond the scope of this article. 4 8211 Practical limitations The above framework is excellent for evaluating investments factor8217s quality however there are a number of practical limitations that have to be addressed for real life implementation: Rebalancing . In the description above, it8217s assumed that at the end of each month the portfolio is fully rebalanced. This means all stocks falling in Q1 are underweight and all stocks falling in Q5 are overweight relative to the benchmark. This is not always possible for practical reasons: some stocks might be excluded from the investment universe, there are constraints on industry or sector weight, there are constraints on turnover etc8230 Transaction Costs . This has not be taken into account in the analysis above and this is a serious brake to real life implementation. Turnover considerations are usually implemented in real life in a form of penalty on factor quality. Transfer coefficient . This is an extension of the fundamental law of active management and it relaxes the assumption of Grinold8217s model that managers face no constraints which preclude them from translating their investments insights directly into portfolio bets. And finally, I8217m amazed by what can be achieved in less than 80 lines of code with R8230 As usual any comments welcome I come across a lot of strategies on the blogosphere some are interesting some are a complete waste of time but most share a common feature: people developing those strategies do their homework in term of analyzing the return but much less attention is paid to the risk side its random nature. I8217ve seen comment like 8220a 25 drawdown in 2011 but excellent return overall8221. Well my bet is that no one on earth will let you experience a 25 loss with their money (unless special agreements are in place). In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so for a few months before you gain a bit of credibility. First let8217s say you have a bad start and you lose money at the beginning. With a 10 drawdown you8217re most certainly out but even with a 5 drawdown the chances of seeing your allocation reduced are very high. This has significant implications on your strategies. Let8217s assume that if you lose 5 your allocation is divided by 2 and you come back to your initial allocation only when you passed the high water mark again (e. g. the drawdown comes back to 0). In the chart below I simulated the experiment with one of my strategies. You start trading in 1st June 2003 and all goes well until 23rd Jul. 2003 where your drawdown curve hits the -5 threshold (1). Your allocation is cut by 50 and you don8217t cross back the high water mark level until 05th Dec. 2003 (3). If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. 2003 (2) and by the end of the year you would have made more money. But let8217s push the reasoning a bit further. Still on the chart above, assume you get really unlucky and you start trading toward mid-June 2003. You hit the 10 drawdown limit by the beginning of August and you8217re most likely out of the game. You would have started in early August your allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date8230. The trading success of any individual has some form of path dependency and there is not much you can do about it. However you can control the size of a strategy8217s drawdown and this should be addressed with great care. A portfolio should be diversified in every possible dimension: asset classes, investment strategies, trading frequencies etc8230. From that perspective risk is your 8220survival variable8221. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. Otherwise you won8217t be there next month to see what happens. As usual any comments welcome This is a follow up on my previous post 8220A Simple Shiny App for Monitoring Trading Strategies 8220. I added a few improvements that make the app a bit better (at least for me). Below is the list of new features : A sample. csv file (the one that contains the raw data) A 8220EndDate8221 drop down box allowing to specify the end of the period. A 8220Risk8221 page containing a VaR analysis and a chart of worst performance over various horizons A 8220How To8221 page explaining how to use and tailor the app to individual needs I also made the app totally self contained. It is now available as a stand alone product and there is no need to have R/RStudio installed on your computer to run it. It can be downloaded from the R Trader Google drive account. This version of the app runs using portable R and portable Chrome. For the keen reader, this link explains in full details how to package a Shiny app into a desktop app (Windows only for now). 1 8211 How to install amp run the app on your computer Create a specific folder Unzip the contain of the. zip file onto that new folder. Change the paths in the runShinyApp file to match your setings To run the app, you just have launch the run. vbs file. I also included an icon (RTraderTradingApp. ico) should you want to create a shortcut on your desktop. The app uses as input several csv files (one for each strategy). Each file has two columns: date and daily return. There is an example of such a file in the Github repository. The code is essentially made of 3 files. ui. R: controls the layout and appearance of the app server. R: contains the instructions needed to build the app. You can load as much strategies as you want as long as the corresponding csv file has the right format (see below). shinyStrategyGeneral. R: loads the required packages and launches the app put ui. R and server. R file in a separate directory In the server. R file change the inputPath, inputFile and keepColumns parameters to match your settings. The first two are self explanatory the third one is a list of column names within the csv file. Keep only date and daily return. 3 8211 How to add a trading strategy Create the corresponding. csv file in the right directory Create a new input in the data reactive function (within the server. R file) Add an extra element to the choice parameter in the first selectInput in the sidebarPanel (within the ui. R file). The element8217s name should match the name of the new input above. 4 8211 How to remove a trading strategy Remove the input in the data reactive function corresponding to the strategy you want to remove (within the server. R file) Remove the element in the choice parameter in the first selectInput in the sidebarPanel corresponding to the strategy you want to remove (within the ui. R file). Please feel free to get in touch should you have any suggestion. In a previous post I showed how to use R, Knitr and LaTeX to build a template strategy report. This post goes a step further by making the analysis interactive. Besides the interactivity, the Shiny App also solves two problems : I can now access all my trading strategies from a single point regardless of the instrument traded. Coupled with the Shiny interactivity, it allows easier comparison. I can focus on a specific time period. The code used in this post is available on a Gist/Github repository. There are essentially 3 files. ui. R . controls the layout and appearance of the app. server. R . contains the instructions needed to build the app. It loads the data and format it. There is one csv file per strategy each containing at least two columns: date and return with the following format: (82202010-12-228243,82210.048221 ). You can load as much strategies as you want as long as they have the right format. shinyStrategyG eneral. R . loads the required packages and launches the app. This app is probably far from perfect and I will certainly improve it in the future. Feel free to get in touch should you have any suggestion. A big thank you to the RStudio/Shiny team for such a great tool. The question one should always asked him/herself when using technical indicators is what would be an objective criteria to select indicators parameters (e. g. why using a 14 days RSI rather than 15 or 20 days). Genetic algorithms (GA) are well suited tools to answer that question. In this post I8217ll show you how to set up the problem in R. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. Its not a finished strategy either but a research idea that needs to be further researched, developed and tailored to individual needs. What are genetic algorithms The best description of GA I came across comes from Cybernatic Trading a book by Murray A. Ruggiero. 8220Genetic Algorithms were invented by John Holland in the mid-1970 to solve hard optimisation problems. This method uses natural selection, survival of the fittest8221. The general process follows the steps below: Encode the problem into chromosomes Using the encoding, develop a fitness function for use in evaluating each chromosome8217s value in solving a given problem Initialize a population of chromosomes Evaluate each chromosome in the population Create new chromosomes by mating two chromosomes. This is done by muting and recombining two parents to form two children (parents are selected randomly but biased by their fitness) Evaluate the new chromosome Delete a member of the population that is less fit than the new chromosome and insert the new chromosome in the population. If the stop criteria is reached (maximum number of generations, fitness criteria is good enough8230) then return the best chromosome alternatively go to step 4 From a trading perspective GA are very useful because they are good at dealing with highly nonlinear problems. However they exhibit some nasty features that are worth mentioning: Over fitting: This is the main problem and it8217s down to the analyst to set up the problem in a way that minimises this risk. Computing time . If the problem isn8217t properly defined, it can be extremely long to reach a decent solution and the complexity increases exponentially with the number of variables. Hence the necessity to carefully select the parameters. There are several R packages dealing with GA, I chose to use the most common one: rgenoud Daily closing prices for most liquid ETFs from Yahoo finance going back to January 2000. The in sample period goes from January 2000 to December 2010. The Out of sample period starts on January 2011. The logic is as following: the fitness function is optimised over the in sample period to obtain a set of optimal parameters for the selected technical indicators. The performance of those indicators is then evaluated in the out of sample period. But before doing so the technical indicators have to be selected. The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: moving averages cross over and RSI. This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes . The other key element is the fitness function . We might want to use something like: maximum return or Sharpe ratio or minimum average Drawdown. In what follows, I chose to maximise the Sharpe ratio. The R implementation is a set of 3 functions: fitnessFunction . defines the fitness function (e. g. maximum Sharpe ratio) to be used within the GA engine tradingStatistics . summary of trading statistics for the in and out of sample periods for comparison purposes genoud . the GA engine from the rgenoud package The genoud function is rather complex but I8217m not going to explain what each parameter means as I want to keep this post short (and the documentation is really good). In the table below I present for each instrument the optimal parameters (RSI look-back period, RSI threshold, Short Term Moving Average, and Long Term Moving Average) along with the in and out of sample trading statistics. Before commenting the above results, I want to explain a few important points. To match the logic defined above, I bounded the parameters to make sure the look-back period for the long term moving average is always longer that the shorter moving average. I also constrained the optimiser to choose only the solutions with more than 50 trades in the in sample period (e. g, statistical significance). Overall the out of sample results are far from impressive. The returns are low even if the number of trades is small to make the outcome really significant. However there8217s a significant loss of efficiency between in and out of sample period for Japan (EWJ) which very likely means over fitting. This post is intended to give the reader the tools to properly use GA in a quantitative trading framework. Once again, It8217s just an example that needs to be further refined. A few potential improvement to explore would be: fitness function . maximising the Sharpe ratio is very simplistic. A 8220smarter8221 function would certainly improve the out of sample trading statistics pattern . we try to capture a very straightforward pattern. A more in depth pattern research is definitely needed. optimisation . there are many ways to improve the way the optimisation is conducted. This would improve both the computation speed and the rationality of the results. The code used in this post is available on a Gist repository . As usual any comments welcome There is an enormous body of literature both academic and empirical about market forecasting. Most of the time it mixes two market features: Magnitude and Direction. In this article I want to focus on identifying the market direction only. The goal I set myself, is to identify market conditions when the odds are significantly biased toward an up or a down market. This post gives an example of how CART (Classification And Regression Trees) can be used in this context. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. Its not a finished strategy either but a research idea that needs to be further researched, developed and tailored to individual needs. 1 8211 What is CART and why using it From statistics, CART are a set of techniques for classification and prediction. The technique is aimed at producing rules that predict the value of an outcome (target) variable from known values of predictor (explanatory) variables. There are many different implementations but they are all sharing a general characteristic and thats what Im interested in. From Wikipedia, Algorithms for constructing decision trees usually work top-down, by choosing a variable at each step that best splits the set of items. Different algorithms use different metrics for measuring 8220best8221. These generally measure the homogeneity of the target variable within the subsets. These metrics are applied to each candidate subset, and the resulting values are combined (e. g. averaged) to provide a measure of the quality of the split. CART methodology exhibits some characteristics that are very well suited for market analysis: Non parametric . CART can handle any type of statistical distributions Non linear . CART can handle a large spectrum of dependency between variables (e. g. not limited to linear relationships) Robust to outliers There are various R packages dealing with Recursive Partitioning, I use here rpart for trees estimation and rpart. plot for trees drawing. 2 8211 Data amp Experiment Design Daily OHLC prices for most liquid ETFs from January 2000 to December 2013 extracted from Google finance. The in sample period goes from January 2000 to December 2010 the rest of the dataset is the out of sample period. Before running any type of analysis the dataset has to be prepared for the task. The target variable is the ETF weekly forward return defined as a two states of the world outcome (UP or DOWN). If weekly forward return gt 0 then the market in the UP state, DOWN state otherwise The explanatory variables are a set of technical indicators derived from the initial daily OHLC dataset. Each indicator represents a well-documented market behavior. In order to reduce the noise in the data and to try to identify robust relationships, each independent variable is considered to have a binary outcome. Volatility (VAR1) . High volatility is usually associated with a down market and low volatility with an up market. Volatility is defined as the 20 days raw ATR (Average True Range) spread to its moving average (MA). If raw ATR gt MA then VAR1 1, else VAR1 -1. Short term momentum (VAR2) . The equity market exhibits short term momentum behavior captured here by a 5 days simple moving averages (SMA). If Price gt SMA then VAR2 1 else VAR2 -1 Long term momentum (VAR3) . The equity market exhibits long term momentum behavior captured here by a 50 days simple moving averages (LMA). If Price gt LMA then VAR3 1 else VAR3 -1 Short term reversal (VAR4) . This is captured by the CRTDR which stands for Close Relative To Daily Range and calculated as following: . If CRTDR gt 0.5, then VAR4 1 else VAR4 -1 Autocorrelation regime (VAR5) . The equity market tends to go through periods of negative and positive autocorrelation regimes. If returns autocorrelation over the last 5 days gt 0 then VAR5 1 else VAR5 -1 I put below a tree example with some explanations In the tree above, the path to reach node 4 is: VAR3 gt0 (Long Term Momentum gt 0) and VAR4 gt 0 (CRTDR gt 0). The red rectangle indicates this is a DOWN leaf (e. g. terminal node) with a probability of 58 (1 8211 0.42). In market terms this means that if Long Term Momentum is Up and CRTDR is gt 0.5 then the probability of a positive return next week is 42 based on the in sample sample data. 18 indicates the proportion of the data set that falls into that terminal node (e. g. leaf). There are many ways to use the above approach, I chose to estimate and combine all possible trees. From the in sample data, I collect all leaves from all possible trees and I gather them into a matrix. This is the 8220rules matrix8221 giving the probability of next week beeing UP or DOWN. I apply the rules in the above matrix to the out of sample data (Jan 2011 8211 Dec 2013) and I compare the results to the real outcome. The problem with this approach is that a single point (week) can fall into several rules and even belong to UP and DOWN rules simultaneously. Therefore I apply a voting scheme . For a given week I sum up all the rules that apply to that week giving a 1 for an UP rule and -1 for a DOWN rule. If the sum is greater than 0 the week is classified as UP, if the sum is negative it8217s a DOWN week and if the sum is equal to 0 there will be no position taken that week (return 0) The above methodology is applied to a set of very liquid ETFs. I plot below the out of sample equity curves along with the buy and hold strategy over the same period. Initial results seem encouraging even if the quality of the outcome varies greatly by instrument. However there is a huge room for improvement. I put below some directions for further analysis Path optimality . The algorithm used here for defining the trees is optimal at each split but it doesn8217t guarantee the optimality of the path. Adding a metric to measure the optimality of the path would certainly improve the above results. Other variables . I chose the explanatory variables solely based on experience. It8217s very likely that this choice is neither good nor optimal. Backtest methodology . I used a simple In and Out of sample methodology. In a more formal backtest I would rather use a rolling or expanding window of in and out sample sub-periods (e. g. walk forward analysis) As usual, any comments welcome A few obvious features clearly appear For US Equity markets (SPY, QQQ, IWM), Emerging Equity Markets (EEM), Metals (GLD, GDX, SLV) and Investment Grades (LQD) the bulk of the return is definitely made overnight. Intraday returns tend to deteriorate the overall performance (intraday return lt 0) The exact opposite is true for European Equity Markets (EFA, EWG, EWU, EWL), US Bonds (SHY, IEF, TLT) and Oil (USO). Overnight returns are detracting significantly from the overall performance. I didn8217t manage to come up with a decent explanation about why this is happening but I8217m keen on learning if someone is willing to share I8217m not too sure at this stage how this information can be used but it has to be taken into account somehow. Below is the code for generating the analysis above. As usual any comments welcome Recent Posts Archives Categories Blogroll 72 queries. 0.895 seconds.

No comments:

Post a Comment