QSForex es un backtesting basado en eventos de código abierto y una plataforma de trading en vivo para uso en los mercados de divisas (forex), actualmente en un estado alfa. Se ha creado como parte de la serie Forex Trading Diario en QuantStart para proporcionar a la comunidad de comercio sistemática con un motor de comercio robusto que permite la implementación de la estrategia de Forex y las pruebas directas. El software se proporciona bajo una licencia permisiva del MIT (véase abajo). Open-Source - QSForex ha sido lanzado bajo una Licencia de MIT de código abierto extremadamente permisiva, que permite el uso completo en aplicaciones de investigación y comerciales, sin restricciones, pero sin garantía de ningún tipo. Gratis - QSForex es completamente gratuito y no cuesta nada descargar o usar. Colaboración - Como QSForex es de código abierto, muchos desarrolladores colaboran para mejorar el software. Se agregan nuevas funciones con frecuencia. Cualquier error es rápidamente determinado y fijo. Desarrollo de software - QSForex está escrito en el lenguaje de programación de Python para soporte directo de multiplataforma. QSForex contiene un conjunto de pruebas de unidad para la mayoría de su código de cálculo y nuevas pruebas se agregan constantemente para nuevas características. Arquitectura impulsada por eventos - QSForex es completamente dirigida por eventos, tanto para backtesting como para comercio en vivo, lo que lleva a la transición directa de estrategias desde una fase de investigación / prueba hasta una implementación de trading en vivo. Costes de transacción - Los costes de propagación se incluyen de forma predeterminada para todas las estrategias de backtest. Backtesting - QSForex ofrece backtesting de varios días de varias divisas de resolución de ticks. Trading - QSForex actualmente soporta el comercio intraday en vivo utilizando el OANDA Brokerage API a través de una cartera de pares. Métricas de rendimiento - QSForex actualmente admite la medición del rendimiento básico y la visualización de la equidad a través de las bibliotecas de visualización Matplotlib y Seaborn. Instalación y uso 1) Visite oanda / y configure una cuenta para obtener las credenciales de autenticación de la API, que deberá realizar en vivo. Explicar cómo llevar a cabo esto en este artículo: Quantstart / articles / Forex-Trading-Diario-1-Automated-Forex-Trading-con-el-OANDA-API. 2) Clone este repositorio git en una ubicación adecuada en su máquina usando el siguiente comando en su terminal: git clone github / mhallsmoore / qsforex. git. Alternativa puede descargar el archivo zip de la rama principal actual en github / mhallsmoore / qsforex / archive / master. zip. 3) Cree un conjunto de variables de entorno para todas las configuraciones encontradas en el archivo settings. py en el directorio raíz de la aplicación. Alternativamente, puede codificar sus configuraciones específicas sobrescribiendo las llamadas os. environ. get (.) Para cada configuración: 4) Cree un entorno virtual (virtualenv) para el código QSForex y utilice pip para instalar los requisitos. Por ejemplo, en un sistema basado en Unix (Mac o Linux) puede crear un directorio como el siguiente introduciendo los siguientes comandos en el terminal: Esto creará un nuevo entorno virtual para instalar los paquetes en. Suponiendo que descargó el repositorio gist QSForex en un directorio de ejemplo como / projects / qsforex / (cambie este directorio a donde quiera que haya instalado QSForex), entonces para instalar los paquetes necesitará ejecutar los siguientes comandos: Tiempo como NumPy, SciPy, Pandas, Scikit-Learn y Matplotlib deben ser compilados. Hay muchos paquetes necesarios para que esto funcione, así que eche un vistazo a estos dos artículos para obtener más información: También tendrá que crear un enlace simbólico desde su directorio de paquetes de sitio a su directorio de instalación de QSForex para poder llamar Import qsforex dentro del código. Para ello, necesitará un comando similar al siguiente: Asegúrese de cambiar / projects / qsforex a su directorio de instalación y /venv/qsforex/lib/python2.7/site-packages/ a su directorio de paquetes de sitios virtualenv. Ahora podrá ejecutar los comandos siguientes correctamente. 5) En esta etapa, si simplemente desea llevar a cabo la práctica o el comercio en vivo, entonces puede ejecutar python trading / trading. py. Que utilizará la estrategia de trading predeterminada de TestStrategy. Esto simplemente compra o vende un par de divisas cada 5 tick. Es puramente para la prueba - no la utilice en un ambiente que vive vivo Si usted desea crear una estrategia más útil, después cree simplemente una nueva clase con un nombre descriptivo, por ejemplo. MeanReversionMultiPairStrategy y asegúrese de que tiene un método calculatesignals. Tendrá que pasar a esta clase la lista de parejas, así como la cola de eventos, como en trading / trading. py. Por favor, vea strategy / strategy. py para más detalles. 6) Con el fin de llevar a cabo cualquier backtesting es necesario generar datos de forex simulados o descargar datos históricos tick. Si desea simplemente probar el software, la forma más rápida de generar un ejemplo de backtest es generar algunos datos simulados. El formato de datos actual utilizado por QSForex es el mismo que el proporcionado por el DukasCopy Historical Data Feed en dukascopy / swiss / english / marketwatch / historical /. Para generar algunos datos históricos, asegúrese de que la configuración de CSVDATADIR en settings. py debe establecerse en un directorio donde desee que los datos históricos se mantengan. A continuación, debe ejecutar generatesimulatedpair. py. Que está en el directorio scripts /. Se espera un solo argumento de línea de comandos, que en este caso es el par de divisas en formato BBBQQQ. Por ejemplo: En esta etapa, el script está codificado para crear un solo mes de datos para enero de 2014. Es decir, verá archivos individuales, del formato BBBQQQYYYYMMDD. csv (por ejemplo, GBPUSD20140112.csv) aparecen en su CSVDATADIR para todos los días hábiles en Ese mes. Si desea cambiar el mes / año de la salida de datos, simplemente modifique el archivo y vuelva a ejecutarlo. 7) Ahora que los datos históricos han sido generados es posible realizar un backtest. El archivo backtest se almacena en backtest / backtest. py. Pero esto sólo contiene la clase Backtest. Para ejecutar realmente un backtest es necesario instanciar esta clase y proporcionarle los módulos necesarios. La mejor manera de ver cómo se hace esto es mirar el ejemplo de implementación de Media Crossover de Moving en el archivo examples / mac. py y usarlo como una plantilla. Esto hace uso de MovingAverageCrossStrategy que se encuentra en strategy / strategy. py. Por defecto, se negocian GBP / USD y EUR / USD para demostrar el uso de varios pares de divisas. Utiliza los datos encontrados en CSVDATADIR. Para ejecutar el ejemplo backtest, simplemente ejecute lo siguiente: Esto llevará algún tiempo. En mi sistema de escritorio Ubuntu en casa, con los datos históricos generados a través de generatesimulatedpair. py. Tarda alrededor de 5-10 minutos para correr. Una gran parte de este cálculo se produce al final del backtest real, cuando se calcula la reducción, así que por favor recuerde que el código no ha colgado Por favor, déjelo hasta su finalización. 8) Si desea ver el rendimiento del backtest, puede utilizar output. py para ver una curva de equidad, retornos de periodo (es decir, tick-to-tick) y una curva de reducción: Y eso es todo. Para comenzar a crear sus propios backtests modificando o añadiendo estrategias en strategy / strategy. py y utilizando datos reales descargados de DukasCopy (dukascopy / swiss / english / marketwatch / historical /). Si tiene alguna pregunta sobre la instalación, por favor no dude en enviarme un correo electrónico a mikequantstart. Si tiene algún error o cualquier otro problema que cree que puede ser debido específicamente a la base de código, no dude en abrir un problema de Github aquí: github / mhallsmoore / qsforex / issues Copyright (c) 2015 Michael Halls-Moore A cualquier persona que obtenga una copia de este software y archivos de documentación asociados (el Software), para tratar el Software sin restricciones, incluyendo, sin limitación, los derechos de usar, copiar, modificar, fusionar, publicar, distribuir, sublicenciar y O vender copias del Software y permitir que las personas a las que se suministre el Software, con sujeción a las siguientes condiciones: El aviso de copyright anterior y este aviso de permiso se incluirán en todas las copias o partes sustanciales del Software. EL SOFTWARE SE PROPORCIONA TAL CUAL, SIN GARANTÍA DE NINGÚN TIPO, EXPLÍCITA O IMPLÍCITA, INCLUYENDO PERO SIN LIMITARSE A LAS GARANTÍAS DE COMERCIABILIDAD, ADECUACIÓN PARA UN FIN DETERMINADO Y NO INFRACCIÓN. EN NINGÚN CASO, LOS AUTORES O LOS TITULARES DE DERECHOS DE AUTOR SERÁN RESPONSABLES DE CUALQUIER RECLAMACIÓN, DAÑO O CUALQUIER OTRA RESPONSABILIDAD, YA SEA EN UNA ACCIÓN DE CONTRATO, AGRAVIO O DE OTRA MANERA, QUE SURJA DE O EN RELACIÓN CON EL SOFTWARE O EL USO O OTROS NEGOCIOS EN EL SOFTWARE. Descargo de divisas Forex Trading El cambio de divisas en el margen conlleva un alto nivel de riesgo y puede no ser adecuado para todos los inversores. Los resultados anteriores no son indicativos de resultados futuros. El alto grado de apalancamiento puede trabajar en su contra, así como para usted. Antes de decidir invertir en divisas debe considerar cuidadosamente sus objetivos de inversión, nivel de experiencia y apetito de riesgo. Existe la posibilidad de que usted podría sostener una pérdida de parte o la totalidad de su inversión inicial y por lo tanto no debe invertir dinero que no puede permitirse perder. Usted debe ser consciente de todos los riesgos asociados con el comercio de divisas, y buscar el asesoramiento de un asesor financiero independiente si tiene alguna duda. QSForex es un backtesting impulsado por eventos de código abierto y la plataforma de comercio en vivo para su uso en el mercado de divisas ), Actualmente en un estado alfa. Se ha creado como parte de la serie Forex Trading Diario en QuantStart para proporcionar a la comunidad de comercio sistemática con un motor de comercio robusto que permite la implementación de la estrategia de Forex y las pruebas directas. El software se proporciona bajo una licencia permisiva del MIT (véase abajo). Open-Source - QSForex ha sido lanzado bajo una Licencia de MIT de código abierto extremadamente permisiva, que permite el uso completo en aplicaciones de investigación y comerciales, sin restricciones, pero sin garantía de ningún tipo. Gratis - QSForex es completamente gratuito y no cuesta nada descargar o usar. Colaboración - Como QSForex es de código abierto, muchos desarrolladores colaboran para mejorar el software. Se agregan nuevas funciones con frecuencia. Cualquier error es rápidamente determinado y fijo. Desarrollo de software - QSForex está escrito en el lenguaje de programación de Python para soporte directo de multiplataforma. QSForex contiene un conjunto de pruebas de unidad para la mayoría de su código de cálculo y nuevas pruebas se agregan constantemente para nuevas características. Arquitectura impulsada por eventos - QSForex es completamente dirigida por eventos, tanto para backtesting como para comercio en vivo, lo que lleva a la transición directa de estrategias desde una fase de investigación / prueba hasta una implementación de trading en vivo. Costes de transacción - Los costes de propagación se incluyen de forma predeterminada para todas las estrategias de backtest. Backtesting - QSForex ofrece backtesting de varios días de varias divisas de resolución de ticks. Trading - QSForex actualmente soporta el comercio intraday en vivo utilizando el OANDA Brokerage API a través de una cartera de pares. Métricas de rendimiento - QSForex actualmente admite la medición del rendimiento básico y la visualización de la equidad a través de las bibliotecas de visualización Matplotlib y Seaborn. Instalación y uso 1) Visite oanda / y configure una cuenta para obtener las credenciales de autenticación de la API, que necesitará para realizar transacciones en vivo. Explicar cómo llevar a cabo esto en este artículo: Quantstart / articles / Forex-Trading-Diario-1-Automated-Forex-Trading-con-el-OANDA-API. 2) Clone este repositorio git en una ubicación adecuada en su máquina usando el siguiente comando en su terminal: git clone github / mhallsmoore / qsforex. git. Alternativa puede descargar el archivo zip de la rama principal actual en github / mhallsmoore / qsforex / archive / master. zip. 3) Cree un conjunto de variables de entorno para todas las configuraciones encontradas en el archivo settings. py en el directorio raíz de la aplicación. Alternativamente, puede codificar sus configuraciones específicas sobrescribiendo las llamadas os. environ. get (.) Para cada configuración: 4) Cree un entorno virtual (virtualenv) para el código QSForex y utilice pip para instalar los requisitos. Por ejemplo, en un sistema basado en Unix (Mac o Linux) puede crear un directorio como el siguiente introduciendo los siguientes comandos en el terminal: Esto creará un nuevo entorno virtual para instalar los paquetes en. Suponiendo que descargó el repositorio gist QSForex en un directorio de ejemplo como / projects / qsforex / (cambie este directorio a donde quiera que haya instalado QSForex), entonces para instalar los paquetes necesitará ejecutar los siguientes comandos: Tiempo como NumPy, SciPy, Pandas, Scikit-Learn y Matplotlib deben ser compilados. Hay muchos paquetes necesarios para que esto funcione, así que eche un vistazo a estos dos artículos para obtener más información: También tendrá que crear un enlace simbólico desde su directorio de paquetes de sitio a su directorio de instalación QSForex para poder llamar Import qsforex dentro del código. Para ello necesitará un comando similar al siguiente: Asegúrese de cambiar / projects / qsforex a su directorio de instalación y /venv/qsforex/lib/python2.7/site-packages/ a su directorio de paquetes de sitios virtualenv. Ahora podrá ejecutar los comandos siguientes correctamente. 5) En esta etapa, si simplemente desea llevar a cabo la práctica o el comercio en vivo, entonces puede ejecutar python trading / trading. py. Que utilizará la estrategia de trading predeterminada de TestStrategy. Esto simplemente compra o vende un par de divisas cada 5 tick. Es puramente para la prueba - no la utilice en un ambiente que vive vivo Si usted desea crear una estrategia más útil, después cree simplemente una nueva clase con un nombre descriptivo, por ejemplo. MeanReversionMultiPairStrategy y asegúrese de que tiene un método calculatesignals. Tendrá que pasar a esta clase la lista de parejas, así como la cola de eventos, como en trading / trading. py. Por favor, vea strategy / strategy. py para más detalles. 6) Con el fin de llevar a cabo cualquier backtesting es necesario generar datos de forex simulados o descargar datos históricos tick. Si desea simplemente probar el software, la forma más rápida de generar un ejemplo de backtest es generar algunos datos simulados. El formato de datos actual utilizado por QSForex es el mismo que el proporcionado por el DukasCopy Historical Data Feed en dukascopy / swiss / english / marketwatch / historical /. Para generar algunos datos históricos, asegúrese de que la configuración de CSVDATADIR en settings. py debe establecerse en un directorio donde desee que los datos históricos se mantengan. A continuación, debe ejecutar generatesimulatedpair. py. Que está en el directorio scripts /. Se espera un solo argumento de línea de comandos, que en este caso es el par de divisas en formato BBBQQQ. Por ejemplo: En esta etapa, el script está codificado para crear un solo mes de datos para enero de 2014. Es decir, verá archivos individuales, del formato BBBQQQYYYYMMDD. csv (por ejemplo, GBPUSD20140112.csv) aparecen en su CSVDATADIR para todos los días hábiles en Ese mes. Si desea cambiar el mes / año de la salida de datos, simplemente modifique el archivo y vuelva a ejecutarlo. 7) Ahora que los datos históricos han sido generados es posible realizar un backtest. El archivo backtest se almacena en backtest / backtest. py. Pero esto sólo contiene la clase Backtest. Para ejecutar realmente un backtest es necesario instanciar esta clase y proporcionarle los módulos necesarios. La mejor manera de ver cómo se hace esto es mirar el ejemplo de implementación de Media Crossover de Moving en el archivo examples / mac. py y usarlo como una plantilla. Esto hace uso de MovingAverageCrossStrategy que se encuentra en strategy / strategy. py. Por defecto, se negocian GBP / USD y EUR / USD para demostrar el uso de varios pares de divisas. Utiliza los datos encontrados en CSVDATADIR. Para ejecutar el ejemplo backtest, simplemente ejecute lo siguiente: Esto llevará algún tiempo. En mi sistema de escritorio Ubuntu en casa, con los datos históricos generados a través de generatesimulatedpair. py. Tarda alrededor de 5-10 minutos para correr. Una gran parte de este cálculo se produce al final del backtest real, cuando se calcula la reducción, así que por favor recuerde que el código no ha colgado Por favor, déjelo hasta su finalización. 8) Si desea ver el rendimiento del backtest, puede utilizar output. py para ver una curva de equidad, retornos de periodo (es decir, tick-to-tick) y una curva de reducción: Y eso es todo. Para comenzar a crear sus propios backtests modificando o añadiendo estrategias en strategy / strategy. py y utilizando datos reales descargados de DukasCopy (dukascopy / swiss / english / marketwatch / historical /). Si tiene alguna pregunta sobre la instalación, por favor no dude en enviarme un correo electrónico a mikequantstart. Si tiene algún error o cualquier otro problema que cree que puede ser debido específicamente a la base de código, no dude en abrir un problema de Github aquí: github / mhallsmoore / qsforex / issues Copyright (c) 2015 Michael Halls-Moore A cualquier persona que obtenga una copia de este software y archivos de documentación asociados (el Software), para tratar el Software sin restricciones, incluyendo, sin limitación, los derechos de usar, copiar, modificar, fusionar, publicar, distribuir, sublicenciar y O vender copias del Software y permitir que las personas a las que se suministre el Software, con sujeción a las siguientes condiciones: El aviso de copyright anterior y este aviso de permiso se incluirán en todas las copias o partes sustanciales del Software. EL SOFTWARE SE PROPORCIONA COMO ES, SIN GARANTÍA DE NINGÚN TIPO, EXPLÍCITA O IMPLÍCITA, INCLUYENDO PERO SIN LIMITARSE A LAS GARANTÍAS DE COMERCIABILIDAD, ADECUACIÓN PARA UN FIN DETERMINADO Y NO INFRACCIÓN. EN NINGÚN CASO, LOS AUTORES O LOS TITULARES DE DERECHOS DE AUTOR SERÁN RESPONSABLES DE CUALQUIER RECLAMACIÓN, DAÑO O CUALQUIER OTRA RESPONSABILIDAD, YA SEA EN UNA ACCIÓN DE CONTRATO, AGRAVIO O DE OTRA MANERA, QUE SURJA DE O EN RELACIÓN CON EL SOFTWARE O EL USO O OTROS NEGOCIOS EN EL SOFTWARE. Descargo de divisas Forex Trading El cambio de divisas en el margen conlleva un alto nivel de riesgo y puede no ser adecuado para todos los inversores. Los resultados anteriores no son indicativos de resultados futuros. El alto grado de apalancamiento puede trabajar en su contra, así como para usted. Antes de decidir invertir en divisas debe considerar cuidadosamente sus objetivos de inversión, nivel de experiencia y apetito de riesgo. Existe la posibilidad de que usted podría sostener una pérdida de parte o la totalidad de su inversión inicial y por lo tanto no debe invertir dinero que no puede permitirse perder. Usted debe ser consciente de todos los riesgos asociados con el comercio de divisas, y buscar el asesoramiento de un asesor financiero independiente si tiene alguna duda. Este post será una revisión en profundidad de Alpha Architect8217s Cuantitativo Momentum libro. En general, en mi opinión, el libro es fantástico para aquellos que son profesionales en la gestión de fondos en el espacio de la equidad individual, y todavía contiene ideas vale la pena pensar fuera de ese espacio. Sin embargo, el sistema detallado en el libro se beneficia de una clasificación anidada (rango a lo largo del eje X, tomar el decil superior, clasificar a lo largo del eje Y dentro del decil superior en X y tomar el decil superior a lo largo del eje Y, restringiendo esencialmente la selección a 1 universo). Además, el libro no hace mucho para tocar los controles de volatilidad, lo que puede haber mejorado el sistema descrito en gran medida. Antes de que me meta en el peso de este post, me gustaría dejar a mis lectores saber que formalizé mis nueces y pernos de la serie quantstrat de mensajes como un curso formal de datacamp. Datacamp es una forma muy barata de aprender un montón de R, y las aplicaciones financieras están entre esos temas. Mi curso cubre los fundamentos de quantstrat, y si aquellos que completan el curso como él, puedo muy bien crear módulos más avanzados quantstrat en datacamp. Espero que los cursos de finanzas sean bien recibidos, ya que hay temas financieros en los que me gusta aprender que una conferencia de 45 minutos realmente es suficiente (como el Dr. David Matteson 8217s cambia de magia, PortfolioAnalytics, etc.). En cualquier caso, aquí está el enlace. Por lo tanto, vamos a empezar con un resumen del libro: Parte 1 es varios capítulos que son la exposición gigante de por qué funciona el momentum (o al menos, ha trabajado durante al menos 20 años desde 1993), es decir, que los sesgos humanos y los comportamientos irracionales actúan Ciertas maneras de hacer que la anomalía funcione. Luego, también el riesgo de carrera (AKA es un factor de riesgo, y por lo tanto, si su punto de referencia es SPY y se ejecuta a través de un período de 3 años de bajo rendimiento, usted tiene grave riesgo de carrera), y esencialmente, una letanía de por qué un activo profesional Gerente sería despedido, pero si usted acaba de pegarse con la anomalía durante muchos años y montar multi-año estiramientos de relativo bajo rendimiento, you8217ll salir adelante en el muy largo plazo. Generalmente, siento que hay trabajo que hacer si esto es lo mejor que se puede hacer, pero bueno, lo aceptaré. Esencialmente, la parte 1 es para los no iniciados. Para aquellos que han estado alrededor del bloque de impulso un par de veces, pueden saltar a la derecha después de esto. Por desgracia, es la mitad del libro, por lo que deja un poco de sabor amargo en la boca. A continuación, la parte dos es donde, en mi opinión, la verdadera carne y patatas del libro, la 8220how8221. Esencialmente, el algoritmo puede ser reducido a lo siguiente: Tomando el universo de las acciones grandes y medianas, haga lo siguiente: 1) Ordenar las existencias en deciles por 2-12 momentum8211 es decir, al final de cada mes, calcular el momento Por último mes8217s precio de cierre menos el precio de cierre hace 12 meses. Esencialmente, la investigación indica que hay un efecto de reversión en el impulso de 1 mes. Sin embargo, este efecto no se traslada al universo de la ETF en mi experiencia. 2) Aquí está la parte interesante que hace que el libro valga la pena por sí solo (en mi opinión): después de clasificar en deciles, clasifique el decil superior por la siguiente métrica: multiplique el signo del momento 2-12 por la siguiente ecuación: (Los resultados negativos 8211 son positivos). Esencialmente, la idea aquí es determinar la suavidad del momento. Es decir, en la situación más extrema, imaginar una acción que no hizo absolutamente nada durante 230 días, y luego tuvo un día masivo que le dio toda su apreciación de precios (creo que Google cuando tuvo un 10 saltar de números mejor de lo esperado Informes), y en el otro extremo, una acción que simplemente tenía cada día ser una pequeña apreciación positiva del precio. Obviamente, quieres el segundo tipo de acciones. Esa es la idea. Una vez más, clasificar en deciles, y tomar el decil superior. Por lo tanto, tomar el decil superior del decile superior te deja con 1 del universo. Esencialmente, esto hace que la idea sea muy difícil de replicar, ya que usted necesita rastrear un enorme universo de acciones. Dicho esto, creo que la expresión es realmente una idea bastante buena como un stand-in para la volatilidad. Es decir, independientemente de cuán volátil sea un activo si es tan volátil como una mercancía como DBC, o como no volátil como un producto de renta fija como SHY, esta expresión es una manera interesante de afirmar que este camino es choppy8221 vs. 8220 este camino es Smooth8221. Podría investigar esta expresión en mi blog más adelante en el futuro. 3) Por último, si la cartera está cambiando trimestralmente en lugar de mensual, los mejores meses para darle vuelta son los meses que preceden al mes de fin de trimestre (es decir, febrero, mayo, agosto, noviembre) porque un montón de activos aficionados Los gerentes tienen gusto de 8220window vestir8221 sus carteras. Es decir, tuvieron un cuarto malo, por lo que en el último mes antes de que tienen que enviar declaraciones trimestrales, se cargan a algunos ganadores recientes para que sus clientes no creen que son tan aficionados como realmente lo hacen, y hay un golpe para esta. Del mismo modo, enero tiene algunas anomalías de venta debido a la recolección de impuestos. En cuanto a las implementaciones prácticas, creo que esto es un toque muy agradable. Concediendo el hecho de que dar vuelta cada mes puede ser un poco demasiado caro, me gusta que Wes y Jack dicen 8220sure, que desea convertirlo una vez cada tres meses, pero en que months8221. Es una pregunta muy buena para preguntar si significa que obtendrá un punto porcentual adicional o 150 bps al año a partir de eso, ya que sólo podría cubrir los costos de transacción y, a continuación, algunos. En general, es una estrategia bastante simple de entender. Sin embargo, la parte que tipo de puertas del libro a una réplica perfecta es la dificultad en la obtención de los datos de CRSP. Sin embargo, recomiendo Alpha Architect por revelar todo el algoritmo de principio a fin. Además, si el impulso básico 2-12 no es suficiente, hay un apéndice que detalla otros tipos de ideas de momentum (dinámica de ganancias, clasificación por distancia a máximos de 52 semanas, momento histórico absoluto, etc.). Ninguna de estas estrategias es realmente mucho mejor que la estrategia de impulso de precio básico, por lo que están ahí para los interesados, pero parece que no hay nada realmente innovador allí. Es decir, si usted está negociando una vez al mes, sólo hay tantas maneras de decirlo, creo que esta cosa está subiendo. También me gusta que Wes y Jack se refirieran al hecho de que el seguimiento de tendencias, mientras que no mejora el CAGR o Sharpe , Hace una cantidad enorme para mejorar en la reducción máxima. Es decir, si se enfrentan con la perspectiva de perder 70-80 de todo, y perder sólo 30, que8217s una elección fácil de hacer. Tendencia de seguimiento es bueno, incluso una versión simplista. En general, creo que el libro cumple lo que se propone hacer, que es presentar un algoritmo bien investigado. En última instancia, el punchline está en el sitio de Alpha Architect8217s (creo que tienen algún tipo de filtro de stock mensual). Además, el libro afirma que hay mejores rendimientos ajustados al riesgo cuando se combina con el algoritmo descrito en el libro de valor cuantitativo 8221. En mi experiencia, nunca he tenido los algoritmos de valor me impresionan en el backtests I8217ve hecho, pero puedo tiza que hasta que yo sea inexperto con todas las métricas de valoración diferentes. Mi crítica del libro, sin embargo, es la siguiente: El algoritmo de momento en el libro pierde lo que siento es un componente clave: volatilidad de control de orientación. Simplemente, el documento 8220momentum tiene sus momentos8221 (que he cubierto en mis series de desarrollo impulsadas por la hipótesis) señala esencialmente que la estrategia habitual de momento Fama-Francés es mucho mejor de una estrategia de riesgo-recompensa por el desapalancamiento en tiempos de volatilidad excesiva y Evitando choques momentum. No estoy seguro de por qué Wes y Jack no tocaron este artículo, ya que la implementación es muy simple (factor de apalancamiento de volatilidad objetivo / realizado). Idealmente, me encantaría que Wes o Jack me enviara la corriente de devoluciones para esta estrategia (preferiblemente diariamente, pero mensualmente también funciona). Esencialmente, creo que este libro es muy completo. Sin embargo, creo que también tiene un 8220don8217t probar esto en home8221 se siente debido a la necesidad de datos para replicar. Ciertamente, si su corredor le cobra una transacción, no es una estrategia factible dejar caer varios miles de dólares al año en los costos de transacción que sólo le darán sus retornos a su corredor. Sin embargo, me pregunto si el QMOM ETF (de Alpha Architect, por supuesto) es, de hecho, una mejor versión de esta estrategia, fuera de la cuota de gestión. En cualquier caso, mi opinión final es la siguiente: mientras este libro deja un poco de conocimiento sobre la mesa, en su conjunto, cumple lo que se propone hacer, está claro con sus procedimientos y proporciona varias ideas valiosas. Por el precio de un libro de texto no técnico (aka los 60 libros sobre amazon), este libro es un robo. Gracias por leer. NOTA: Mientras estoy actualmente empleado en una capacidad de análisis exitosa, estoy interesado en escuchar acerca de puestos de tiempo completo más estrechamente relacionados con los temas de este blog. Si usted tiene una posición de tiempo completo que puede beneficiarse de mis habilidades actuales, por favor hágamelo saber. Mi Linkedin se puede encontrar aquí. Esta publicación tratará de intentar utilizar el paquete Depmix para la predicción de estado en línea. Mientras que el paquete depmix se desempeña admirablemente cuando se trata de describir los estados del pasado, cuando se usa para una predicción de un paso adelante, bajo el supuesto de que el estado de tomorrow8217s será idéntico a today8217s, el proceso de markov oculto encontrado en el paquete no Cumplir con las expectativas. Así, para empezar, este post fue motivado por Michael Halls-Moore, quien recientemente publicó un código R sobre el uso de la librería depmixS4 para usar modelos de markov ocultos. Por lo general, estoy reacio a crear mensajes sobre temas que no siento que tengo una comprensión absoluta de adelante a atrás, pero estoy haciendo esto con la esperanza de aprender de otros sobre cómo hacer correctamente la predicción de espacio en estado en línea o 8220regime switching8221 Detección, como puede llamarse en un lenguaje más financiero. Aunque he visto la teoría habitual de los modelos de markov ocultos (es decir, puede llover o puede ser soleado, pero sólo se puede inferir el tiempo a juzgar por la ropa que ves a la gente que usa fuera de su ventana cuando se despierta) y han trabajado Con ejemplos de juguete en MOOCs (Udacity8217s auto-conducción coche curso trata con ellos, si recuerdo correctamente8211 o tal vez fue el curso de AI), al final del día, la teoría es tan bueno como lo bien que una aplicación puede trabajar en datos reales . Para este experimento, decidí tomar los datos del SPY desde el inicio, y hacer un 8220backtest8221 completo en la muestra en los datos. Es decir, dado que el algoritmo HMM de depmix ve toda la historia de los retornos, con esta vista de los datos, el algoritmo clasifica correctamente los regímenes, si los resultados del backtest son cualquier indicación del código para hacerlo, inspirado en Dr. Halls-Moore8217s. Esencialmente, mientras que seleccioné tres estados, noté que cualquier cosa con una intercepción por encima de cero es un estado de toro, y por debajo de cero es un estado de oso, por lo que esencialmente, se reduce a dos estados. Con el resultado: Por lo tanto, no es particularmente terrible. El algoritmo funciona, tipo de, especie de, bien Bueno, let8217s probar la predicción en línea ahora. Así que lo que hice aquí fue que tomé una ventana en expansión, a partir de 500 días desde el inicio SPY8217s, y siguió aumentando, por un día a la vez. Mi predicción fue, trivialmente, el día más reciente, usando un 1 para un estado de toro, y un -1 para un estado de oso. Ejecuté este proceso en paralelo (en un clúster linux, porque la biblioteca doParallel de windows8217s parece ni siquiera saber que ciertos paquetes están cargados, y it8217s más desordenado), y el primer gran problema es que este proceso tomó alrededor de tres horas en siete núcleos Aproximadamente 23 años de datos. No es exactamente alentador, pero el tiempo de computación no es caro en estos días. Así que vamos a ver si este proceso realmente funciona. En primer lugar, vamos a probar si el algoritmo hace lo que realmente se supone que debe hacer y usar un día de sesgo prospectivo (es decir, el algoritmo nos dice el estado al final del día), como es correcto para ese día. Con el resultado: Así, supuestamente, el algoritmo parece hacer lo que fue diseñado para hacer, que es clasificar un estado para un conjunto de datos dado. Ahora, la pregunta más pertinente: ¿qué tan bien hacen estas predicciones incluso un día de anticipación? Creo que las predicciones de espacio de estado sería parsimonioso de un día a otro, dada la larga historia, correcta con el resultado: es decir, sin el sesgo de mira, el El algoritmo de predicción de espacio de estado es atroz. En resumen, el algoritmo hmm en línea en el paquete depmix parece cambiar su mente muy fácilmente, con implicaciones obvias (negativas) para las estrategias comerciales reales. Por lo tanto, que lo envuelve para este post. Esencialmente, el mensaje principal aquí es éste: hay una gran diferencia entre la carga que hace el análisis descriptivo (AKA 8220 donde has estado, por qué ocurrieron las cosas8221) vs. el análisis predictivo (es decir 8220 si predigo correctamente el futuro, obtienes un pago positivo8221 ). In my opinion, while descriptive statistics have their purpose in terms of explaining why a strategy may have performed how it did, ultimately, we8217re always looking for better prediction tools. In this case, depmix, at least in this 8220out-of-the-box8221 demonstration does not seem to be the tool for that. If anyone has had success with using depmix (or other regime-switching algorithm in R) for prediction, I would love to see work that details the procedure taken, as it8217s an area I8217m looking to expand my toolbox into, but don8217t have any particular good leads. Essentially, I8217d like to think of this post as me describing my own experiences with the package. Gracias por leer. NOTE: On Oct. 5th, I will be in New York City. On Oct. 6th, I will be presenting at The Trading Show on the Programming Wars panel. NOTE: My current analytics contract is up for review at the end of the year, so I am officially looking for other offers as well. If you have a full-time role which may benefit from the skills you see on my blog, please get in touch with me. My linkedin profile can be found here. This post will introduce component conditional value at risk mechanics found in PerformanceAnalytics from a paper written by Brian Peterson, Kris Boudt, and Peter Carl. This is a mechanism that is an easy-to-call mechanism for computing component expected shortfall in asset returns as they apply to a portfolio. While the exact mechanics are fairly complex, the upside is that the running time is nearly instantaneous, and this method is a solid tool for including in asset allocation analysis. For those interested in an in-depth analysis of the intuition of component conditional value at risk, I refer them to the paper written by Brian Peterson, Peter Carl, and Kris Boudt. Essentially, here8217s the idea: all assets in a given portfolio have a marginal contribution to its total conditional value at risk (also known as expected shortfall)8211that is, the expected loss when the loss surpasses a certain threshold. For instance, if you want to know your 5 expected shortfall, then it8217s the average of the worst 5 returns per 100 days, and so on. For returns using daily resolution, the idea of expected shortfall may sound as though there will never be enough data in a sufficiently fast time frame (on one year or less), the formula for expected shortfall in the PerformanceAnalytics defaults to an approximation calculation using a Cornish-Fisher expansion, which delivers very good results so long as the p-value isn8217t too extreme (that is, it works for relatively sane p values such as the 1-10 range). Component Conditional Value at Risk has two uses: first off, given no input weights, it uses an equal weight default, which allows it to provide a risk estimate for each individual asset without burdening the researcher to create his or her own correlation/covariance heuristics. Secondly, when provided with a set of weights, the output changes to reflect the contribution of various assets in proportion to those weights. This means that this methodology works very nicely with strategies that exclude assets based on momentum, but need a weighting scheme for the remaining assets. Furthermore, using this methodology also allows an ex-post analysis of risk contribution to see which instrument contributed what to risk. First, a demonstration of how the mechanism works using the edhec data set. There is no strategy here, just a demonstration of syntax. This will assume an equal-weight contribution from all of the funds in the edhec data set. So tmp is the contribution to expected shortfall from each of the various edhec managers over the entire time period. Here8217s the output: The salient part of this is the percent contribution (the last output). Notice that it can be negative, meaning that certain funds gain when others lose. At least, this was the case over the current data set. These assets diversify a portfolio and actually lower expected shortfall. In this case, I equally weighted the first ten managers in the edhec data set, and put zero weight in the last three. Furthermore, we can see what happens when the weights are not equal. This time, notice that as the weight increased in the convertible arb manager, so too did his contribution to maximum expected shortfall. For a future backtest, I would like to make some data requests. I would like to use the universe found in Faber8217s Global Asset Allocation book. That said, the simulations in that book go back to 1972, and I was wondering if anyone out there has daily returns for those assets/indices. While some ETFs go back into the early 2000s, there are some that start rather late such as DBC (commodities, early 2006), GLD (gold, early 2004), BWX (foreign bonds, late 2007), and FTY (NAREIT, early 2007). As an eight-year backtest would be a bit short, I was wondering if anyone had data with more history. One other thing, I will in New York for the trading show. and speaking on the 8220programming wars8221 panel on October 6th. Gracias por leer. NOTE: While I am currently contracting, I am also looking for a permanent position which can benefit from my skills for when my current contract ends. If you have or are aware of such an opening, I will be happy to speak with you. This post will cover a function to simplify creating Harry Long type rebalancing strategies from SeekingAlpha for interested readers. As Harry Long has stated, most, if not all of his strategies are more for demonstrative purposes rather than actual recommended investments. So, since Harry Long has been posting some more articles on Seeknig Alpha, I8217ve had a reader or two ask me to analyze his strategies (again). Instead of doing that, however, I8217ll simply put this tool here, which is a wrapper that automates the acquisition of data and simulates portfolio rebalancing with one line of code. Here8217s the tool. It fetches the data for you (usually from Yahoo, but a big thank you to Mr. Helumth Vollmeier in the case of ZIV and VXX), and has the option of either simply displaying an equity curve and some statistics (CAGR, annualized standard dev, Sharpe, max Drawdown, Calmar), or giving you the return stream as an output if you wish to do more analysis in R. Here8217s an example of simply getting the statistics, with an 80 XLP/SPLV (they8217re more or less interchangeable) and 20 TMF (aka 60 TLT, so an 80/60 portfolio), from one of Harry Long8217s articles . Nothing out of the ordinary of what we might expect from a balanced equity/bonds portfolio. Generally does well, has its largest drawdown in the financial crisis, and some other bumps in the road, but overall, I8217d think a fairly vanilla 8220set it and forget it8221 sort of thing. And here would be the way to get the stream of individual daily returns, assuming you wanted to rebalance these two instruments weekly, instead of yearly (as is the default). And now let8217s get some statistics. Turns out, moving the rebalancing from annually to weekly didn8217t have much of an effect here (besides give a bunch of money to your broker, if you factored in transaction costs, which this doesn8217t). So, that8217s how this tool works. The results, of course, begin from the latest instrument8217s inception. The trick, in my opinion, is to try and find proxy substitutes with longer histories for newer ETFs that are simply leveraged ETFs, such as using a 60 weight in TLT with an 80 weight in XLP instead of a 20 weight in TMF with 80 allocation in SPLV. For instance, here are some proxies: SPXL XLP SPXL/UPRO SPY 3 TMF TLT 3 That said, I8217ve worked with Harry Long before, and he develops more sophisticated strategies behind the scenes, so I8217d recommend that SeekingAlpha readers take his publicly released strategies as concept demonstrations, as opposed to fully-fledged investment ideas, and contact Mr. Long himself about more customized, private solutions for investment institutions if you are so interested. Gracias por leer. NOTE: I am currently in the northeast. While I am currently contracting, I am interested in networking with individuals or firms with regards to potential collaboration opportunities. This post will demonstrate how to take into account turnover when dealing with returns-based data using PerformanceAnalytics and the Return. Portfolio function in R. It will demonstrate this on a basic strategy on the nine sector SPDRs. So, first off, this is in response to a question posed by one Robert Wages on the R-SIG-Finance mailing list. While there are many individuals out there with a plethora of questions (many of which can be found to be demonstrated on this blog already), occasionally, there will be an industry veteran, a PhD statistics student from Stanford, or other very intelligent individual that will ask a question on a topic that I haven8217t yet touched on this blog, which will prompt a post to demonstrate another technical aspect found in R. This is one of those times. So, this demonstration will be about computing turnover in returns space using the PerformanceAnalytics package. Simply, outside of the PortfolioAnalytics package, PerformanceAnalytics with its Return. Portfolio function is the go-to R package for portfolio management simulations, as it can take a set of weights, a set of returns, and generate a set of portfolio returns for analysis with the rest of PerformanceAnalytics8217s functions. Again, the strategy is this: take the 9 three-letter sector SPDRs (since there are four-letter ETFs now), and at the end of every month, if the adjusted price is above its 200-day moving average, invest into it. Normalize across all invested sectors (that is, 1/9th if invested into all 9, 100 into 1 if only 1 invested into, 100 cash, denoted with a zero return vector, if no sectors are invested into). It8217s a simple, toy strategy, as the strategy isn8217t the point of the demonstration. Here8217s the basic setup code: So, get the SPDRs, put them together, compute their returns, generate the signal, and create the zero vector, since Return. Portfolio treats weights less than 1 as a withdrawal, and weights above 1 as the addition of more capital (big FYI here). Now, here8217s how to compute turnover: So, the trick is this: when you call Return. portfolio, use the verbose TRUE option. This creates several objects, among them returns, BOP. Weight, and EOP. Weight. These stand for Beginning Of Period Weight, and End Of Period Weight. The way that turnover is computed is simply the difference between how the day8217s return moves the allocated portfolio from its previous ending point to where that portfolio actually stands at the beginning of next period. That is, the end of period weight is the beginning of period drift after taking into account the day8217s drift/return for that asset. The new beginning of period weight is the end of period weight plus any transacting that would have been done. Thus, in order to find the actual transactions (or turnover), one subtracts the previous end of period weight from the beginning of period weight. This is what such transactions look like for this strategy. Something we can do with such data is take a one-year rolling turnover, accomplished with the following code: It looks like this: This essentially means that one year8217s worth of two-way turnover (that is, if selling an entirely invested portfolio is 100 turnover, and buying an entirely new set of assets is another 100, then two-way turnover is 200) is around 800 at maximum. That may be pretty high for some people. Now, here8217s the application when you penalize transaction costs at 20 basis points per percentage point traded (that is, it costs 20 cents to transact 100). So, at 20 basis points on transaction costs, that takes about one percent in returns per year out of this (admittedly, terrible) strategy. This is far from negligible. So, that is how you actually compute turnover and transaction costs. In this case, the transaction cost model was very simple. However, given that Return. portfolio returns transactions at the individual asset level, one could get as complex as they would like with modeling the transaction costs. Gracias por leer. NOTE: I will be giving a lightning talk at R/Finance, so for those attending, you8217ll be able to find me there. This post will outline an easy-to-make mistake in writing vectorized backtests8211namely in using a signal obtained at the end of a period to enter (or exit) a position in that same period. The difference in results one obtains is massive. Today, I saw two separate posts from Alpha Architect and Mike Harris both referencing a paper by Valeriy Zakamulin on the fact that some previous trend-following research by Glabadanidis was done with shoddy results, and that Glabadanidis8217s results were only reproducible through instituting lookahead bias. The following code shows how to reproduce this lookahead bias. First, the setup of a basic moving average strategy on the SampP 500 index from as far back as Yahoo data will provide. And here is how to institute the lookahead bias. These are the 8220results8221: Of course, this equity curve is of no use, so here8217s one in log scale. As can be seen, lookahead bias makes a massive difference. Here are the numerical results: Again, absolutely ridiculous. Note that when using Return. Portfolio (the function in PerformanceAnalytics), that package will automatically give you the next period8217s return, instead of the current one, for your weights. However, for those writing 8220simple8221 backtests that can be quickly done using vectorized operations, an off-by-one error can make all the difference between a backtest in the realm of reasonable, and pure nonsense. However, should one wish to test for said nonsense when faced with impossible-to-replicate results, the mechanics demonstrated above are the way to do it. Now, onto other news: I8217d like to thank Gerald M for staying on top of one of the Logical Invest strategies8211namely, their simple global market rotation strategy outlined in an article from an earlier blog post. Up until March 2015 (the date of the blog post), the strategy had performed well. However, after said date It has been a complete disaster, which, in hindsight, was evident when I passed it through the hypothesis-driven development framework process I wrote about earlier. So, while there has been a great deal written about not simply throwing away a strategy because of short-term underperformance, and that anomalies such as momentum and value exist because of career risk due to said short-term underperformance, it8217s never a good thing when a strategy creates historically large losses, particularly after being published in such a humble corner of the quantitative financial world. In any case, this was a post demonstrating some mechanics, and an update on a strategy I blogged about not too long ago. Gracias por leer. NOTE: I am always interested in hearing about new opportunities which may benefit from my expertise, and am always happy to network. You can find my LinkedIn profile here . This post will shed light on the values of R2s behind two rather simplistic strategies 8212 the simple 10 month SMA, and its relative, the 10 month momentum (which is simply a difference of SMAs, as Alpha Architect showed in their book DIY Financial Advisor . Not too long ago, a friend of mine named Josh asked me a question regarding R2s in finance. He8217s finishing up his PhD in statistics at Stanford, so when people like that ask me questions, I8217d like to answer them. His assertion is that in some instances, models that have less than perfect predictive power (EG R2s of .4, for instance), can still deliver very promising predictions, and that if someone were to have a financial model that was able to explain 40 of the variance of returns, they could happily retire with that model making them very wealthy. Indeed. 4 is a very optimistic outlook (to put it lightly), as this post will show. In order to illustrate this example, I took two 8220staple8221 strategies 8212 buy SPY when its closing monthly price is above its ten month simple moving average, and when its ten month momentum (basically the difference of a ten month moving average and its lag) is positive. While these models are simplistic, they are ubiquitously talked about, and many momentum strategies are an improvement upon these baseline, 8220out-of-the-box8221 strategies. Here8217s the code to do that: And here are the results: In short, the SMA10 and the 10-month momentum (aka ROC 10 aka MOM10) both handily outperform the buy and hold, not only in absolute returns, but especially in risk-adjusted returns (Sharpe and Calmar ratios). Again, simplistic analysis, and many models get much more sophisticated than this, but once again, simple, illustrative example using two strategies that outperform a benchmark (over the long term, anyway). Now, the question is, what was the R2 of these models To answer this, I took a rolling five-year window that essentially asked: how well did these quantities (the ratio between the closing price and the moving average 8211 1, or the ten month momentum) predict the next month8217s returns That is, what proportion of the variance is explained through the monthly returns regressed against the previous month8217s signals in numerical form (perhaps not the best framing, as the signal is binary as opposed to continuous which is what is being regressed, but let8217s set that aside, again, for the sake of illustration). Here8217s the code to generate the answer. And the answer, in pictorial form: In short, even in the best case scenarios, namely, crises which provide momentum/trend-following/call it what you will its raison d8217etre, that is, its risk management appeal, the proportion of variance explained by the actual signal quantities was very small. In the best of times, around 20. But then again, think about what the R2 value actually is8211it8217s the percentage of variance explained by a predictor. If a small set of signals (let alone one) was able to explain the majority of the change in the returns of the SampP 500, or even a not-insignificant portion, such a person would stand to become very wealthy. More to the point, given that two strategies that handily outperform the market have R2s that are exceptionally low for extended periods of time, it goes to show that holding the R2 up as some form of statistical holy grail certainly is incorrect in the general sense, and anyone who does so either is painting with too broad a brush, is creating disingenuous arguments, or should simply attempt to understand another field which may not work the way their intuition tells them. Gracias por leer. This review will review the 8220Adaptive Asset Allocation: Dynamic Global Portfolios to Profit in Good Times 8211 and Bad8221 book by the people at ReSolve Asset Management. Overall, this book is a definite must-read for those who have never been exposed to the ideas within it. However, when it comes to a solution that can be fully replicated, this book is lacking. Okay, it8217s been a while since I reviewed my last book, DIY Financial Advisor. from the awesome people at Alpha Architect. This book in my opinion, is set up in a similar sort of format. This is the structure of the book, and my reviews along with it: Part 1: Why in the heck you actually need to have a diversified portfolio, and why a diversified portfolio is a good thing. In a world in which there is so much emphasis put on single-security performance, this is certainly something that absolutely must be stated for those not familiar with portfolio theory. It highlights the example of two people8211one from Abbott Labs, and one from Enron, who had so much of their savings concentrated in their company8217s stock. Mr. Abbott got hit hard and changed his outlook on how to save for retirement, and Mr. Enron was never heard from again. Long story short: a diversified portfolio is good, and a properly diversified portfolio can offset one asset8217s zigs with another asset8217s zags. This is the key to establishing a stream of returns that will help meet financial goals. Basically, this is your common sense story (humans love being told stories) so as to motivate you to read the rest of the book. It does its job, though for someone like me, it8217s more akin to a big 8220wait for it, wait for it8230and there8217s the reason why we should read on, as expected8221. Part 2: Something not often brought up in many corners of the quant world (because it8217s real life boring stuff) is the importance not only of average returns, but when those returns are achieved. Namely, imagine your everyday saver. At the beginning of their careers, they8217re taking home less salary and have less money in their retirement portfolio (or speculation portfolio, but the book uses retirement portfolio). As they get into middle age and closer to retirement, they have a lot more money in said retirement portfolio. Thus, strong returns are most vital when there is more cash available to the portfolio, and the difference between mediocre returns at the beginning and strong returns at the end of one8217s working life as opposed to vice versa is astronomical and cannot be understated. Furthermore, once in retirement, strong returns in the early years matter far more than returns in the later years once money has been withdrawn out of the portfolio (though I8217d hope that a portfolio8217s returns can be so strong that one can simply 8220live off the interest8221). Or, put more intuitively: when you have 10,000 in your portfolio, a 20 drawdown doesn8217t exactly hurt because you can make more money and put more into your retirement account. But when you8217re 62 and have 500,000 and suddenly lose 30 of everything, well, that8217s massive. How much an investor wants to avoid such a scenario cannot be understated. Warren Buffett once said that if you can8217t bear to lose 50 of everything, you shouldn8217t be in stocks. I really like this part of the book because it shows just how dangerous the ideas of 8220a 50 drawdown is unavoidable8221 and other 8220stay invested for the long haul8221 refrains are. Essentially, this part of the book makes a resounding statement that any financial adviser keeping his or her clients invested in equities when they8217re near retirement age is doing something not very advisable, to put it lightly. In my opinion, those who advise pension funds should especially keep this section of the book in mind, since for some people, the long-term may be coming to an end, and what matters is not only steady returns, but to make sure the strategy doesn8217t fall off a cliff and destroy decades of hard-earned savings. Part 3: This part is also one that is a very important read. First off, it lays out in clear terms that the long-term forward-looking valuations for equities are at rock bottom. That is, the expected forward 15-year returns are very low, using approximately 75 years of evidence. Currently, according to the book, equity valuations imply a negative 15-year forward return. However, one thing I will take issue with is that while forward-looking long-term returns for equities may be very low, if one believed this chart and only invested in the stock market when forecast 15-year returns were above the long term average, one would have missed out on both the 2003-2007 bull runs, and the one since 2009 that8217s just about over. So, while the book makes a strong case for caution, readers should also take the chart with a grain of salt in my opinion. However, another aspect of portfolio construction that this book covers is how to construct a robust (assets for any economic environment) and coherent (asset classes balanced in number) universe for implementation with any asset allocation algorithm. I think this bears repeating: universe selection is an extremely important topic in the discussion of asset allocation, yet there is very little discussion about it. Most research/topics simply take some 8220conventional universe8221, such as 8220all stocks on the NYSE8221, or 8220all the stocks in the SampP 5008221, or 8220the entire set of the 50-60 most liquid futures8221 without consideration for robustness and coherence. This book is the first source I8217ve seen that actually puts this topic under a magnifying glass besides 8220finger in the air pick and choose8221. Part 4: and here8217s where I level my main criticism at this book. For those that have read 8220Adaptive Asset Allocation: A Primer8221. this section of the book is basically one giant copy and paste. It8217s all one large buildup to 8220momentum rank min-variance optimization8221. All well and good, until there8217s very little detail beyond the basics as to how the minimum variance portfolio was constructed. Namely, what exactly is the minimum variance algorithm in use Is it one of the poor variants susceptible to numerical instability inherent in inverting sample covariance matrices Or is it a heuristic like David Varadi8217s minimum variance and minimum correlation algorithm The one feeling I absolutely could not shake was that this book had a perfect opportunity to present a robust approach to minimum variance, and instead, it8217s long on concept, short on details. While the theory of 8220maximize return for unit risk8221 is all well and good, the actual algorithm to implement that theory into practice is not trivial, with the solutions taught to undergrads and master8217s students having some well-known weaknesses. On top of this, one thing that got hammered into my head in the past was that ranking also had a weakness at the inclusion/exclusion point. E. G. if, out of ten assets, the fifth asset had a momentum of say, 10.9, and the sixth asset had a momentum of 10.8, how are we so sure the fifth is so much better And while I realize that this book was ultimately meant to be a primer, in my opinion, it would have been a no-objections five-star if there were an appendix that actually went into some detail on how to go from the simple concepts and included a small numerical example of some algorithms that may address the well-known weaknesses. This doesn8217t mean Greek/mathematical jargon. Just an appendix that acknowledged that not every reader is someone only picking up his first or second book about systematic investing, and that some of us are familiar with the 8220whys8221 and are more interested in the 8220hows8221. Furthermore, I8217d really love to know where the authors of this book got their data to back-date some of these ETFs into the 90s. Part 5: some more formal research on topics already covered in the rest of the book8211namely a section about how many independent bets one can take as the number of assets grow, if I remember it correctly. Long story short You easily get the most bang for your buck among disparate asset classes, such as treasuries of various duration, commodities, developed vs. emerging equities, and so on, as opposed to trying to pick among stocks in the same asset class (though there8217s some potential for alpha there8230just8230a lot less than you imagine). So in case the idea of asset class selection, not stock selection wasn8217t beaten into the reader8217s head before this point, this part should do the trick. The other research paper is something I briefly skimmed over which went into more depth about volatility and retirement portfolios, though I felt that the book covered this topic earlier on to a sufficient degree by building up the intuition using very understandable scenarios. So that8217s the review of the book. Overall, it8217s a very solid piece of writing, and as far as establishing the why, it does an absolutely superb job. For those that aren8217t familiar with the concepts in this book, this is definitely a must-read, and ASAP. However, for those familiar with most of the concepts and looking for a detailed 8220how8221 procedure, this book does not deliver as much as I would have liked. And I realize that while it8217s a bad idea to publish secret sauce, I bought this book in the hope of being exposed to a new algorithm presented in the understandable and intuitive language that the rest of the book was written in, and was left wanting. Still, that by no means diminishes the impact of the rest of the book. For those who are more likely to be its target audience, it8217s a 5/5. For those that wanted some specifics, it still has its gem on universe construction. Overall, I rate it a 4/5. Gracias por leer. Happy new year. This post will be a quick one covering the relationship between the simple moving average and time series momentum. The implication is that one can potentially derive better time series momentum indicators than the classical one applied in so many papers. Okay, so the main idea for this post is quite simple: I8217m sure we8217re all familiar with classical momentum. That is, the price now compared to the price however long ago (3 months, 10 months, 12 months, etc.). E. G. P(now) 8211 P(10) And I8217m sure everyone is familiar with the simple moving average indicator, as well. E. G. SMA(10). Well, as it turns out, these two quantities are actually related. It turns out, if instead of expressing momentum as the difference of two numbers, it is expressed as the sum of returns, it can be written (for a 10 month momentum) as: MOM10 return of this month return of last month return of 2 months ago 8230 return of 9 months ago, for a total of 10 months in our little example. This can be written as MOM10 (P(0) 8211 P(1)) (P(1) 8211 P(2)) 8230 (P(9) 8211 P(10)). (Each difference within parentheses denotes one month8217s worth of returns.) Which can then be rewritten by associative arithmetic as: (P(0) P(1) 8230 P(9)) 8211 (P(1) P(2) 8230 P(10)). In other words, momentum 8212 aka the difference between two prices, can be rewritten as the difference between two cumulative sums of prices. And what is a simple moving average Simply a cumulative sum of prices divided by however many prices summed over. Here8217s some R code to demonstrate. With the resulting number of times these two signals are equal: In short, every time. Now, what exactly is the punchline of this little example Here8217s the punchline: The simple moving average is8230fairly simplistic as far as filters go. It works as a pedagogical example, but it has some well known weaknesses regarding lag, windowing effects, and so on. Here8217s a toy example how one can get a different momentum signal by changing the filter. With the following results: While the difference of EMA10 strategy didn8217t do better than the difference of SMA10 (aka standard 10-month momentum), that8217s not the point. The point is that the momentum signal is derived from a simple moving average filter, and that by using a different filter, one can still use a momentum type of strategy. Or, put differently, the main/general takeaway here is that momentum is the slope of a filter, and one can compute momentum in an infinite number of ways depending on the filter used, and can come up with a myriad of different momentum strategies. Gracias por leer. NOTE: I am currently contracting in Chicago, and am always open to networking. Contact me at my email at ilya. kipnisgmail or find me on my LinkedIn here. This post will outline a first failed attempt at applying the ensemble filter methodology to try and come up with a weighting process on SPY that should theoretically be a gradual process to shift from conviction between a bull market, a bear market, and anywhere in between. This is a follow-up post to this blog post. So, my thinking went like this: in a bull market, as one transitions from responsiveness to smoothness, responsive filters should be higher than smooth filters, and vice versa, as there8217s generally a trade-off between the two. In fact, in my particular formulation, the quantity of the square root of the EMA of squared returns punishes any deviation from a flat line altogether (although inspired by Basel8217s measure of volatility, which is the square root of the 18-day EMA of squared returns), while the responsiveness quantity punishes any deviation from the time series of the realized prices. Whether these are the two best measures of smoothness and responsiveness is a topic I8217d certainly appreciate feedback on. In any case, an idea I had on the top of my head was that in addition to having a way of weighing multiple filters by their responsiveness (deviation from price action) and smoothness (deviation from a flat line), that by taking the sums of the sign of the difference between one filter and its neighbor on the responsiveness to smoothness spectrum, provided enough ensemble filters (say, 101, so there are 100 differences), one would obtain a way to move from full conviction of a bull market, to a bear market, to anything in between, and have this be a smooth process that doesn8217t have schizophrenic swings of conviction. Here8217s the code to do this on SPY from inception to 2003: And here8217s the very underwhelming result: Essentially, while I expected to see changes in conviction of maybe 20 at most, instead, my indicator of sum of sign differences did exactly as I had hoped it wouldn8217t, which is to be a very binary sort of mechanic. My intuition was that between an 8220obvious bull market8221 and an 8220obvious bear market8221 that some differences would be positive, some negative, and that they8217d net each other out, and the conviction would be zero. Furthermore, that while any individual crossover is binary, all one hundred signs being either positive or negative would be a more gradual process. Apparently, this was not the case. To continue this train of thought later, one thing to try would be an all-pairs sign difference. Certainly, I don8217t feel like giving up on this idea at this point, and, as usual, feedback would always be appreciated. Gracias por leer. NOTE: I am currently consulting in an analytics capacity in downtown Chicago. However, I am also looking for collaborators that wish to pursue interesting trading ideas. If you feel my skills may be of help to you, let8217s talk. You can email me at ilya. kipnisgmail, or find me on my LinkedIn here . Post navigation Categories Blogroll
Comments
Post a Comment