Wednesday 26 July 2017

Quantstart Forex


O QSForex é um backtesting orientado a eventos de código aberto e uma plataforma de negociação ao vivo para uso nos mercados de câmbio (forex), atualmente em um estado alfa. Ele foi criado como parte da série Forex Trading Diary em QuantStart para fornecer a comunidade de negociação sistemática com um mecanismo de negociação robusto que permite a implementação direta de estratégia forex e testes. O software é fornecido sob uma licença MIT permissiva (veja abaixo). Open-Source - O QSForex foi lançado sob uma Licença de MIT de código aberto extremamente permissiva, que permite o uso completo em pesquisas e aplicações comerciais, sem restrições, mas sem garantia de qualquer tipo. Free - QSForex é totalmente gratuito e não custa nada para download ou uso. Colaboração - Como o QSForex é de código aberto, muitos desenvolvedores colaboram para melhorar o software. Novos recursos são adicionados com freqüência. Quaisquer erros são rapidamente determinados e corrigidos. Desenvolvimento de Software - QSForex é escrito na linguagem de programação Python para suporte cruzado direto. QSForex contém um conjunto de testes de unidade para a maioria do seu código de cálculo e novos testes são constantemente adicionados para novos recursos. Arquitetura Orientada a Eventos - QSForex é completamente orientada a eventos tanto para backtesting quanto para negociação ao vivo, o que leva à transição direta de estratégias de uma fase de pesquisa / teste para uma implementação de negociação ao vivo. Custos de transação - Os custos de spread são incluídos por padrão para todas as estratégias testadas. Backtesting - O QSForex apresenta backtesting de par multi-moeda de vários dias. Trading - A QSForex atualmente oferece suporte a negociação intraday ao vivo usando a OANDA Brokerage API em um portfólio de pares. Métricas de Desempenho - QSForex atualmente suporta medição de desempenho básico e visualização de equidade através das bibliotecas de visualização Matplotlib e Seaborn. Instalação e Uso 1) Visite oanda / e configure uma conta para obter as credenciais de autenticação da API, que você precisará para realizar a negociação ao vivo. Eu explico como realizar isso neste artigo: Quantstart / artigos / Forex-Trading-Diary-1-Automated-Forex-Trading-com-OANDA-API. 2) Clone este repositório git em um local adequado em sua máquina usando o seguinte comando em seu terminal: git clone github / mhallsmoore / qsforex. git. Alternativa você pode baixar o arquivo zip do ramo mestre atual em github / mhallsmoore / qsforex / archive / master. zip. 3) Crie um conjunto de variáveis ​​de ambiente para todas as configurações encontradas no arquivo settings. py no diretório raiz do aplicativo. Como alternativa, você pode codificar suas configurações específicas, substituindo as chamadas os. environ. get (.) Para cada configuração: 4) Crie um ambiente virtual (virtualenv) para o código QSForex e utilize pip para instalar os requisitos. Por exemplo, em um sistema baseado em Unix (Mac ou Linux), você pode criar um diretório como o seguinte, digitando os seguintes comandos no terminal: Isso criará um novo ambiente virtual para instalar os pacotes em. Supondo que você baixou o repositório gst do QSForex para um diretório de exemplo como / projects / qsforex / (mude este diretório abaixo para onde você instalou o QSForex), então para instalar os pacotes você precisará executar os seguintes comandos: Tempo como NumPy, SciPy, Pandas, Scikit-Learn e Matplotlib devem ser compilados. Há muitos pacotes necessários para que isso funcione, por favor, dê uma olhada nesses dois artigos para obter mais informações: Você também precisará criar um link simbólico do seu diretório de pacotes do site para o diretório de instalação do QSForex para poder chamar Importe qsforex dentro do código. Para fazer isso, você precisará de um comando semelhante ao seguinte: Certifique-se de alterar / projects / qsforex para o diretório de instalação e /venv/qsforex/lib/python2.7/site-packages/ para o diretório de pacotes do site virtualenv. Agora você poderá executar os comandos subseqüentes corretamente. 5) Nesta fase, se você simplesmente deseja realizar prática ou negociação ao vivo, então você pode executar python trading / trade. py. Que utilizará a estratégia de negociação padrão do TestStrategy. Isso simplesmente compra ou vende um par de moedas a cada 5 tick. É puramente para testes - não usá-lo em um ambiente de negociação ao vivo Se você deseja criar uma estratégia mais útil, basta criar uma nova classe com um nome descritivo, p. MeanReversionMultiPairStrategy e verifique se ele tem um método calculatesignals. Você precisará passar esta classe a lista de pares, bem como a fila de eventos, como em trading / trading. py. Consulte estratégia / estratégia. py para obter detalhes. 6) A fim de realizar qualquer backtesting é necessário para gerar dados forex simulados ou download histórico tiquetaquear dados. Se você quiser simplesmente tentar o software para fora, a maneira mais rápida de gerar um exemplo backtest é gerar alguns dados simulados. O formato de dados atual usado pelo QSForex é o mesmo que o fornecido pelo DukasCopy Historical Data Feed em dukascopy / swiss / english / marketwatch / historical /. Para gerar alguns dados históricos, certifique-se de que a configuração CSVDATADIR em settings. py seja definida para um diretório no qual você deseja que os dados históricos sejam transmitidos. Em seguida, você precisa executar generatesimulatedpair. py. Que está sob o diretório scripts /. Ele espera um único argumento de linha de comando, que neste caso é o par de moedas no formato BBBQQQ. Por exemplo: Neste estágio, o script é codificado para criar um único mês de dados para janeiro de 2014. Ou seja, você verá arquivos individuais, do formato BBBQQQYYYYMMDD. csv (por exemplo, GBPUSD20140112.csv) aparecem no seu CSVDATADIR para todos os dias úteis em Esse mês. Se você deseja alterar o mês / ano da saída de dados, basta modificar o arquivo e voltar a executar. 7) Agora que os dados históricos foram gerados, é possível realizar um backtest. O próprio arquivo backtest é armazenado em backtest / backtest. py. Mas isso só contém a classe Backtest. Para realmente executar um backtest você precisa instanciar essa classe e fornecer os módulos necessários. A melhor maneira de ver como isso é feito é observar a implementação do Crossover de Moving Average no arquivo examples / mac. py e usá-lo como um modelo. Isso faz uso do MovingAverageCrossStrategy que é encontrado em strategy / strategy. py. Isso padrão para negociação tanto GBP / USD e EUR / USD para demonstrar o uso de par de moedas múltiplas. Ele usa os dados encontrados no CSVDATADIR. Para executar o exemplo backtest, basta executar o seguinte: Isso levará algum tempo. No meu sistema de desktop Ubuntu em casa, com os dados históricos gerados via generatesimulatedpair. py. Leva cerca de 5-10 minutos para ser executado. Uma grande parte deste cálculo ocorre no final do backtest real, quando o levantamento está sendo calculado, por favor, lembre-se que o código não desligou Por favor, deixe-o até a conclusão. 8) Se você quiser ver o desempenho do backtest você pode simplesmente usar output. py para ver uma curva de equidade, retornos de período (ou seja, retornos de tick-to-tick) e uma curva de redução: E thats it Nesta fase você está pronto Para começar a criar seus próprios backtests modificando ou anexando estratégias em strategy / strategy. py e usando dados reais baixados do DukasCopy (dukascopy / swiss / english / marketwatch / historical /). Se você tiver alguma dúvida sobre a instalação, então sinta-se livre para me enviar um e-mail no mikequantstart. Se você tiver quaisquer bugs ou outros problemas que você acha que podem ser devido à codebase especificamente, sinta-se livre para abrir uma questão Github aqui: github / mhallsmoore / qsforex / issues Copyright (c) 2015 Michael Halls-Moore A qualquer pessoa que obtenha uma cópia deste software e arquivos de documentação associados (o Software), para negociar o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar, modificar, fundir, publicar, distribuir, sublicenciar e / Ou vender cópias do Software e permitir que as pessoas a quem o Software é fornecido o façam, sujeito às seguintes condições: O aviso de copyright acima e este aviso de permissão devem ser incluídos em todas as cópias ou partes substanciais do Software. O SOFTWARE É FORNECIDO TAL COMO É, SEM GARANTIA DE QUALQUER TIPO, EXPRESSA OU IMPLÍCITA, INCLUINDO, MAS NÃO SE LIMITANDO ÀS GARANTIAS DE COMERCIALIZAÇÃO, ADEQUAÇÃO A UM FIM ESPECÍFICO E NÃO-INFRAÇÃO. EM NENHUMA CIRCUNSTÂNCIA OS AUTORES OU TITULARES DE DIREITOS AUTORAIS SERÃO RESPONSÁVEIS POR QUALQUER RECLAMAÇÃO, DANOS OU OUTRA RESPONSABILIDADE, SEJA EM UMA ACÇÃO DE CONTRATO, DANO ILÍCITO OU DE OUTRA FORMA, DECORRENTE DE, OU DE CONEXÃO COM O SOFTWARE OU O USO OU OUTROS NEGOCIADOS NO PROGRAMAS. Negação de Negociação de Forex Trocando o câmbio na margem carrega um nível elevado do risco, e não pode ser apropriado para todos os investors. O desempenho passado não é indicativo de resultados futuros. O alto grau de alavancagem pode trabalhar contra você, bem como para você. Antes de decidir investir em divisas você deve considerar cuidadosamente seus objetivos de investimento, nível de experiência e apetite pelo risco. A possibilidade existe que você poderia sustentar uma perda de alguns ou todos do seu investimento inicial e, portanto, você não deve investir o dinheiro que você não pode dar ao luxo de perder. Você deve estar ciente de todos os riscos associados com negociação de câmbio, e procurar aconselhamento de um conselheiro financeiro independente, se você tiver qualquer dúvida. QSForex é um open-source backtesting evento-driven e plataforma de negociação ao vivo para uso no câmbio ), Atualmente em um estado alfa. Ele foi criado como parte da série Forex Trading Diary em QuantStart para fornecer a comunidade comercial sistemática com um mecanismo de negociação robusto que permite a implementação direta de estratégia forex e testes. O software é fornecido sob uma licença MIT permissiva (veja abaixo). Open-Source - O QSForex foi lançado sob uma Licença de MIT de código aberto extremamente permissiva, que permite o uso completo em pesquisas e aplicações comerciais, sem restrições, mas sem garantia de qualquer tipo. Free - QSForex é totalmente gratuito e não custa nada para download ou uso. Colaboração - Como o QSForex é de código aberto, muitos desenvolvedores colaboram para melhorar o software. Novos recursos são adicionados com freqüência. Quaisquer erros são rapidamente determinados e corrigidos. Desenvolvimento de Software - QSForex é escrito na linguagem de programação Python para suporte cruzado direto. QSForex contém um conjunto de testes de unidade para a maioria do seu código de cálculo e novos testes são constantemente adicionados para novos recursos. Arquitetura Orientada a Eventos - QSForex é completamente orientada a eventos tanto para backtesting quanto para negociação ao vivo, o que leva à transição direta de estratégias de uma fase de pesquisa / teste para uma implementação de trading ao vivo. Custos de transação - Os custos de spread são incluídos por padrão para todas as estratégias testadas. Backtesting - O QSForex apresenta backtesting de par multi-moeda de vários dias. Trading - A QSForex atualmente oferece suporte a negociação intraday ao vivo usando a OANDA Brokerage API em um portfólio de pares. Métricas de Desempenho - QSForex atualmente suporta medição de desempenho básico e visualização de equidade através das bibliotecas de visualização Matplotlib e Seaborn. Instalação e Uso 1) Visite oanda / e configure uma conta para obter as credenciais de autenticação da API, que você precisará para realizar a negociação ao vivo. Eu explico como realizar isso neste artigo: Quantstart / artigos / Forex-Trading-Diary-1-Automated-Forex-Trading-com-OANDA-API. 2) Clone este repositório git em um local adequado em sua máquina usando o seguinte comando em seu terminal: git clone github / mhallsmoore / qsforex. git. Alternativa você pode baixar o arquivo zip do ramo mestre atual em github / mhallsmoore / qsforex / archive / master. zip. 3) Crie um conjunto de variáveis ​​de ambiente para todas as configurações encontradas no arquivo settings. py no diretório raiz do aplicativo. Como alternativa, você pode codificar suas configurações específicas, substituindo as chamadas os. environ. get (.) Para cada configuração: 4) Crie um ambiente virtual (virtualenv) para o código QSForex e utilize pip para instalar os requisitos. Por exemplo, em um sistema baseado em Unix (Mac ou Linux), você pode criar um diretório como o seguinte, digitando os seguintes comandos no terminal: Isso criará um novo ambiente virtual para instalar os pacotes em. Supondo que você baixou o repositório gist QSForex para um diretório de exemplo como / projects / qsforex / (mude este diretório abaixo para onde você instalou QSForex), então para instalar os pacotes você precisará executar os seguintes comandos: Tempo como NumPy, SciPy, Pandas, Scikit-Learn e Matplotlib devem ser compilados. Há muitos pacotes necessários para que isso funcione, por favor, dê uma olhada nesses dois artigos para obter mais informações: Você também precisará criar um link simbólico do seu diretório de pacotes do site para o diretório de instalação do QSForex para poder chamar Importe qsforex dentro do código. Para fazer isso, você precisará de um comando semelhante ao seguinte: Certifique-se de alterar / projects / qsforex para o diretório de instalação e /venv/qsforex/lib/python2.7/site-packages/ para o diretório de pacotes do site virtualenv. Agora você poderá executar os comandos subseqüentes corretamente. 5) Nesta fase, se você simplesmente deseja realizar prática ou negociação ao vivo, então você pode executar python trading / trade. py. Que utilizará a estratégia de negociação padrão do TestStrategy. Isso simplesmente compra ou vende um par de moedas a cada 5º tick. É puramente para testes - não usá-lo em um ambiente de negociação ao vivo Se você deseja criar uma estratégia mais útil, basta criar uma nova classe com um nome descritivo, p. MeanReversionMultiPairStrategy e verifique se ele tem um método calculatesignals. Você precisará passar esta classe a lista de pares, bem como a fila de eventos, como em trading / trading. py. Consulte estratégia / estratégia. py para obter detalhes. 6) A fim de realizar qualquer backtesting é necessário para gerar dados forex simulados ou download histórico tiquetaquear dados. Se você quiser simplesmente tentar o software para fora, a maneira mais rápida de gerar um exemplo backtest é gerar alguns dados simulados. O formato de dados atual usado pelo QSForex é o mesmo que o fornecido pelo DukasCopy Historical Data Feed em dukascopy / swiss / english / marketwatch / historical /. Para gerar alguns dados históricos, certifique-se de que a configuração CSVDATADIR em settings. py seja definida para um diretório no qual você deseja que os dados históricos sejam transmitidos. Em seguida, você precisa executar generatesimulatedpair. py. Que está sob o diretório scripts /. Ele espera um único argumento de linha de comando, que neste caso é o par de moedas no formato BBBQQQ. Por exemplo: Neste estágio, o script é codificado para criar um único mês de dados para janeiro de 2014. Ou seja, você verá arquivos individuais, do formato BBBQQQYYYYMMDD. csv (por exemplo, GBPUSD20140112.csv) aparecem no seu CSVDATADIR para todos os dias úteis em Esse mês. Se você deseja alterar o mês / ano da saída de dados, basta modificar o arquivo e voltar a executar. 7) Agora que os dados históricos foram gerados, é possível realizar um backtest. O próprio arquivo backtest é armazenado em backtest / backtest. py. Mas isso só contém a classe Backtest. Para realmente executar um backtest você precisa instanciar essa classe e fornecer os módulos necessários. A melhor maneira de ver como isso é feito é observar a implementação do Crossover de Moving Average no arquivo examples / mac. py e usá-lo como um modelo. Isso faz uso do MovingAverageCrossStrategy que é encontrado em strategy / strategy. py. Isso padrão para negociação tanto GBP / USD e EUR / USD para demonstrar o uso de par de moedas múltiplas. Ele usa os dados encontrados no CSVDATADIR. Para executar o exemplo backtest, basta executar o seguinte: Isso levará algum tempo. No meu sistema de desktop Ubuntu em casa, com os dados históricos gerados via generatesimulatedpair. py. Leva cerca de 5-10 minutos para ser executado. Uma grande parte deste cálculo ocorre no final do backtest real, quando o levantamento está sendo calculado, por favor, lembre-se que o código não desligou Por favor, deixe-o até a conclusão. 8) Se você quiser ver o desempenho do backtest você pode simplesmente usar output. py para ver uma curva de equidade, retornos de período (ou seja, retornos de tick-to-tick) e uma curva de redução: E thats it Nesta fase você está pronto Para começar a criar seus próprios backtests modificando ou anexando estratégias em strategy / strategy. py e usando dados reais baixados do DukasCopy (dukascopy / swiss / english / marketwatch / historical /). Se você tiver alguma dúvida sobre a instalação, então sinta-se livre para me enviar um e-mail no mikequantstart. Se você tiver quaisquer bugs ou outros problemas que você acha que podem ser devido à codebase especificamente, sinta-se livre para abrir uma questão Github aqui: github / mhallsmoore / qsforex / issues Copyright (c) 2015 Michael Halls-Moore A qualquer pessoa que obtenha uma cópia deste software e arquivos de documentação associados (o Software), para negociar o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar, modificar, fundir, publicar, distribuir, sublicenciar e / Ou vender cópias do Software e permitir que as pessoas a quem o Software é fornecido o façam, sujeito às seguintes condições: O aviso de copyright acima e este aviso de permissão devem ser incluídos em todas as cópias ou partes substanciais do Software. O SOFTWARE É FORNECIDO TAL COMO É, SEM GARANTIA DE QUALQUER TIPO, EXPRESSA OU IMPLÍCITA, INCLUINDO, MAS NÃO SE LIMITANDO ÀS GARANTIAS DE COMERCIALIZAÇÃO, ADEQUAÇÃO A UM FIM ESPECÍFICO E NÃO-INFRAÇÃO. EM NENHUMA CIRCUNSTÂNCIA OS AUTORES OU TITULARES DE DIREITOS AUTORAIS SERÃO RESPONSÁVEIS POR QUALQUER RECLAMAÇÃO, DANOS OU OUTRA RESPONSABILIDADE, SEJA EM UMA ACÇÃO DE CONTRATO, DANO ILÍCITO OU DE OUTRA FORMA, DECORRENTE DE, EM RELAÇÃO AO SOFTWARE OU AO USO OU OUTROS NEGÓCIOS NA PROGRAMAS. Negação de Negociação de Forex Trocando o câmbio na margem carrega um nível elevado do risco, e não pode ser apropriado para todos os investors. O desempenho passado não é indicativo de resultados futuros. O alto grau de alavancagem pode trabalhar contra você, bem como para você. Antes de decidir investir em divisas você deve considerar cuidadosamente seus objetivos de investimento, nível de experiência e apetite pelo risco. A possibilidade existe que você poderia sustentar uma perda de alguns ou todos do seu investimento inicial e, portanto, você não deve investir o dinheiro que você não pode dar ao luxo de perder. Você deve estar ciente de todos os riscos associados com negociação de câmbio, e procurar aconselhamento de um conselheiro financeiro independente, se você tiver quaisquer dúvidas. Este post será uma revisão aprofundada do Alpha Architect8217s quantitativa Momentum livro. Em geral, na minha opinião, o livro é fantástico para aqueles que são praticantes de gestão de fundos no espaço de capital individual, e ainda contém idéias vale a pena pensar fora desse espaço. No entanto, o sistema detalhado no livro se beneficia do ranking aninhado (classificação ao longo do eixo X, pegue o decil superior, posicione ao longo do eixo Y dentro do decil superior em X e pegue o decil superior ao longo do eixo Y, restringindo a seleção a 1 do universo). Além disso, o livro não faz muito para tocar em controles de volatilidade, o que pode ter melhorado o sistema descrito muito. Antes que eu comece no peso deste borne, I8217d gostaria de deixar meus leitores saber que eu formalize minhas porcas e parafusos da série quantstrat dos bornes como um curso formal do datacamp. Datacamp é uma maneira muito barata de aprender um monte de R, e aplicações financeiras estão entre esses tópicos. Meu curso cobre os fundamentos do quantstrat, e se aqueles que concluírem o curso como ele, eu posso muito bem criar módulos quantstrat mais avançados no datacamp. Espero que os cursos de finanças sejam bem recebidos, uma vez que há tópicos financeiros em R I8217d gostaria de aprender-me que uma palestra de 45 minutos realmente não é suficiente para (como Dr. David Matteson8217s pontos de mudança de magia, PortfolioAnalytics e assim por diante). Em qualquer caso, aqui está o link. Assim, vamos começar com um resumo do livro: Parte 1 é vários capítulos que são a exposição gigante de por que dinâmica funciona (ou pelo menos, tem trabalhado por pelo menos 20 anos desde 1993), ou seja, que os vieses humanos e comportamentos irracionais agem em Certas maneiras de fazer a anomalia funcionar. Então, também o risco de carreira (AKA é um fator de risco, e assim, se o seu benchmark é SPY e você atravessa um período de 3 anos de desempenho inferior, você tem grave risco de carreira), e essencialmente, uma ladainha inteira de por que um activo profissional Gerente seria demitido, mas se você só ficar com a anomalia ao longo de muitos anos e montar multi-year trechos de underperformance relativo, you8217ll sair à frente no muito longo prazo. Geralmente, sinto-me como se houvesse trabalho a ser feito se este é o melhor que pode ser feito, mas tudo bem, I8217ll aceitá-lo. Essencialmente, a parte 1 é para os não iniciados. Para aqueles que estiveram em torno do bloco do impulso um par das épocas, podem saltar para a direita após este. Infelizmente, é metade do livro, de modo que deixa um pouco de sabor amargo na boca. Em seguida, parte dois é onde, na minha opinião, a verdadeira carne e batatas do livro do 8220how8221. Essencialmente, o algoritmo pode ser reduzido para o seguinte: Tomando o universo de grandes e mid-cap estoques, faça o seguinte: 1) Classificar os estoques em deciles por 2-12 momentum8211 que é, no final de cada mês, calcular momento Pelo último preço de fechamento de month8217s menos o preço de fechamento 12 meses atrás. Essencialmente, a pesquisa afirma que há um efeito de reversão no impulso de 1 mês. No entanto, esse efeito não se transporta para o universo ETF na minha experiência. 2) Aqui está a parte interessante que faz com que o livro valha a pena pegar sozinho (na minha opinião): depois de classificar em deciles, classifique o decil superior pela seguinte métrica: multiplique o sinal do momento 2-12 pela seguinte equação: (Retornos negativos 8211 positivos). Essencialmente, a idéia aqui é determinar a suavidade do momento. Ou seja, na situação mais extrema, imagine uma ação que não fez absolutamente nada por 230 dias e, em seguida, teve um dia maciço que lhe deu toda a sua valorização do preço (acho que o Google, quando teve um pular 10 de números melhores do que o esperado Relatórios), e no outro extremo, um estoque que simplesmente tinha cada dia único ser uma pequena valorização positiva do preço. Obviamente, você quer o segundo tipo de estoque. É essa a idéia. Novamente, classifique em deciles e pegue o decil superior. Portanto, tomar o decil superior do decile superior deixa você com 1 do universo. Essencialmente, isso torna a idéia muito difícil de replicar, uma vez que você precisa rastrear um enorme universo de ações. Que declarou, eu acho que a expressão é realmente uma idéia muito boa como um stand-in para a volatilidade. Ou seja, independentemente de quão volátil um ativo é 827ser tão volátil como uma mercadoria como DBC, ou como não-volátil como um produto de renda fixa como SHY, esta expressão é uma maneira interessante de afirmar que este caminho é choppy8221 vs. 8220este caminho é Smooth8221. Eu poderia investigar esta expressão em meu blog mais no futuro. 3) Por último, se a carteira está se voltando trimestral em vez de mensal, os melhores meses para transformá-lo são os meses anteriores ao final do trimestre mês (ou seja, fevereiro, maio, agosto, novembro) porque um monte de ativos amadores Os gerentes gostam de vestir suas carteiras. Ou seja, eles tiveram um trimestre difícil, então no último mês antes de eles terem que enviar declarações trimestrais, eles se encarregam de alguns ganhadores recentes para que seus clientes não achem que eles são tão amadores como eles realmente deixaram, e há um bump para esta. Similarmente, janeiro tem algumas anomalias vendendo devido à colheita de imposto-perda. Na medida em implementações práticas ir, eu acho que este é um toque muito agradável. Conceder o fato de que virar todos os meses pode ser um pouco caro demais, eu gosto que Wes e Jack dizem 8220sure, você quer transformá-lo uma vez a cada três meses, mas em que months8221. É uma pergunta muito boa para perguntar se isso significa que você ganha um ponto percentual adicional ou 150 bps por ano a partir de que, como ele só pode cobrir os custos de transação e, em seguida, alguns. Em suma, é uma estratégia bastante simples de entender. No entanto, a parte que tipo de portas fora do livro para uma replicação perfeita é a dificuldade em obter os dados CRSP. No entanto, eu recomendo o Alpha Architect por divulgar todo o algoritmo do início ao fim. Além disso, se o impulso básico 2-12 não é suficiente, há um apêndice que detalha outros tipos de ideias de momentum (ganhos momentum, classificação pela distância até 52 semanas de alta, momento histórico absoluto, e assim por diante). Nenhuma dessas estratégias é realmente muito melhor do que a estratégia de preço básico, então eles estão lá para os interessados, mas parece que não há nada realmente inovador lá. Ou seja, se você está negociando uma vez por mês, há apenas tantas maneiras de dizer, eu acho que essa coisa está indo para cima. Eu também gosto que Wes e Jack toquem o fato de que a tendência de acompanhamento, embora não melhore a CAGR ou Sharpe , Faz uma quantidade maciça para melhorar no drawdown máximo. Ou seja, se confrontado com a perspectiva de perder 70-80 de tudo, e perder apenas 30, que8217s uma escolha fácil de fazer. Trend-seguindo é bom, até mesmo uma versão simplista. Em suma, acho que o livro realiza o que se propõe a fazer, que é apresentar um algoritmo bem pesquisado. Em última análise, o punchline está no site Alpha Architect8217s (eu acredito que eles têm algum tipo de filtro estoque mensal). Além disso, o livro afirma que há melhores retornos ajustados ao risco quando combinados com o algoritmo delineado no livro valor quantitativo 8222. Na minha experiência, nunca tive algoritmos de valor impressionar-me nos backtests feito, mas eu posso giz que até mim ser inexperiente com todas as métricas de avaliação diferentes. Minha crítica do livro, entretanto, é esta: O algoritmo do momentum no livro falta o que eu sinto é um componente chave: volatilidade que alveja o controle. Simplificando, o papel 8220momento tem seus momentos8221 (que eu incluí na minha série de postos de desenvolvimento orientada para a hipótese), afirma que a estratégia usual de dinâmica Fama-francesa é muito melhor de uma estratégia de risco-recompensa por desalavancagem em períodos de volatilidade excessiva e Evitando falhas de momento. Não sei por que Wes e Jack não tocaram neste artigo, uma vez que a implementação é muito simples (fator de alavancagem de volatilidade alvo / realizado). Idealmente, eu adoraria se Wes ou Jack pudessem me enviar o fluxo de retornos para esta estratégia (preferencialmente diariamente, mas mensalmente também funciona). Essencialmente, eu acho que este livro é muito abrangente. No entanto, eu acho que também tem um pouco de experimentar isso em home8221 sentir a ele, devido à exigência de dados para replicá-lo. Certamente, se o seu corretor lhe cobrar uma transação, não é uma estratégia viável deixar cair vários milhares de dólares por ano nos custos de transação, apenas dar seus retornos ao seu corretor. No entanto, eu me pergunto se o QMOM ETF (do Alpha Architect, é claro) é, de fato, uma versão melhor dessa estratégia, fora da taxa de gerenciamento. Em todo caso, a minha opinião final é esta: enquanto este livro deixa um pouco de conhecimento sobre a mesa, em um todo, ele realiza o que se propõe a fazer, é claro com seus procedimentos e fornece várias idéias valiosas. Para o preço de um livro não-técnico (aka esses 60 livros sobre amazon), este livro é um roubo. Obrigado pela leitura. NOTA: Enquanto estou atualmente empregado em uma capacidade de análise bem-sucedida, estou interessado em ouvir sobre posições em tempo integral mais estreitamente relacionadas com os tópicos neste blog. Se você tem uma posição em tempo integral que pode se beneficiar de minhas habilidades atuais, por favor me avise. Meu Linkedin pode ser encontrado aqui. Esta postagem será sobre a tentativa de usar o pacote Depmix para previsão de estado on-line. Enquanto o pacote depmix executa admiravelmente quando se trata de descrever os estados do passado, quando usado para a previsão one-step-ahead, sob a suposição de que tomorrow8217s estado será idêntico a today8217s, o processo oculto markov modelo encontrado dentro do pacote não Desempenho às expectativas. Assim, para começar, este post foi motivado por Michael Halls-Moore, que recentemente postou algum código R sobre o uso da biblioteca depmixS4 para usar modelos de markov ocultos. Geralmente, eu sou repugnante criar posts sobre tópicos que eu não sinto que tenho uma compreensão absolutamente de frente para trás, mas estou fazendo isso com a esperança de aprender com outros sobre como fazer apropriadamente a previsão de espaço em estado on-line, ou 8220regime switching8221 Detecção, como pode ser chamado em linguagem mais financeira. Embora eu tenha visto a teoria usual de modelos de markov ocultos (ou seja, pode chover ou pode ser ensolarado, mas você só pode inferir o tempo a julgar pelas roupas que você vê pessoas vestindo fora de sua janela quando você acorda) e têm trabalhado Com exemplos de brinquedo em MOOCs (Udacity8217s curso de carro de auto-condução lida com eles, se bem me lembro corretamente8211ou talvez foi o curso de AI), no final do dia, a teoria é tão boa como o quão bem uma implementação pode trabalhar em dados reais . Para esta experiência, eu decidi tomar os dados do SPY desde o início, e fazer um full in-sample 8220backtest8221 nos dados. Ou seja, dado que o algoritmo HMM de depmix vê todo o histórico de retornos, com esta visão dos dados, o algoritmo classifica corretamente os regimes, se os resultados de backtest são qualquer indicação de que o código para fazê-lo, inspirado por Dr. Halls-Moore8217s. Essencialmente, enquanto eu selecionava três estados, eu observei que qualquer coisa com uma intercepção acima de zero é um estado de touro, e abaixo de zero é um estado de urso, então essencialmente, ele se reduz a dois estados. Com o resultado: Então, não particularmente terrível. O algoritmo funciona, tipo de, tipo de direito Bem, let8217s tentar online previsão agora. Então o que eu fiz aqui foi eu peguei uma janela de expansão, a partir de 500 dias desde o início do SPY8217s, e continuou aumentando, por um dia de cada vez. Minha previsão, foi, trivialmente o suficiente, o dia mais recente, usando um 1 para um touro estado, e -1 para um urso estado. Eu executei este processo em paralelo (em um cluster linux, porque a biblioteca doParallel do windows8217s parece nem saber que certos pacotes são carregados e it8217s mais confuso), eo primeiro grande problema é que este processo levou cerca de três horas em sete núcleos para Cerca de 23 anos de dados. Não é exatamente encorajador, mas o tempo de computação não é caro hoje em dia. Então vamos ver se esse processo realmente funciona. Primeiro, vamos testar se o algoritmo faz o que realmente deveria fazer e usar um dia de viés prospectivo (isto é, o algoritmo nos diz o estado no final do dia), como correto é mesmo para aquele dia. Com o resultado: Então, supostamente, o algoritmo parece fazer o que foi projetado para fazer, que é classificar um estado para um determinado conjunto de dados. Agora, a pergunta mais pertinente: o quão bem fazem essas previsões, mesmo um dia à frente Você pensa que as previsões do espaço de estado seriam parcimoniosas de dia para dia, dada a longa história, correta Com o resultado: Ou seja, sem o viés de olhar para a frente, Estado algoritmo de previsão de espaço é atroz. Por que é que bem, aqui é o enredo dos estados: Em suma, o algoritmo hmm online no pacote depmix parece mudar sua mente muito facilmente, com óbvias implicações (negativas) para estratégias de negociação real. Então, que envolve-lo para este post. Essencialmente, a principal mensagem aqui é a seguinte: existe uma vasta diferença entre o carregamento da análise descritiva (AKA 8220, onde você esteve, por que as coisas aconteceram) versus a análise preditiva (isto é, se eu prevejo corretamente o futuro, recebo um pagamento 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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. Obrigado pela leitura. 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

No comments:

Post a Comment