O Ivy Portfolio Allocation System.
A maioria dos sistemas de negociação sobre os quais escrevi tem sido muito semelhantes. Cada um dos seguintes sistemas tentam capturar grandes pedaços de tendências de maneiras semelhantes. Os sistemas de reversão à média que analisei oferecem maneiras ligeiramente diferentes de executar a mesma estratégia básica de reversão à média. Embora cada um desses sistemas ofereça diferenças sutis em sua abordagem, a estratégia geral é geralmente bastante semelhante.
De todos os sistemas que eu olhei, o maior valor atípico foi o Best10 Portfolio Management System, de George Vrba. Este sistema não estava focado na tendência ou na reversão à média. Estava simplesmente tentando melhorar a abordagem de comprar e manter o mercado em geral. Porque era tão diferente, esse sistema ficou no fundo da minha mente como algo que eu adoraria explorar mais.
Em minha pesquisa e redação, geralmente me concentro em sistemas muito simples. A razão para isso é que, se um sistema é simples o suficiente para que minha mãe possa entender a lógica por trás dele, isso pode convencê-la a mudar de sua atual estratégia de compra e esperança. Acredito que exista um imenso mercado de investidores, como minha mãe, que não tem vontade de negociar para ganhar a vida, mas adoraria ter uma maneira simples de bater o mercado em geral.
O portfólio Ivy.
Em dezembro passado, Jeff Swanson, da System Trader Success, escreveu sobre o The Ivy Portfolio, que é semelhante ao Bestr System da Vrba. O trabalho de Swanson foi baseado em um livro escrito por Mebane Faber e Eric Richardson, que estudou como as escolas da Ivy League são capazes de obter retornos constantes e significativos em seus fundos de dotação. Usando o que aprendeu com o livro, Swanson construiu um sistema similar que tentaria replicar como essas escolas estão negociando.
O conceito do sistema Swanson é notavelmente simples. Ele está aceitando uma cesta de 5 ou 10 ETFs que representam uma ampla seção transversal do mercado e investem naqueles com maior força relativa. Ele formou um algoritmo simples para calcular a força relativa de cada ETF e depois investe nos três principais ETFs. Ele então calcula a força relativa e ajusta o portfólio a cada mês. Ele também usa a média móvel simples de 100 dias (SMA) como um filtro de tendência para se certificar de que ele está sempre negociando com a tendência.
O primeiro passo do sistema é classificar cada um dos ETFs em termos de força relativa. Swanson faz isso calculando o retorno de 20 dias e o retorno de três meses. Isso dá perspectivas de curto e longo prazo em cada um dos ETFs. Ele então pondera cada um dos retornos como metade da classificação geral. Aqui está como sua fórmula se parece:
Classificação geral = (Retorno de 20 dias * 0,5) + (Retorno de 3 meses * 0,5)
A cada mês, a Swanson realiza esse cálculo em cada um dos ETFs negociados pelo seu sistema e, em seguida, exclui quaisquer ETFs que estejam negociando abaixo de seu SMA de 100 dias. Ele então ajusta suas posições vendendo qualquer participação que não esteja nas três primeiras posições. Ele então estabelece uma posição em cada um dos três principais ETFs, desde que ele não tenha uma posição neles. Cada posição representa 1/3 do patrimônio da conta.
Swanson propõe duas versões diferentes deste sistema. Seu sistema Ivy Five comercializa os seguintes ETFs:
BND & # 8211; Vanguard Total Bond Market DBC & # 8211; Powershares DB Commodity Index VEU & # 8211; Vanguard FTSE All-World ex-EUA VNQ & # 8211; Vanguard MSCI US REIT VTI & # 8211; Vanguard MSCI Total nos EUA.
Ele também propôs uma versão maior deste sistema que negocia esses dez ETFs:
BND & # 8211; Vanguard Total Bond Market DBC & # 8211; PowerShares DB Commodity Index GSG & # 8211; Confiança indexada em commodities iShares S & P RWX & # 8211; SPDR DJ International Imóveis TIP & # 8211; iShares Barclays DICAS VB & # 8211; Vanguard MSCI EUA Small Cap VEU & # 8211; Vanguard FTSE All World ex-EUA VNQ & # 8211; Vanguard MSCI US REIT VTI & # 8211; Vanguard MSCI Total nos mercados de ações VWO & # 8211; Vanguard MSCI Emerging Markets.
Resultados de backtesting.
A Swanson conseguiu fazer back back de ambos os sistemas de meados de 2003 até o final de 2010. Durante esse período, ambas as versões superaram o S & amp; P 500 em uma quantidade substancial com rebaixamentos menores. Ser capaz de diversificar as ações e até mesmo ficar completamente fora do mercado às vezes deu a esses sistemas uma tremenda vantagem quando o S & P 500 caiu em 2008.
No decorrer do período de backtesting, a versão de cinco ETF teve um retorno anual médio de 11,8% comparado a apenas 7% para o S & P 500. O sistema teve um rebaixamento máximo de 21,3% comparado a 55,2% no S & amp; P 500. Ele também tinha um índice de Sharpe de 0,72 comparado a 0,29 no S & P 500. Como você pode ver, o Ivy Five System superou significativamente uma abordagem de compra e manutenção com menos da metade do rebaixamento.
Como tinha mais opções de diversificação, o sistema Ivy Ten teve um desempenho ainda melhor no mesmo período de tempo. Ele obteve uma rentabilidade anual média de 14,7%, um rebaixamento máximo de -28,7% e um Índice de Sharpe de 0,82. Embora o rebaixamento fosse um pouco mais alto do que o Ivy Five System, ele ainda era bem menor que o S & P 500, e o retorno geral foi melhor do que o do Ivy Five System.
Análise de sistema.
Os retornos produzidos pela Ivy Systems não são tão espetaculares quanto os retornos da Best10, mas eu diria que os sistemas da Ivy são muito mais aplicáveis a um operador de meio período. Os sistemas também envolvem um universo muito menor, cálculos mais simples e significativamente menos exposição ao risco.
Esses sistemas são fáceis de entender, parecem lucrativos e seriam bastante simples de implementar. Qualquer um com uma educação de matemática do ensino médio poderia realizar os cálculos necessários eo processo poderia ser facilitado com uma simples planilha do Excel.
Minha única reserva com esses sistemas é a exposição ao risco negativo que existiria no caso de um crash do mercado Black Swan. Se o fundo cair de repente fora de um mercado, eu não quero que os sistemas esperem até o final do mês para recalibrar e ir para uma posição de caixa. Isso poderia ser solucionado definindo-se perdas no filtro SMA de 100 dias para todas as posições abertas.
Exemplo de cálculos de classificação.
Para demonstrar como calcular as classificações mensais, eu construo uma simples planilha do Excel e pesquiso os dados de preços para cada um dos 10 ETFs. Eu indico o preço atual, o preço de 20 dias úteis atrás e o preço de 3 meses atrás. Eu também dei uma olhada rápida no gráfico de cada ETF para ver se estava acima ou abaixo da linha SMA de 100 dias. Eu coloquei um & # 8220; Y & # 8221; na planilha para cada ETF que estava acima da linha e um & # 8220; N & # 8221; para cada ETF que estava abaixo da linha. O resto foi matemática simples para calcular os retornos. Agora que eu tenho a planilha Ivy construída, a matemática será feita automaticamente daqui em diante.
Resultados de backtesting de uma carteira com 10 ETFs.
Como você pode ver, cinco dos ETFs estão atualmente acima das linhas de 100 dias da SMA e os outros cinco estão abaixo das linhas de 100 dias. Os cinco que estão negociando abaixo de suas linhas de 100 dias são automaticamente excluídos da consideração. Curiosamente, eles foram os cinco últimos no ranking geral também.
Os três principais ETFs na classificação geral são GSG, DBC e VB. Portanto, se estivéssemos iniciando ou revisando uma carteira da Ivy Ten neste fim de semana, ela colocaria um terço de sua equidade em cada um desses três ETFs. Então, repetiríamos o mesmo processo no próximo mês.
Ajudando você a construir e comercializar sistemas de negociação rentáveis!
Código Fonte Incluído!
Receba este eBook de 60 páginas grátis com cinco estratégias de negociação!
Que tipo de comerciante do sistema é você?
Socorro! Eu sou um novato. Onde eu começo?
Apenas começando ou não sabe o que é trading de sistema? Eu preciso ser um programador? Posso realmente ganhar dinheiro com um programa de computador que comercializa os mercados? Parece bom demais para ser verdade. Por onde eu começo?
Eu quero construir sistemas de negociação.
Aprenda sobre as melhores técnicas para ajudá-lo a construir, testar e negociar sistemas lucrativos. Aprenda como evitar o ajuste de curvas. Descubra como maximizar retornos e reduzir o draw-down. Vamos construir sistemas lucrativos!
Nossos últimos artigos.
Em primeiro lugar queria dizer ótimo site. Eu descobri o site recentemente e você tem algum conteúdo fantástico, mesmo a partir dos primeiros artigos que li, encontrei várias maneiras de melhorar o processo de desenvolvimento de meus sistemas. Então queria dizer obrigado!
Artigos mais impressionantes.
Estratégias.
Indicadores
Desenvolvimento de sistema.
Resultados da negociação ao vivo!
A partir de dezembro de 2016, abrimos uma conta de negociação para negociar exclusivamente vários sistemas de negociação oferecidos aqui no System Trader Success!
Nossa missão.
Ajudá-lo a construir sistemas de negociação rentáveis.
É a missão do System Trader Success educar e capacitar o profissional de varejo com o conhecimento e as ferramentas adequadas para se tornar um operador consistentemente lucrativo no mundo comercial quantitativo.
Ajudamos milhares de pessoas a descobrir oportunidades lucrativas, ensiná-las sobre técnicas de negociação automatizadas e fornecer informações de mercado poderosas para ajudá-las a atingir suas metas financeiras.
Nosso site é uma fonte única de qualidade e eficaz ferramenta de negociação, sistemas, serviços e conselhos para automatizar seus lucros!
Junte-se para obter acesso exclusivo a.
Ofertas exclusivas e treinamento!
Junte-se à nossa comunidade de operadores de sistema e tenha acesso a incríveis informações de negociação, ferramentas exclusivas, sistemas de negociação e outras oportunidades lucrativas!
Copyright © 2011-2018 pela Capital Evolution LLC. - projetado por prosperar temas | Alimentado por WordPress.
QuantStrat TradeR.
Negociação, QuantStrat, R e mais.
Anunciar alguns ETF sistemáticos (estritamente da minha própria vontade)
Este post apresentará vários ETFs da Alpha Architect e da Cambria Funds (geridos pela Meb Faber) que eu acho que os leitores devem estar cientes (se não já) para capitalizar sobre investimentos sistemáticos sem precisar perder boa parte do retorno devido impostos e custos de transação.
Então, como meus leitores sabem, faço backtest de várias estratégias neste blog que lidam com o faturamento mensal e muitas transações. Em todos os casos, assumo que A) os custos de derrapagem e transação são insignificantes, = B) há capital suficiente tal que quando um esquema de ponderação declara colocar 5,5% de uma carteira em um ETF com um preço caro por ação (EG aranha do setor, SPY, etc.), que a emissão de ações inteiras pode ser cumprida sem emissão, e C) que não há impostos sobre as transações mensais. Para investidores de varejo, sem milhões de dólares, uma ou mais dessas premissas podem não se sustentar. Afinal, se você tem US $ 20.000 para investir, e está pagando US $ 50 por mês em custos de rotatividade, isso é -3% para o seu CAGR, o que tornaria algumas dessas estratégias bastante terríveis.
Então, nesta breve sinopse, quero esclarecer vários desses ETFs.
Em primeiro lugar, um link para um post da Alpha Architect que afirma essencialmente que existem apenas duas tentativas de mercado - anomalias & # 8221; ao corrigir para mineração de dados: valor e momento. Bem, isso e o fator de bens de consumo duráveis. A primeira, eu não sei bem como testar rigorosamente usando apenas dados disponíveis gratuitamente, e o último, não sei bem por que funciona. Baixa volatilidade, talvez?
Em qualquer caso, para pessoas que não possuem capacidades de investimento de nível institucional, aqui estão alguns ETFs que visam capitalizar de forma inteligente os fatores de valor e momentum, juntamente com um portfólio permanente & # 8221; tipo de ETF.
GMOM: Momento Global. Essencialmente, espalhe suas apostas e siga a tendência. Considerando que Meb Faber é um proponente do momentum (veja seu famoso livro Ivy Portfolio), esta é a maneira de capitalizar sobre isso.
QVAL: ETF de valor quantitativo (doméstico) do Alpha Architect. A equipe da Alpha Architect é proponente do investimento em valor e, com uma equipe de vários PhDs dedicados a um processo sistemático de pesquisa de valor, isso pode ser uma maneira de os investidores comprarem e manterem um produto e terceirizarem a pesquisa de valor meticuloso necessária. para a implementação adequada de tal estratégia.
IVAL: uma variante internacional do acima.
GVAL: O fundo de valor quantitativo do Cambria Funds.
Alocação de Ativos (carteira permanente):
GAA: alocação global de ativos. Minha interpretação? Pegue a boa carteira de ações, títulos e ativos reais e espalhe-a pelo mundo.
Agora, vamos apenas fazer um breve resumo e ver como essas estratégias se comportaram no pequeno horizonte de tempo em que o último já existiu.
Em outras palavras, além do momentum, que está tendo uma série de meses, os desempenhos são em geral bastante fortes, nesta pequena amostra (nada significativa).
A única ressalva que eu joguei lá fora, no entanto, é que esses instrumentos não são infalíveis. Por diversão, aqui está um enredo da GVAL (isto é, o fundo de valor global da Cambria) desde a sua criação.
E as estatísticas para isso durante toda a duração do seu início.
Novamente, pequena amostra, nada conclusivo, mas isso significa que esses fundos podem doer ocasionalmente (sem almoço grátis). No entanto, acho que o Dr. Wesley Gray e Mebane Faber, da Alpha Architect e da Cambria Funds, respectivamente, são tão respeitáveis quanto os gerentes financeiros, e a ideia de que se pode investir com eles, ao contrário de Deus. sabe com que fundo mútuo, para mim, é algo que eu acho que vale a pena não apenas apontar, mas chamar uma atenção positiva para isso.
Dito isto, se alguém lá fora tem performances hipotéticas para esses fundos que remonta a uma história de dez anos em uma série de tempo, eu adoraria fazer algumas análises sobre isso. Afinal, se houvesse alguma maneira simples de melhorar ainda mais o desempenho de um portfólio desses instrumentos, acredito que Newton tinha algo a dizer sobre ficar de pé sobre os ombros dos gigantes.
Obrigado pela leitura.
NOTA: Eu estarei dando uma rápida conversa no R em finanças em Chicago no final deste mês (cerca de duas semanas). O registro antecipado termina nesta sexta-feira.
Compartilhar isso:
Relacionado
Pós-navegação.
12 pensamentos sobre & ldquo; Anunciar alguns ETF sistemáticos (estritamente da minha própria vontade) & rdquo;
Estou curioso para saber como funciona a entrada de dados. O que o comando Ad (get (etc)) faz?
Anúncio = ajustado Get converte a string em um nome de variável.
Eu vejo, obrigada. Então os dados vêm de quantmod getSymbols, mas qual é a fonte?
Obrigado Illya por destacar esses ETFs. Seu direito sobre a utilidade potencial de ETFs como estes para nós pequenos investidores. Estou confuso sobre a discrepância nos retornos anualizados da GVAL. Na primeira tabela é 0.323 mas na sua última tabela é -0.081.
Data de início diferente.
Obrigado eu vejo isso agora. Que diferença faz a marcha até o início de dezembro de 2014.
Ótimo blog e recomendações. Qualquer outro ETF ativo (ou fundos mútuos) que passe no teste de detecção para investigação adicional?
Eu vejo tantas alocações de ativos de bricolage na Internet, mas aparentemente tão poucas sendo traduzidas em ETFs. Espero que o rapaz (e não quants) tenha mais opções no futuro.
Estou recebendo: Erro em `[.xts` (x, seq_len (xlen & # 8211; n)): subscrito fora dos limites,
QuantStrat TradeR.
Negociação, QuantStrat, R e mais.
Arquivos da categoria: R.
Uma atualização sobre EAA e uma estratégia de volatilidade.
Novamente, antes de começar este post, gostaria de informar aos leitores que o livro Quantitative Trading With R, escrito por Harry Georgakopoulos, com contribuições minhas, já está disponível para encomenda na Amazon. Já acumulou um par de avaliações de cinco estrelas e lida não apenas com quantstrat, mas com aspectos como negociação de spread, dados de alta frequência e opções. Eu recomendo.
Então, em primeiro lugar, quero informar a todos que a EAA (isto é, Elastic Asset Allocation, o novo algoritmo lançado recentemente pelo Dr. Wouter Keller há algumas semanas) está agora no meu pacote IKTrading. Fiz algumas modificações para lidar com datas de início de segurança incongruentes (ou seja, lidou com o impulso NA, e assim por diante, de forma semelhante ao processo na FAA). Mais uma vez, não há garantias específicas, mas neste momento, acho que o algoritmo não vai quebrar regularmente (mas eu posso estar faltando algum caso de ponta, então o feedback é sempre apreciado). Além disso, depois de pensar um pouco mais, não prevejo a EAA como é capaz de fazer uso de um algoritmo de correlação condicional, pois ao invés de usar simplesmente correlação para seleção de segurança, ele usa correlações para tomar decisões de ponderação. o que levanta a questão de qual seria o valor de correlação da primeira segurança. 0? -1? Idéias sobre como lidar com isso são sempre bem-vindas, já que aplicar a correlação condicional fora de um contexto de classificação é um tópico que agora me interessa.
Além disso, o TrendXplorer publicou recentemente seu próprio post no EAA depois de ver o meu em seu blog. É * muito * abrangente, e para aqueles que estão mais inclinados para a AmiBroker, você estará no Nirvana. Pode ser encontrado aqui. Além disso, parece que ele fez algum trabalho com outro colaborador do SeekingAlpha chamado Cliff Smith (e parece ter trabalhado lado a lado com ele), e assim, teve uma experiência muito mais positiva do que replicar sozinho Harry Long's estratégias (ou, se alguns de vocês quiserem, materiais de marketing). O TrendXplorer fez algum trabalho com uma estratégia chamada QTS, que espero poder cobrir em breve. Isso tudo pode ser encontrado aqui. Então, eu gostaria de estender formalmente graças ao TrendXplorer pelo trabalho que ele fez com a EAA, e também apontando-me para outra estratégia viável de alocação de ativos.
Em termos de minha própria EAA atualizada, para testá-la, acrescentei a Tesla Motors aos sete valores mobiliários originais. Então, vamos analisar o EAA atual.
Essencialmente, pouco mudou além de algumas linhas que lidam com NAs (títulos AKA que ainda não estavam na época, cujos preços são dados como NAs).
Para testar se o algoritmo funcionou, adicionei o TSLA para ver se ele não quebrava o código. Aqui está o novo código de teste.
Com a seguinte tabela de estatísticas e curva de capital:
Essencialmente, o TSLA & # 8212; um momento alto, estoque de alta volatilidade causa alguma consternação na variante ofensiva do algoritmo. Vamos analisar as estatísticas de peso do TSLA quando ele estava no portfólio.
Com os resultados:
Além disso, para ser claro, a função de resumo de R não foi criada com os objetos do tipo xts em mente, portanto as estatísticas de índice são apenas um absurdo (R está tentando fazer estatísticas resumidas sobre os valores numéricos subjacentes do índice de data & # 8212; eles não têm relação com os pesos do TSLA), então se você alguma vez chamar um resumo sobre qualquer coisa em um xts, esteja ciente de que ele não está realmente fornecendo as datas dos pesos correspondentes (se existirem todos & #########################################################. 8212; EG, a média dos pesos não é um peso real em qualquer ponto no tempo).
Em qualquer caso, parece que a variante ofensiva do algoritmo é suscetível a criar portfólios que são muito pouco diversificados, já que a variante ofensiva não coloca qualquer peso na volatilidade da segurança - simplesmente correlação. Então, se houvesse um instrumento muito volátil que estivesse em uma tendência ruidosa, a EAA diria a você para colocar todo o seu portfólio naquele único instrumento - o que, claro, pode ser a coisa certa a fazer se você tiver certeza de que tendência vai continuar, até, claro, ele doesn & t.
Tenho certeza de que ainda existem alguns métodos para explicar instrumentos de perfis de risco / retorno totalmente diferentes, mesmo sem a necessidade de código adicional, variando os parâmetros. Eu só queria demonstrar a necessidade de estar ciente deste fenômeno, o que aconteceu simplesmente testando o portfólio para datas de início incongruentes e só assim aconteceu para escolher um tópico quente & # 8221; estoque.
Por último (para este post), gostaria de tornar os leitores cientes de que o blogger Volatility Made Simple criou uma variante de uma estratégia sobre a qual escrevi anteriormente (mais uma vez, graças ao Sr. Helmuth Vollmeier por fornecer a base inicial) , em que ele misturou sinais das três variantes que eu encontrei em regiões estáveis, e eu estou realmente feliz que ele tenha feito isso, já que ele é uma das primeiras pessoas que estenderam explicitamente o meu trabalho.
Infelizmente, essa estratégia está atualmente em queda. No entanto, olhando para a sua curva de rebaixamento contra a do próprio XIV, parece que a volatilidade tem feito coisas malucas ultimamente, e o rebaixamento tem sido pior no passado. Estou preocupado, no entanto, que pode ser uma estratégia propensa a overfitting, e é um lembrete constante de que ainda há mais a aprender, e mais técnicas para usar para convencer-se de que um backtest não é apenas um overfit, ilusão baseada em dados, amostra-dependente com boa comercialização que irá quebrar imediatamente após olhar para uma amostra maior. No entanto, como eu mesmo não criei a estratégia, gostaria pelo menos de esperar que quem quer que tenha sido a primeira pessoa que surgiu com a ideia de relação VXV / VXMT tenha algumas boas razões para a estratégia, para começar.
No futuro imediato, irei analisar a análise de ponto de mudança e o novo pacote de detecção de fuga do Twitter.
Obrigado pela leitura.
OBS: Sou consultor freelancer em análise quantitativa de temas relacionados a este blog. Se você tem um contrato ou funções em tempo integral disponíveis para pesquisa proprietária que poderiam se beneficiar de minhas habilidades, entre em contato comigo através do meu LinkedIn aqui.
Adicionando uma taxa livre de risco às suas análises.
Primeiro, antes de começar este post, gostaria de tornar meus leitores conscientes do lançamento de um livro para o qual contribuí quase um capítulo inteiro.
Negociação Quantitativa Com R é uma cartilha sobre negociação quantitativa em R escrita por Harry Georgakopoulos, um dos melhores de Chicago. Eu contribuí quase todo o capítulo sobre quantstrat. Se você foi capaz de seguir e entender o código que eu escrevo neste blog, então o capítulo será principalmente revisado e uma referência básica de porcas e parafusos. Mas para aqueles dos meus leitores que encobrem o código e aguardam a piada, eu recomendo fortemente. Além disso, há capítulos sobre negociação de alta frequência, opções, spreads e outras coisas que eu não acredito que estejam disponíveis em qualquer outro livro que realmente ensine aos leitores os detalhes da implementação. Agora, no post.
Como parte da minha continuação do Elastic Asset Allocation, eu quis cobrir como implementar uma medida de uma taxa livre de risco em suas análises. Neste post, analisarei duas pequenas variações do EAA do último post.
Essencialmente, a ideia de que, em vez de olhar para o retorno absoluto, deveríamos olhar para o excesso de retorno sobre algum tipo de taxa livre de risco, como a conta do tesouro de 13 semanas.
Felizmente, o Yahoo realmente * tem * uma maneira de obter os retornos do ativo livre de risco, a saber, o IRX. Mas primeiro, vamos tirar as semelhanças do último post fora do caminho.
Ok, tudo bem até agora, o mesmo que antes. Agora, aqui está a nova inovação, trazida à minha atenção pelo TrendXplorer. Acontece que o índice IRX é, na verdade, o rendimento anualizado para as tesourarias de curto prazo (três meses). Então, adicionando 1, aumentando-o para a 252ª raiz e pegando o produto cumulativo, podemos obter o preço & # 8220; price & # 8221; da taxa livre de risco e, a partir disso, calcule os retornos diários (isso é mais provável que seja redundante, mas quero que todos os meus retornos sejam calculados da mesma maneira).
Então, como isso se encaixa no EAA? Bem, eu adicionei um novo argumento chamado monthlyRiskFree, que permite que um usuário passe na série de preços mensais do ativo livre de risco, neste caso a série de preços IRX derivada. Essa informação é então usada para calcular um retorno livre de risco, que é subtraído dos retornos de todos os ativos e, em vez de obter o retorno absoluto dos ativos no universo, em vez disso, o algoritmo calcula o retorno em excesso do valor livre de risco. de ativos.
Aqui está a função modificada:
Essencialmente, o novo bloco de código é o seguinte:
Qual faz exatamente como eu mencionei acima "# 8212; calcula a variante EAA dos retornos para o período para o ativo livre de risco e subtrai-o dos outros retornos.
Então, como o uso dessa nova inovação se compara a simplesmente observar retornos absolutos?
Aqui está a tabela de estatísticas:
E o gráfico correspondente:
Em suma, não. Não há dados lá. No portfólio defensivo, a mudança é insignificante e, do lado ofensivo, parece encorajar mais risco do que o necessário, com “nada para mostrar, na verdade.
Dito isso, só porque esse método não funcionou, não significa que a mecânica real de obter dados livres de risco seja sem valor.
Obrigado pela leitura.
OBS: Sou consultor freelancer em análise quantitativa de temas relacionados a este blog. Se você tem um contrato ou funções em tempo integral disponíveis para pesquisa proprietária que poderiam se beneficiar de minhas habilidades, entre em contato comigo através do meu LinkedIn aqui.
Por um ano novo, um novo sistema de alocação de ativos acaba de ser publicado no SSRN.
Então, isso é algo que eu tenho trabalhado antes de sua publicação oficial (então este é o primeiro lugar em toda a internet que você verá fora da SSRN, e certamente um dos poucos lugares que o estenderão) ), diretamente em contato com o autor do artigo original, Dr. Wouter Keller, que publicou o algoritmo de alocação flexível de ativos que eu melhorei anteriormente. É chamado Elastic Asset Allocation e parece ser um algoritmo mais simples, porém mais geral. Aqui está o link para o SSRN.
Essencialmente, o algoritmo pode ser explicado simplesmente:
Use dados mensais.
Por um período de 12 meses, queremos a média mensal dos retornos cumulativos de 1, 3, 6 e 12 meses (ou seja, some todos os que estão acima, divida por 22), a volatilidade dos retornos mensais individuais e a correlação de o universo de retornos à média mensal dos retornos. Em seguida, organize esses valores na seguinte expressão:
z_i = (r_i ^ wR * (1-c_i) ^ wC / (v_i + erro) ^ wV) ^ (wS + erro) se r_i & gt; 0, 0 caso contrário, em que:
r_i são os retornos médios.
c_i são as correlações.
v_i são as volatilidades.
wR, wC e wV são os respectivos pesos para retornos, correlações e volatilidades.
Em seguida, selecione os principais ativos do N de P para incluir no portfólio.
Em seguida, os pesos para cada segurança podem ser expressos como os valores normalizados da soma dos z_i & s selecionados.
Se uma regra de proteção contra travamento estiver habilitada, calcule CP, que é a fração do universo de títulos (títulos não selecionados, mas todo o universo) abaixo de zero, dividido pelo tamanho do universo e multiplique todos os pesos por 1-CP. Reinvestir o restante no ativo em dinheiro (algo como VBMFX, VFISX, SHY, etc.). Na FAA, chamei isso de ativo livre de risco, mas, neste caso, é simplesmente o ativo em dinheiro.
O termo de erro é 1e-6 ou algum outro valor pequeno para evitar erros de divisão por zero.
Finalmente, wS é um parâmetro de agressão. Definir esse valor como 0 força essencialmente um portfólio de peso igual, e o infinito simplesmente selecionará o melhor ativo a cada mês.
De qualquer forma, vamos olhar para um protótipo do código (vai bug com retornos de NA, e ainda não inclui retornos em excesso sobre alguns títulos do Tesouro), utilizando os títulos originais da FAA. Os pesos são wR = 1, wC = .5 e wV = 0, com wS = 2 para um esquema ofensivo ou wS = .5 e wC = 1 para um esquema mais defensivo. A proteção contra falhas está ativada.
E aqui estão os resultados:
E as curvas de patrimônio resultantes:
Risco e retorno em exibição total aqui. A variante defensiva que possui uma maior CAGR do que um rebaixamento máximo faz com que pareça atraente à primeira vista, mas eu tenho bastante certeza que é devido ao investimento pesado em fundos de bônus durante o QE.
Não é um algoritmo ruim, embora o fato de haver apenas 7 títulos aqui o deixem aberto a algum risco idiossincrático. O resultado mais óbvio é que a correlação usa uma variante de passagem única, o que significa que é bem possível selecionar ativos correlacionados que não estão correlacionados a ativos não selecionados, mas que estão, de fato, correlacionados entre si. No entanto, como as correlações reais são usadas aqui em oposição à classificação de correlação, estou pensando que um processo de seleção de correlação passo a passo teria que ser escrito especificamente para esse algoritmo específico. Sem dúvida executarei isso por David Varadi e veremos como configurar corretamente um algoritmo de correlação passo a passo ao trabalhar com a interação de correlações com outros valores (retornos, volatilidade).
Em todo caso, o que eu gosto neste algoritmo é que não é apenas um algoritmo de segurança * seleção *, que era o FAA, mas também inclui outro aspecto, que é o aspecto real da ponderação, em vez de simplesmente deixar todos os ativos peso igual.
No momento, isso ainda está em fase prototípica, e estou ciente dos bugs de ativos que não são iniciados ao mesmo tempo, que serão corrigidos antes de eu enviar isso para o meu pacote IKTrading. Mas eu queria colocar isso para fora para aqueles que queriam experimentá-lo e fornecer feedback se eles se deparassem com algo que eles acreditam que vale a pena compartilhar.
Obrigado pela leitura.
OBS: Sou consultor freelancer em análise quantitativa de temas relacionados a este blog. Se você tem um contrato ou funções em tempo integral disponíveis para pesquisa proprietária que poderiam se beneficiar de minhas habilidades, entre em contato comigo através do meu LinkedIn aqui.
Por que o backtesting em pernas individuais em uma propagação é uma má idéia.
Então, depois de ler o último post, o autor do quantstrat teve um feedback principalmente crítico, principalmente da filosofia que estimulou sua escrita em primeiro lugar. Basicamente, a razão pela qual eu escrevi isso, como afirmei antes, é que eu vi muitos usuários de varejo da quantstrat perguntarem constantemente "como faço para modelar instrumentos de propagação individuais", e de outra forma tentar parecer com eles? # 8217; é sofisticado por spreads comerciais.
A verdade é que os verdadeiros profissionais usam ferramentas de força industrial para determinar suas taxas de hedge intradia (essa ferramenta é chamada de spreader). O propósito do quantstrat não é ser um sistema de modelagem de execução, mas ser um sistema de modelagem * strategy *. Basicamente, o objetivo do seu backteste não é olhar para os instrumentos individuais, uma vez que no último post, as estatísticas agregadas do comércio não nos diziam absolutamente nada sobre como a nossa estratégia de negociação de spread real foi executada. O backtest era uma bagunça no que diz respeito às análises, tornando-as mais ou menos inúteis. Portanto, este post, a pedido do autor do quantstrat, é sobre como fazer melhor a análise, e olhando para o que mais importa - o desempenho real da estratégia no relacionamento real que está sendo negociado, ou seja, o spread * *, em vez dos dois componentes.
Então, sem mais delongas, vamos analisar o código revisado:
Neste caso, as coisas são muito mais simples. Ao invés de pular através dos arcos de pré-computação de um indicador, junto com as travessuras de regras separadas tanto para o longo quanto para o curto, nós simplesmente temos um spread, como teoricamente supostamente funciona: três de um ETF desalavancado contra o ETF alavancado 3x, e podemos ir longo a propagação, ou reduzir o spread. Nesse caso, a dinâmica parece estar em alta e queremos capturá-la.
Então como fomos?
E aqui está a saída:
Em outras palavras, o perfil típico de um seguidor de tendência, e não a análise não informativa do último post. Além disso, o dimensionamento da posição e o gráfico da curva de capital realmente fazem sentido agora. Aqui estão eles.
Para concluir, embora seja possível modelar spreads usando pernas individuais, faz muito mais sentido, em termos de análise, examinar realmente o desempenho da estratégia no relacionamento real que está sendo negociado, que é o próprio spread. Além disso, depois de construir o spread como um instrumento sintético, ele pode ser tratado como qualquer outro instrumento regular no contexto da análise em quantstrat.
Obrigado pela leitura.
OBS: Sou consultor freelancer em análise quantitativa de temas relacionados a este blog. Se você tem um contrato ou funções em tempo integral disponíveis para pesquisa proprietária que poderiam se beneficiar de minhas habilidades, entre em contato comigo através do meu LinkedIn aqui.
Uma maneira de modelar a execução em pernas individuais de um spread em Quantstrat.
Neste post, tentarei abordar uma questão que já vi repetidas vezes em relação ao quantstrat.
& # 8220; Como faço para modelar execuções em instrumentos subjacentes individuais na negociação de spread? & # 8221;
Em primeiro lugar, um aviso de isenção de responsabilidade: este método é um pouco desajeitado e, ao usá-lo, você perderá a funcionalidade de otimização embutida do quantstrat. Essencialmente, ele se baseia na metodologia de sinal pré-computada que descrevi em um post anterior.
Essencialmente, anexando uma coluna com o mesmo nome, mas com valores diferentes para dois instrumentos separados, eu posso "enganar" # 8221; Quantstrat em fornecer-me o comportamento desejado, modelando negociação em dois instrumentos subjacentes.
Então, aqui está a estratégia:
Faça 3 longas ações do ETF UNG (gás natural) contra 1 ação da UGAZ (3x touro) quando o spread ultrapassar sua média móvel exponencial de 20 dias, caso contrário, não faça nada. Aqui está o raciocínio do porquê:
Com o enredo correspondente:
Então, como você pode ver, temos um spread que sobe (algo a ver com a natureza do ETF alavancado)? Então, vamos tentar capturar isso com uma estratégia.
A maneira que eu vou fazer isso é pré-calcular um sinal se o close do spread está ou não acima de seu EMA20, e anexar esse sinal ao UNG, com o negativo do referido sinal anexado ao UGAZ e, em seguida, encapsulá-lo em uma estratégia quantstrat. In this case, there’s no ATR order sizing function or initial equity–just a simple 3 UNG to 1 UGAZ trade.
So, did our spread trade work?
Tipo de. However, when you think about it–looking at the statistics on a per-instrument basis in a spread trade is a bit of a red herring. After all, outside of a small spread, what one instrument makes, another will lose, so the aggregate numbers should be only slightly north of 1 or 50% in most cases, which is what we see here.
A better way of looking at whether or not the strategy performs is to look at the cumulative sum of the daily P&L.
With the following equity curve:
Is this the greatest equity curve? Provavelmente não. In fact, after playing around with the strategy a little bit, it’s better to actually get in at the close of the next day than the open (apparently there’s some intraday mean-reversion).
Furthermore, one thing to be careful of is that in this backtest, I made sure that for UNG, my precomputedSig would only take values 1 and 0, and vice versa for the UGAZ variant, such that I could write the rules I did. If it took the values 1, 0, and -1, or 1 and -1, the results would not make sense.
In conclusion, the method I showed was essentially a method building on a previous technique of pre-computing signals. Doing this will disallow users to use quantstrat’s built-in optimization functionality, but will allow users to backtest individual leg execution.
To answer one last question, if one wanted to short the spread as well, the thing to do using this methodology would be to pre-compute a second column called, say, precomputedSig2, that behaved the opposite way.
Obrigado pela leitura.
NOTE: I am a freelance consultant in quantitative analysis on topics related to this blog. If you have contract or full time roles available for proprietary research that could benefit from my skills, please contact me through my LinkedIn here.
The ZOMMA Warthog Index.
Harry Long posted another article on SeekingAlpha. As usual, it’s another strategy to be taken with a grain of salt, but very much worth discussing. So here’s the strategy:
50% XLP, 15% GLD, 35% TLT — aka a variation of the stocks/bonds portfolio, just with some gold added in. The twist is the idea that XLP is less risky than SPY. The original article, written by Harry Long, can be found here.
This strategy is about as simple as they come, and is tested just as easily in R.
Here’s the original replication:
And the resulting replicated (approximately) equity curve:
Now, let’s put the claim of outperforming over an entire cycle to the test.
And here’s the output:
So, even with SPY’s 2008 in mind, this strategy seems to break even on a year-to-year basis, and the returns are slightly better, which I suppose should be par for the course for a backtest against SPY through the recession.
Now, let’s just remove that one year and see how things stack up:
And we obtain the following results:
In short, the so-called outperformance is largely sample-dependent on the S&P having a terrible year. Beyond that, things don’t look so stellar for the strategy.
Lastly, anytime anyone makes a claim about a strategy outperforming a benchmark, one very, very easy test to do is to simply look at the equity curve of a “market neutral” strategy that shorts the benchmark against the strategy, and see if that looks like an equity curve one would be comfortable holding. Aqui estão os resultados:
And the resulting equity curve of the outperformance:
Basically, ever since the crisis passed, the strategy has been flat to underperforming against SPY, which is fair enough considering that the market has been on a roar since then.
To hammer the point, let’s look at the equity curves from 2009 onwards.
With the result:
To its credit, the strategy’s equity curve is certainly a smoother ride. At the same time, the underperformance is clear as well. I suppose this makes sense as a portfolio invested 35% in bonds should expect to underperform a portfolio fully invested in equities on an absolute returns basis.
Now, as I did before, in It’s Amazing How Well Dumb Things Get Marketed, I’m going to backtest this strategy as far as I can using proxies from Quandl for gold and bonds, by going directly to the futures. Refer to that post to see that the proxies are relatively decent for the ETFs. In this case, I switched from adjusted to close prices, but the concept should still hold.
And here’s the resultant equity curve comparison:
So, the idea that the strategy outperforms SPY on an absolute returns basis? It seems to be due to SPY’s horrendous performance in 2008, which is a once-in-several-decades event. As you can see, if you started from XLP’s inception to approximately 2005, the strategy was actually in drawdown for all those years, at least if you started in 1998.
Let’s look at the risk/reward metrics for this timeframe:
And the results:
To its credit, the strategy has a significantly better return to risk profile than SPY does, which I hope would be the case for any backtest going up against SPY with 2008 in mind. Overall, the strategy has a bit of merit as a defensive play, and for a simple static allocation based strategy that plays on the defensive side, it delivers what you might expect from a risk-averse strategy, which is reflected in a much better return to drawdown profile than the market. Nevertheless, one should be careful not to misinterpret a strategy whose focus is to control risk for a strategy that aims to swing for the fences. Furthermore, this is a strategy that Harry Long has been so kind as to give away, so take it for what it’s worth–a simple-to-implement defensive strategy which delivers on its defensive promises.
Obrigado pela leitura.
NOTE: I am a freelance consultant in quantitative analysis on topics related to this blog. If you have contract or full time roles available for proprietary research that could benefit from my skills, please contact me through my LinkedIn here.
An Update to the Robustness Heuristic and a Variation of a Volatility Strategy.
So, before revealing a slight wrinkle on the last strategy I wrote about, I’d like to clear up a bit of confusion regarding Jaekle and Tomasini’s idea of a stable region.
Essentially, the entire idea *is* that similar parameter configurations behave in very similar ways, and so, are supposed to be highly correlated. It does not mean the strategy may not be overfit in other ways, but that incremental changes to a parameter should mean incremental changes to performance, rather than seeing some sort of lucky spike in a sea of poor performance.
In any case, the one change to the strategy from last week is that rather than get in at the current close (aka observe close, execute at close), to get in at the next day’s close.
Again, here’s the strategy script:
The one change I made is that rather than go with the default lag value, I went with a lag of 2. A lag of zero induces look-ahead bias. In any case, let’s run through the process again of analyzing for robustness.
In this case, I added some functionality to not only do the plotting and correlation, but to spit out a table comparing both the aggregate metric along with the rank of the average monthly rank (again, dual ranking layer), and ordered the table by the sum of both the aggregate and the monthly metric, starting with the highest.
For instance, here’s the output from the returns comparison:
So, for this configuration, the correlation went down from above .8 to around .74…which is still strong and credence that the strategy configurations have validity outside some lucky months. The new feature I added was the data frame of the two ranks side by side, along with their configuration name (in this case, my names were simply the SMA parameter, but the names could be anything such as say, SMA_60_lag_2), and the sum of the two rankings, which orders the configurations. As there were 191 configurations (SMA ranging from 10 to 200), the best score that could be achieved was 382. Furthermore, note that although there seems to be a strong region from SMA 53 to SMA 67, there also seems to be another region, at least when it comes to absolute return, of an SMA parameter at SMA 150+.
Here’s the same table for annualized Sharpe (this variation takes a bit longer to compute due to the monthly annualized Sharpes).
So, largely the same sort of results as we see with the annualized returns. A correlation of .5 gives some cause for concern, which will hopefully show up in the line plot of the rank of the four metrics (returns, Sharpe, drawdowns, and return to drawdown), which will reveal the regions with strong performance, and not-so-strong performances.
Here’s the ranking line plot.
And the resulting plot:
There are several regions that show similar, strong metrics for similar parameter choices for the value of SMA when we use a “delayed” entrada. Namely, the regions around the 60 day SMA, the 150 day SMA, and the 125 day SMA.
Let’s look at those configurations.
And the results:
And the resulting performance, on both a regular, and log scale:
Perfect strategies? There’s probably room for improvement. As good if not better than the volatility strategies posted elsewhere on the internet? Provavelmente. Is there more investigation that can be done regarding the differences in signal delay? Sim.
So, in conclusion for this post, I’m hoping that the rank comparison heuristic and its new output gives people another tool to consider, along with another vol strategy to consider as well.
Obrigado pela leitura.
NOTE: I am a freelance consultant in quantitative analysis on topics related to this blog. If you have contract or full time roles available for proprietary research that could benefit from my skills, please contact me through my LinkedIn here.
A New Volatility Strategy, And A Heuristic For Analyzing Robustness.
This post is motivated by a discussion that arose when I tested a strategy by Frank of Trading The Odds (post here). One point, brought up by Tony Cooper of Double Digit Numerics, the original author of the paper that Trading The Odds now trades (I consider it a huge honor that my blog is read by authors of original trading strategies), is that my heatmap analysis only looked cross-sectional performance, as opposed to performance over time–that is, performance that could have been outstanding over the course of the entire backtest could have been the result of a few lucky months. This is a fair point, which I hope this post will address in terms of a heuristic using both visual and analytical outputs.
The strategy for this post is the following, provided to me kindly by Mr. Helmuth Vollmeier (whose help in all my volatility-related investigations cannot be understated):
Consider VXV and VXMT, the three month and six month implied volatility on the usual SP500. Define contango as VXV/VXMT < 1, and backwardation vice versa. Additionally, take an SMA of said ratio. Go long VXX when the ratio is greater than 1 and above its SMA, and go long XIV when the converse holds. Or in my case, get in at the close when that happens and exit at the next day's close after the converse occurs (that is, my replication is slightly off due to using some rather simplistic coding for illustrative purposes).
In any case, here is the script for setting up the strategy, most of which is just downloading the data–the strategy itself is just a few lines of code:
About as straightforward as things get (the results, as we'll see, are solid, as well). In this case, I tested every SMA between a 10 day and a classic 200 day SMA. And since this strategy is a single-parameter strategy (unless you want to get into adjusting the ratio critical values up and down away from 1), instead of heatmaps, we'll suffice with basic scatter plots and line plots (which make things about as simple as they come).
The heuristic I decided upon was to take some PerfA functions (Return. annualized, SharpeRatio. annualized, for instance), and compare the rank of the average of their monthly ranks (that is, a two-layer rank, very similar to the process in Flexible Asset Allocation) to the aggregate, whole time-period rank. The idea here is that performance based on a few lucky months may have a high aggregate ranking, but a much lower monthly ranking, which would be reflected in a scatter plot. Ideally, the scatter plot would go from lower left to upper right in terms of ranks comparisons, with a correlation of 1, meaning that the strategy with the best overall return will have the best average monthly return rank, and so on down the list. This can also apply to the Sharpe ratio, and so on.
Here is my off-the-cuff implementation of such an idea:
So, I get a chart and a correlation of average monthly ranks against a single-pass whole-period rank. Here are the results for cumulative returns and Sharpe ratio:
Basically, the interpretation is this: the outliers above and to the left of the main cluster can be interpreted as those having those “few lucky months”, while those to the lower right consistently perform somewhat well, but for whatever reason, are just stricken with bad luck. However, the critical results that we’re looking for is that the best overall performers (the highest aggregate rank) are also those with the most *consistent* performance (the highest monthly rank), which is generally what we see.
Furthermore, the correlation of .85 also lends credence that this is a robust strategy.
Here’s the process repeated with the annualized Sharpe ratio:
In other words, an even clearer relationship here, and again, we see that the best performers overall are also the best monthly performers, so we can feel safe in the robustness of the strategy.
So what’s the punchline? Well, the idea is now that we’ve established that the best results on aggregate are also the strongest results when analyzing the results across time, let’s look to see if the various rankings of risk and reward metrics reveal which configurations those are.
Here’s a chart of the aggregate rankings of annualized return (aka cumulative return), annualized Sharpe, MAR (return over max drawdown), and max drawdown.
And the resulting plot itself:
So, looking at these results, here are some interpretations, moving from left to right:
At the lower end of the SMA, the results are just plain terrible. Sure, the drawdowns are lower, but the returns are in the basement.
The spike around the 50-day SMA makes me question if there is some sort of behavioral bias at work here.
Next, there’s a region with fairly solid performance between that and the 100-day SMA, but is surrounded on both sides by pretty abysmal performance.
Moving onto the 100-day SMA region, the annualized returns and Sharpe ratios are strong, but get the parameter estimation incorrect going forward, and there’s a severe risk of incurring heavy drawdowns. The jump improvement in the drawdown metric is also interesting. Again, is there some sort of bias towards some of the round numbers? (50, 100, etc.)
Lastly, there’s nothing particularly spectacular about the performances until we get to the high 100s and the 200 day SMA, at which point, we see a stable region of configurations with high ranks in all categories.
Let’s look at that region more closely:
And the results:
So starting from SMA 186 through SMA 200, we see some fairly strong performance–returns in the high 70s to the low 80s, and MARs in the high 1s to low 2s. And of course, since this is about a trading strategy, equity curves are of course, obligatory. Here is what that looks like:
Basically, on aggregate, some very strong performance. However, it is certainly not *smooth* performance. New equity highs are followed by strong drawdowns, which are then followed by a recovery and new, higher equity highs.
To conclude (for the moment, I’ll have a new post on this next week with a slight wrinkle that gets even better results), I hope that I presented not only a simple but effective strategy, but also a simple but effective (if a bit time consuming, to do all the monthly computations on 191 return streams) heuristic suggested/implied by Tony Cooper of double digit numerics for analyzing the performance and robustness of your trading strategies. Certainly, while many professors and theorists elucidate on robustness (with plenty of math that makes stiff bagels look digestible), I believe not a lot of attention is actually paid to it in more common circles, using more intuitive methods. After all, if someone would want to be an unscrupulous individual selling trading systems or signals (instead of worrying about the strategy’s capacity for capital), it’s easy to show an overfit equity curve while making up some excuse so as to not reveal the (most likely overfit) strategy. One thing I’d hope this post inspires is for individuals to ask not only look at equity curves, but also plots such as aggregate against average monthly (or higher frequencies, if the strategies are tested over mere months, for instance, such as intraday trading) metric rankings when performing parameter optimization.
Is this heuristic the most robust and advanced that can be done? Provavelmente não. Would one need to employ even more advanced techniques if computing time becomes an issue? Probably (bootstrapping and sampling come to mind). Can this be built on? Claro. *Will* someone build on it? I certainly plan on revisiting this topic in the future.
Lastly, on the nature of the strategy itself: while Trading The Odds presented a strategy functioning on a very short time frame, I’m surprised that instead, we have a strategy whose parameters are on a much higher end of the numerical spectrum.
Obrigado pela leitura.
NOTE: I am a freelance consultant in quantitative analysis on topics related to this blog. If you have contract or full time roles available for proprietary research that could benefit from my skills, please contact me through my LinkedIn here.
An Update on Flexible Asset Allocation.
A few weeks back, after seeing my replication, one of the original authors of the Flexible Asset Allocation paper got in touch with me to tell me to make a slight adjustment to the code, in that rather than remove any negative-momentum securities before performing any ranking, to perform all ranking without taking absolute momentum into account, and only removing negative absolute momentum securities at the very end, after allocating weights.
Here’s the new code:
And here are the new results, both with the original configuration, and using the stepwise correlation ranking algorithm introduced by David Varadi:
And the resulting equity curve comparison.
Overall, it seems filtering on absolute momentum after applying all weightings using only relative momentum to rank actually improves downside risk profiles ever so slightly compared to removing negative momentum securities ahead of time. In any case, FAAreturns will be the function that removes negative momentum securities ahead of time, and FAA will be the ones that removes them after all else is said and done.
I’ll return to the standard volatility trading agenda soon.
Obrigado pela leitura.
Note: I am a freelance consultant in quantitative analysis on topics related to this blog. If you have contract or full time roles available for proprietary research that could benefit from my skills, please contact me through my LinkedIn here.
Trading The Odds Volatility Risk Premium: Addressing Data Mining and Curve-Fitting.
Several readers, upon seeing the risk and return ratio along with other statistics in the previous post stated that the result may have been the result of data mining/over-optimization/curve-fitting/overfitting, or otherwise bad practice of creating an amazing equity curve whose performance will decay out of sample.
Fortunately, there’s a way to test that assertion. In their book “Trading Systems: A New Approach to System Development and Portfolio Optimization”, Urban Jaekle and Emilio Tomasini use the concept of the “stable region” to demonstrate a way of visualizing whether or not a parameter specification is indeed overfit. The idea of a stable region is that going forward, how robust is a parameter specification to slight changes? If the system just happened to find one good small point in a sea of losers, the strategy is likely to fail going forward. However, if small changes in the parameter specifications still result in profitable configurations, then the chosen parameter set is a valid configuration.
As Frank’s trading strategy only has two parameters (standard deviation computation period, aka runSD for the R function, and the SMA period), rather than make line graphs, I decided to do a brute force grid search just to see other configurations, and plotted the results in the form of heatmaps.
Here’s the modified script for the computations (no parallel syntax in use for the sake of simplicity):
Essentially, just wrap the previous script in a nested for loop over the two parameters.
I chose GGplot2 to plot the heatmaps for more control with coloring.
Here’s the heatmap for the MAR ratio (that is, returns over max drawdown):
Here’s the result:
Immediately, we start to see some answers to questions regarding overfitting. First off, is the parameter set published by TradingTheOdds optimized? Sim. In fact, not only is it optimized, it’s by far and away the best value on the heatmap. However, when discussing overfitting, curve-fitting, and the like, the question to ask isn’t “is this the best parameter set available”, but rather “is the parameter set in a stable region?” The answer, in my opinion to that, is yes, as noted by the differing values of the SMA for the 2-day sample standard deviation. Note that this quantity, due to being the sample standard deviation, is actually the square root of the two squared residuals of that time period.
Here are the MAR values for those configurations:
In this case, not only is the region stable, but the MAR values are all above 2 until the SMA9 value.
Furthermore, note that aside from the stable region of the 2-day sample standard deviation, a stable region using a standard deviation of ten days with less smoothing from the SMA (because there’s already an average inherent in the sample standard deviation) also exists. Let’s examine those values.
Apparently, a standard deviation between 2 and 3 weeks with minimal SMA smoothing also produced some results comparable to the 2-day variant.
Off to the northeast of the plot, using longer periods for the parameters simply causes the risk-to-reward performance to drop steeply. This is essentially an illustration of the detriments of lag.
Finally, there’s a small rough patch between the two aforementioned stable regions. Here’s the data for that.
As you can see, there are some patches where the MAR is below 1, and many where it’s below 1.5. All of these are pretty detached from the stable regions.
Let’s repeat this process with the Sharpe Ratio heatmap.
Again, the TradingTheOdds parameter configuration lights up, but among a region of strong configurations. This time, we can see that in comparison to the rest of the heatmap, the northern stable region seems to have become clustered around the 10-day standard deviation (or 11) with SMAs of 2, 3, and 4. The regions to the northeast are also more subdued by comparison, with the Sharpe ratio bottoming out around 1.
Let’s look at the numerical values again for the same regions.
Two-day standard deviation region:
Again, numbers the likes of which I myself haven’t been able to achieve with more conventional strategies, and numbers the likes of which I haven’t really seen anywhere for anything on daily data. So either the strategy is fantastic, or something is terribly wrong outside the scope of the parameter optimization.
Two week standard deviation region:
Again, pretty outstanding numbers.
The rough patch:
All Sharpe ratios higher than 1, though some below 1.5.
So, to conclude this post:
Was the replication using optimized parameters? Sim. However, those optimized parameters were found within a stable (and even strong) region. Furthermore, it isn’t as though the strategy exhibits poor risk-to-return metrics beyond those regions, either. Aside from raising the lookback period on both the moving average and the standard deviation to levels that no longer resemble the original replication, performance was solid to stellar.
Does this necessarily mean that there is nothing wrong with the strategy? No. It could be that the performance is an artifact of “observe the close, enter at the close” optimistic execution assumptions. For instance, quantstrat (the go-to backtest engine in R for more trading-oriented statistics) uses a next-bar execution method that defaults on the *next* day’s close (so if you look back over my quantstrat posts, I use prefer=”open” so as to get the open of the next bar, instead of its close). It could also be that VXMT itself is an instrument that isn’t very well known in the public sphere, either, seeing as how Yahoo finance barely has any data on it. Lastly, it could simply be the fact that although the risk to reward ratios seem amazing, many investors/mutual fund managers/etc. probably don’t want to think “I’m down 40-60% from my peak”, even though it’s arguably easier to adjust a strategy with a good reward to risk ratio with excess risk by adding cash (to use a cooking analogy, think about your favorite spice. Good in small quantities.), than it is to go and find leverage for a good reward to risk strategy with very small returns (not to mention incurring all the other risks that come with leverage to begin with, such as a 50% drawdown wiping out an account leveraged two to one).
However, to address the question of overfitting, through a modified technique from Jaekle and Tomasini (2009), these are the results I found.
Obrigado pela leitura.
Note: I am a freelance consultant in quantitative analysis on topics related to this blog. If you have contract or full time roles available for proprietary research that could benefit from my skills, please contact me through my LinkedIn here.
O portfólio Ivy.
Several months ago I finished reading a very interesting book called, “The Ivy Portfolio.” This book was written by two money managers, Mebane Faber and Eric Richardson, who work at Cambria Investment Management. The authors wanted to answer the question of why money managers who manage some of the world’s best Ivy League schools produce such consistent results. Routinely Harvard and Yale endowments produce double digit annual returns. Since 1985 Yale University has returned around 16% annual returns and Harvard over 15% annual returns. Not only did they produce outstanding returns, but they did it by also reducing volatility and drawdown.
Wouldn’t it be nice to mimic the investing strategy utilized by these endowments? Well, the authors do just that. Faber and Richardson set out to explore how these endowments produce such great returns and minimize both volatility and drawdown. They go a step further by providing several simplified, yet effective, models to mimic the trading results of these professionals. The heart of one of their proposed models is a simple relative strength, asset allocation strategy using ETFs.
This really caught my attention. Such a simple model could be a great way to invest within a retirement account as most people have access to ETFs. It’s a long-only strategy (no shorting) and you don’t need to place trades very often.
In this article I want to create models based upon Faber’s and Richardson’s recommendations. To do this I’m going to use the fantastic ETF service called, ETF Replay. What this web service allows you to do is create trading strategies and backtest them on a portfolio of ETFs. The website charges a monthly fee to use their service, but it’s very reasonable. Between the book’s recommendation and ETF Replay service, we can produce a trading model.
The Ivy Trading System.
We are going to trade a basket of ETFs. Exactly which ETFs will be explained later. We are not going to simply trade all the ETFs at once. We will instead rotate into the three best performers every month. The concept behind the top three performers is they will likely continue to perform into the near-term future. However, we also wish to reduce drawdowns and avoid holding our ETFs when within a bear market because even the best ranked ETFs during this environment will most likely be falling. Sure they are falling slower than the others in the basket, but we don’t want to be holding any of our ETFs if they are in a bear market. In other words, we wish to preserve our capital during a bear market. Remember, this is a long-only strategy. To avoid holding positions in a bear market we use a 100-day (5-month) simple moving average to filter our trades. We will only buy an ETF if it’s above this average.
Here is a summary of the relative strength ranking model:
1) Rank the ETFs based upon their relative strength. There are many ways to do this, but a very straightforward method is to simply rank each ETF based upon two historical results, a 3-month return and a 1-month return. ETFs are ranked for each of these two returns. A weight is then factored for each rank to compute an overall rank. You can find an example on the ETF Replay website. By using two historical returns, we are taking into account both a short-term return and a longer term return. The ranking score is computed as the sum the equal weighting of the 20-day return and the 3-month return. These numbers are completely arbitrary. They are not optimized.
Overall Rank Score = ( 20-Day Return ) *.5 + ( 3-Month Return ) *.5.
2) Apply regime filter and only hold ETFs within a bull market regime. This is our old familiar regime filter that I’ve written about time and time again. The authors of the book use a 10-month simple moving average. This is similar to a 200-day simple moving average if you estimate about 20 trading days in a month. However, I choose to pick half that value simply because I would like my model to be a bit more responsive when taking into account the possible onset of a bear market. This value is not optimized.
Bull Market = Close > Average( Close, 100 days);
3) Re-balance the portfolio on a monthly schedule. At this time we evaluate our entire basket of ETFs based upon the two methods above. We then take action.
uma. SELL all ETFs that either no longer rank in the top three positions and/or who have fallen below the regime filter.
b. BUY the top three ranking ETFs who are within a bull regime. Each ETF will be dedicated to 1/3 of the available account equity.
4) Our money remains in “Cash” (SHY) whenever not being allocated to a specific asset class.
Given this model it’s possible to hold 1, 2, 3 or zero positions. When money is not allocated to an ETF we move it into cash.
Ivy Five Trading System.
We have our trading model ready to go, but what basket of ETFs are we going to trade? The authors first start us out with a very simple basket of five ETFs. These ETFs represent the broadest asset classes we wish to diversify over. Our relative strength rotational model will allow us to ride the best performing asset classes while perserving our capital during a bear market. The Ivy Five are:
BND – Vanguard Total bond market (4-5 year)
DBC – PowerShares DB Commodity Index.
VEU – Vanguard FTSE All-World ex-US.
VNQ – Vanguard MSCI U. S. REIT.
VTI – Vanguard MSCI Total U. S. Stock Market.
This basket of ETFs gives us a broad exposure to corporate/credit bonds (BND), commodities (DBC), international equity (VEU), REITs, Preferreds and MLPs (VNQ) and U. S. Equity (VTI). Let’s now use the ETF rewind website to test our Ivy Five Portfolio (green line) on our model. We will use the SPY ETF (blue line) as our benchmark. Returns include dividends but exclude commissions and slippage.
We can see our portfolio outperforms the benchmark in several ways. First, it produces a higher total return of 204% vs. 95%. But maybe even more important is during the bear market of 2008 we can see a significant difference in the drawdown levels. While the benchmark was down around 55% and our portfolio was down about half that value at 21%. Overall volatility is also significantly reduced with our portfolio. In the end our portfolio returns a 11.8% CAGR while the benchmark returns a 7.0% CAGR. Our model increases returns while reducing both drawdown and volatility.
Ivy Ten Trading System.
Trading only five ETFs is rather restrictive when you consider the vast number of ETFs available. Let’s continue to work with the same asset classes but introduce a few specialized ETFs to expand our diversification. The authors recommend the following ten ETFs:
BND – Vanguard Total bond market (4-5 year)
DBC – PowerShares DB Commodity Index.
GSG – iShares S&P Commodity-Indexed Trust.
RWX – SPDR DJ International Real Estate.
DICA & # 8211; iShares Barclays TIPS (4-8 years)
VB – Vanguard MSCI U. S. Small Cap.
VEU – Vanguard FTSE All-World ex-US.
VNQ – Vanguard MSCI U. S. REIT.
VTI – Vanguard MSCI Total U. S. Stock Market.
VWO – Vanguard MSCI Emerging Markets.
The results of running this portfolio through out model is below. Again, the SPY ETF is our benchmark. Returns include dividends but exclude commissions and slippage.
We can see our portfolio, once again, outperforms the benchmark in several ways. First, it produces a higher total return of 291% vs. 95%. Notice this is signifcannly higher than our Ivy Five Portfolio. In regards to drawdown, the benchmark was down around 55% while our portfolio was down 29%. It’s interesting to note we do generate a higher return when compared to our Ivy Five Portfolio, but it comes at a cost of more drawdown. In the end our portfolio returns a respectable 14.7% CAGR while the benchmark returns a 7.0% CAGR. We double our returns while significantly reducing drawdown.
Então você tem isso. The Ivy Ten trading system in a nutshell. It’s dead simple with some very nice returns. The authors also demonstrate a 20-ETF portfolio that I may look at in a later article. For now, this should give you some insight to how to mimic the returns and low drawdown of the best Ivy League schools. Can you trade this in your retirement accounts? Well, that’s up to you but I’ve been seriously considering something like this. I find the simplicity and monthly balancing very convenient. Fundamentally, I’ve always liked the idea of momentum investing and knowing when to exit a position during a bear market. This seems to do a decent job of capturing these two aspects rather well.
Obtenha o livro.
Sobre o autor Jeff Swanson.
Jeff é o fundador do System Trader Success - um site e uma missão para capacitar o profissional de varejo com o conhecimento e as ferramentas adequadas para se tornar um operador lucrativo no mundo da negociação quantitativa / automatizada.
Posts Relacionados.
Sharpe Ratio - a resposta certa para a pergunta errada?
Usando metais para o comércio de títulos.
Indicador de MCVI e estratégia em gráficos diários.
Nice find Jeff. I’ve been very interested in multi-sector relative strength strategies. I’m also researching doing this with pairs, ie, going long the strongest sectors and short the weakest sectors (or long the inverse ETF). I’m guessing this would provide even less volatility but might reduce profits. I’m not sure, haven’t run the numbers yet.
I’m planning on introducing a few short ETFs into the mix and see how it affects the results. Those articles will most likely appear early next year. I like the pairs idea as well. I’ll have to look into that.
December’s TAS&C (page 10, “Reducing Risk While Finding Profit”) has a nice article on tracking pairs, particularly with sector ETFs as a way to play sector rotation.
That article looks interesting as I am also researching on using pairs as trading vehicles. Do you know where I can get it as a. pdf?
just a word of warning: As nice as ETF Replay looks, the quality of the simulations is not very good. I know a trader who ran a simulation there and in parallel used his own software and data. When he compared the results the differences were huge (i. e., 400%-points less profit than shown by ETF Replay). He couldn’t find out what caused this, but his best guess is that there is something wrong with their data (or how they deal with splits & dividends). Some errors could be caused by logical errors in their ranking and filtering.
I don’t want to bash ETF Replay and maybe they fixed whatever problems there were. Yet I recommend to double check any results with software that is transparent for you in what is does and utilizes data that is adjusted (or not) in the way that is appropriate for the task.
Thanks for the heads-up TK. That’ a huge difference if there was/is a problem ETF Replay’s data.
All ETFs have different starting days. In the first port6folio of 5 ETFs, VEU starts after March 2007, BND after April 2007 and DBC after Feb 2006. Thus, results are skewed by the positive performance of the VNQ and VTI ETFs and as a result this is selection bias.
I would recommend to you not to rely on backtests of other websites because they may not even know their own assumptions. Try selecting at random 5 ETFs from a universe of 100. Then backtest with specific position sizing rules. You will see that it does not work and buy-and-hold is much better. Fooled by randomness.
Great points, Basha. I checked into ETF Replay about a year ago and was disappointed about limited choices of starting day. Rather than a backtest that starts on the first of each month or the 31st, I’d like to run 31 different backtests where each started on a different day of the month. What we should see is similar performance among all. If some perform significantly better then look for a reason why. Maybe the expected performance going forward should be the average of them all.
Another thing you could do is run some Monte Carlo simulations and then plot equity curves that represent averages. Drawdown analysis could be studied the same way.
Fooled by randomness, indeed!
Mark, thanks for the comment. Have you tested your idea on your backtesting software? I would be interested to see your results.
Alas, while my software can do rotational backtesting, my programming has yet to reach that level of expertise. It’s on my “To Do” Lista.
Basha, out of curiosity I ran the ETF Replay backtest from 2007 and the portfolio still generated very solid performance. The Ivy-10 generates 122% return while the SPY generates a 14% return. Drawdown is 29% vs 55% respectively.
Maybe I mis-understand what you are saying? If you randomly select 5 from a universe of 100, you are not following the idea of selecting 5 that are indicating a positive up trend in an uptrending market.
And, if you randomly select any 5 of 100, shouldn’t you do a Monte Carlo distribution to truely compare the random approach to the Ivy Approach?
o que estou perdendo?
What is the starting capital and position sizing used? Do they reinvest profits?
This comment reply was for Jeff actually.
To Red: that is what I am saying. You also have to also find out which portfolios that met the ranking cirteria did not work out and then average the results.
My understanding about the service is this: The starting equity is 100. Each ETF is weighted equally. In the case for my example Ivy models, each ETF is given 33% of the equity since it picks, at most, the top three relative performers. Returns are total returns which includes profits and dividends. Commissions and slippage are not included.
Having now read the book, I’ve just finished implementing this within TS (although I have to export the equity from the print log and assemble the portfolio equity curve in Excel).
Once the portfolio is increased to 10 ETFs, can you suggest any reason not to also increase the number of instruments in which one is invested each month to 6? And similarly, to 12 for the 20 ETF portfolio? It struck me that increasing the tradeable instruments in the portfolio isn’t actually diversifying if one can only ever be long three of those at any given time.
Would be interested to hear your thoughts on this . . .
As you know, anytime you begin to introduce changes you increase the chance of curve fitting so my first inclination is not to change it. However, I would perform a study testing a full range of top instruments (say 1,2,3…10) simply to see how stable the results are. I would also do this across each of the portfolios. Then I could see how selecting the top three instruments within the 5-ETF portfolio, the 10-ETF portfolio and 20-ETF portfolio performs. I would guess off the top-of-my head that you would find that increasing/decreasing the number of tradable instruments will directly affect the total return and drawdown while the the portfolio remains profitable. I have not tested this however.
My impression is the purpose to increasing the total number of tradable instruments is not to increase diversification, but to increase the potential for total return.
Would you be willing to share the TS code or give us an overview of how the code works?
Apparently TS can only trade data1. How do you initiate trades in alternate data streams based on a filter?
The point that Basha makes is about curve fitting. Not only can you curve fit by selecting the PARAMETERS of your system (like the length of averages; threshold values etc.), but also by selecting TRADING INSTRUMENTS that perform well under your system rules and then run your system on those instruments only.
The question is whether your system really identifies an edge or just a statistical fluke that appears in a few instruments.
If there is a general edge (here the assumption is that strength in the past is likely to be followed by further strength in the future) it is reasonable to expect that this behavior shows up in almost any instrument. So if you randomly pick the ETFs to run the system on you should get good results most of the times. If not, well then it is highly likely that you didn’t find a general edge and that the “Ivy 5 Portfolio” or “Ivy 10 Portfolio” could be a curve fit selection.
As you suggested a good way to test the edge is to randomly select 5 ETFs and repeat this process several times as a Monte Carlo simulation.
I don’t know what you meant with “If you randomly select 5 from a universe of 100, you are not following the idea of selecting 5 that are indicating a positive up trend in an uptrending market.”
The “Ivy 5 Portfolio” is the same all the time. They are not replaced by other ETFs, so there is no “selecting 5” once the initial choice was made.
Or am I missing your point?
I’ve been wondering a lot about this recently, TK. I think what you said about curve fitting here is spot on. However, do we also have to watch out for curve-fitting by the criteria used to select trade candidates for the rotational system?
In a nebulous way, this is kind of what I am getting at. Monte Carlo simulation basically says trade #X could have been trade #Y–it’s just by luck that they ended up ordered as they did. Therefore, to get a better feel for how a system might perform, let’s randomize the order of trades and do it 100s or 1000s of times and then take averages for the equity curves and drawdowns.
When a rotational system has identified trades through a position scoring algorithm, though, it is identifying one and only one set of candidates. For some reason, this doesn’t feel entirely right to me–it feels like we could be leaving the door open to “fluke.”
Maybe you are mixing things up a little. Please allow me to “unmix” what I understood from your comment (sorry, if you meant it differently and you already know what I am going to write).
I am refering to “do we also have to watch out for curve-fitting by the criteria used to select trade candidates for the rotational system?”:
Depending on what you meant the answer is “yes”… =;-)
a) Yes, selecting the 5 ETFs that the system is performed on can be curve fitting (as described in my comment above).
b) Yes, the design of the system rule(s) that pick a max. of 3 out of the “starting 5” can also be a source of curve fitting (i. e., calculation factors, thresholds levels, # of ETFs to pick, etc.).
Refering to “Monte Carlo simulation basically says trade #X could have been trade #Y–it’s just by luck that they ended up ordered as they did.”:
Yes, the assumption is that trade #X does in no way influence the outcome of trade #Y. Therefore #Y might as well have happened before #X. Personally I don’t think this is 100% correct, because I tend to believe that winners and losers are somewhat clustered. For example you might have several winners in a row during a bullish market phase and then a string of losers when the market gets choppy or bearish. So it might be somewhat unrealistic to mix the order of the trades in a Monte Carlo simulation completely by random (but elaborating on that would lead to far for now).
Just beware that the Monte Carlo simulation that I talked about in the previous comment was not mixing the trades, it was mixing the ETFs that are in the “starting 5”. For each simulation run a set of 5 would be picked by random out of all suitable ETFs (maybe 100 to 200). Then you simulate the system over a certain time period and leave the order of trades untouched. But on the next simulation run you would do the same thing with a different set of 5 ETFs. So no shuffling of trades, but shuffling of traded instruments that are presented to the system rules.
Regarding “when a rotational system has identified trades through a position scoring algorithm, though, it is identifying one and only one set of candidates. For some reason, this doesn’t feel entirely right to me”: In my opinion it is OK for a system to choose the trades it wants to take or ignore. This decision may also very well be based not only on the instrument itself, but also on the behavior of the other instruments in the mix. You probably don’t like the idea that at a specific moment ETF “XYZ” would have produced a trade if combined with ETFs “A”, “B”, “C” & amp; “D”, but that it would NOT have produced a trade if combined with ETFs “E”, “F”, “G” & amp; “H”. This is one effect that the choice of the “starting 5” has. But if the “position scoring” really has some kind of edge then it will tend to pick the best of all available trades. Sometimes the alternatives matter. Just like you might have picked a different girlfriend if there would have been some super models available in the “starting 5″… =;-)
P. S. No offence – you certainly picked the best girl in the world. 🙂
You make a good point about an assumption for Monte Carlo testing that all trades be independent. What kind of statistical test could you run to check for this?
On a related note, I sometimes struggle with whether to run a backtest including only the first buy/sell signal or whether to include every buy/sell signal as a trade. For example, consider a 20-day breakout system where today we get a new high followed by new highs tomorrow and the day after. Most backtesting would take today’s signal and not allow for “redundant” signals of tomorrow and the day after. Certainly a challenge would be how to position size if you were to allow for redundant signals but I often think “is there anything inherently different between today’s new high and tomorrow’s or the day after?” If you believe in mean reversion then you say yes–tomorrow’s is more likely to be followed by a pullback and the day after tomorrow is even more likely to be followed by a pullback. The fact that trend systems work sometimes means mean reversion does not always hold, though, which means each signal should be included in the backtest.
Any thoughts on this concept of redundant signals?
The other big issue I see here is how to validate a position scoring algorithm. Consider a simple one-rule trading system based off a 20-MA, for example. I think it’s critical to optimize in order to know performance of the 20-MA is not a fluke. How does the system perform with MA periods between 10-30 by increments of two, for example? If I plot performance vs. MA period then I shouldn’t see a spike high at 20 surrounded by losses. I want to see a high plateau region with 20 roughly in the middle. This suggests that even neighboring values of MA period traded successfully in the past, which makes me think the edge might persist into the future.
I think all trading rules and filters can be studied this way (the technical term for this process is “evolutionary operation”). How would this apply to validation of the position scoring algorithm itself, however?
I don’t know about any kind of test for the “clustering” characteristics of trades. For most purposes the normal MC method should do OK, but I find it inportant to be aware of the assumptions that any method is based on and treat the results with the appropriate grain(s) of salt.
As for your 2nd question regarding “redundant” signals:
The answer depends on what you are examining.
& # 8211; If you examine whether a system has an edge then you need to simulate a trade for any valid signal that is produced. You don’t want the start of a simulated trade to depend on whether or not another trade has already ended (because you will have different trades to compare with every time you change the exit rules, so that you will not know if the exit rule in itself is better or simply better trades happened to get started). Of course you could add a rule to your system that prevents giving any further signals until some kind of condition is met thereby reducing the number of VALID signals.
& # 8211; If you examine what kind of performance you would get from trading the system you MUST simulate in your backtest exactly what would have happened in a real account. So if you would take the first and any following signals in your account then you simulate that. If you would only take the first signal then this is what you simulate.
Just beware that any skipping of VALID signals is adding random, which is pretty bad. Each trade that you take or simulate should be independent from any other trade that’s going on at the same time. If you don’t take a trade after a VALID signal for any reason then you can easily get into trouble.
Last thing: You can validate the scoring algorithm by running a series of MC simulations wit the same set of instruments (“starting 5”), but instead of the scoring algorithm you pick 3 ETFs by random each time a reshuffle is possible. Repeat that 1000 times and then compare the key figures that you get from the scoring algorithm (expectancy, max. DD, …) with the range that the random picks produced. If your algorithm does NOT end up in the top range for each of the key figures it probably doesn’t have much merit (if any) and you might as well make random picks.
Hope that helped,
Ah a new week so renewed potential for understanding, right?
Two thoughts on this post, TK. First:
& gt; b) Yes, the design of the system rule(s) that pick a max. of 3 out of.
& gt; the “starting 5″ can also be a source of curve fitting (i. e., calculation.
& gt; factors, thresholds levels, # of ETFs to pick, etc.).
If even the number of trades to take may be a source for curve.
fitting then I start to wonder if maybe the whole concept of a.
position scoring algorithm for rotation trading is invalid with regard.
to backtesting. I generally think about keeping all factors but.
one constant and then plotting some metric of performance vs.
different values of the variable. If the variable is “Top N tickers”
then it seems far too granular for comparison purposes. Does it.
make sense to compare results from “Top 1” to “Top 2” to “Top 3?”
It seems like the standard error bars might be way too large.
& gt; Just beware that the Monte Carlo simulation that I talked about.
& gt; in the previous comment was not mixing the trades, it was mixing.
& gt; the ETFs that are in the “starting 5″. For each simulation run a.
& gt; set of 5 would be picked by random out of all suitable ETFs.
& gt; (maybe 100 to 200).
It sounds like you’re suggesting comparing the equity curve.
generated by taking the Top 3 each month with an equity.
curve generated by taking three randomized tickers each.
month. How do you compare this, though? There is only.
one Top 3 but there are C(n,3) randomized three where.
n = total number of tickers from which to trade (C denotes.
combinations as opposed to permutations).
>>Ah a new week so renewed potential for understanding, right?
>>If even the number of trades to take may be a source for curve.
>>fitting then I start to wonder if maybe the whole concept of a.
>>position scoring algorithm for rotation trading is invalid with regard.
>>to backtesting. I generally think about keeping all factors but.
>>one constant and then plotting some metric of performance vs.
>>different values of the variable. If the variable is “Top N tickers”
>>then it seems far too granular for comparison purposes. Does it.
>>make sense to compare results from “Top 1″ to “Top 2″ to “Top 3?”
>>It seems like the standard error bars might be way too large.
Don’t get too frustrated, but ANY part of a trading system can be used to curve fit (anything that has an effect can be changed so that the outcome is “better”). But that’s not the real issue. What matters is whether or not it is likely that “new” data (i. e., the real trades that you might take) will show a performance similar to your backtest.
“New” data could be either data not used for the system design so far or future testing in real-time. Typically people use up so much data for the design that there’s not much data left to produce a sufficient number of trades for verification purposes. Real-time testing can have the disadvantage that it may take months or years to get a sufficient number of trades. You may want to take a look at the comments on one of the previous articles here called “Measuring Success: Key Performance Metrics”. Never underestimate the number of trades to fulfill the requirement to be “sufficient”!
>>It sounds like you’re suggesting comparing the equity curve.
>>generated by taking the Top 3 each month with an equity.
>>curve generated by taking three randomized tickers each.
>>month. How do you compare this, though? There is only.
>>one Top 3 but there are C(n,3) randomized three where.
>>n = total number of tickers from which to trade (C denotes.
>>combinations as opposed to permutations).
Here’s how you do it: Let’s say you test the years 2001 to 2005 (60 months). You always have the same 5 ETFs, but on a monthly basis you pick 3 ETFs by random that you hold for the next month. Do this 60 times and you have the FIRST simulation run. Take note of whatever metrics are important to you (i. e., expectancy). Now you start again with 2001 to simulate 60 trades where you again pick the 3 ETFs by random. Most of the 60 trades in this second run should be different than the ones in the first run. Keep doing that until you have a “large” number of runs (i. e., 1000 runs). Then you simulate the 60 months with the rule how to pick the 3 ETFs in effect. This is what you compare to what the other 1000 runs produced (average, standard deviation). If your rule based result is not more than 1 standard deviation (the more the better) away from the average then it’s highly likely that it adds NO VALUE to your system.
But if it HAS VALUE then it might be that this rule is curve fit to the “starting 5” (or the “starting 5” to the selection rule). In order to find that out you can do what was actually the suggestion that I wrote above:
Pick by random the “Starting 5” out of all.
200 ETFs and then apply the rules how to pick the top 3 on those 5 (the same 5 for each of the 60 months). This gives you one run. Then you make another random pick and again simulate the 60 months to get run #2. Repeat that and then compare the “Ivy 5” with the 1000 random runs. This shows you whether the “Ivy 5” are the only ETFs that produce good results. If the system rules should really HAVE VALUE then it shouldn’t matter much which starting 5 you use. Beware if there are only a few runs that produce staisfactory results, because then the “Ivy 5” might be a curve fit selection.
Clear or even more confused. =;-)
P. S. Did you see that I wrote another reply to you at the very bottom?
Hi AnTZ_TK and Mark,
Very interesting your discussion and really insightful.
For me there’s 2 main issues on this topic that I wopuld like to ear Jeff’s opinion:
1. ETF replay doesn’t give me confidence on their data/results and so it’s not a tool that I’ll use.
2. We curve fit either if we choose the best equities for a set of rules or the best rules for a set of equities.
@AnTZ_TK wrote: “The point that Basha makes is about curve fitting. Not only can you curve fit by selecting the PARAMETERS of your system (like the length of averages; threshold values etc.), but also by selecting TRADING INSTRUMENTS that perform well under your system rules and then run your system on those instruments only.”
That is exactly what they have done and it is not onoly curve-fititng but borderline cheating.
This whole thing is based on Post Hoc fallacy.
@Basha: I think we have a plethora of different discussion points here.
MetaStock advertises a software package with dozens of preloaded systems. You can test a system on a wide variety of tickers, find the tickers that perform well with a particular system, and then trade the system going forward.
Do you see anything wrong with that logic?
Yes, it is called survivorship bias. You should take the mean return of a specific system performance for a great number of tickers, form a distribution of means and then test if the mean of the new distribution could have been achieved by chance. Otherwise you are curve-fitting to ticker selection. This is also what the Ivy portfolio did. You should read the book by Aronson.
You asked what is wrong with the logic that MetaStock advertises. Try to look at it that way: You sit a million monkeys in front of a typewriter. After watching them hacking away on their keyboards for a while would you pick the monkey that “wrote” something that actually is correct English and offer him a job as a professional writer for a newspaper.
In other words: throw enough symbols on any kind of “system” and you will have some that show a profitable backtest. But the million dollar question is: Does that have any predictive value regarding FUTURE profits or was it just a result of random that doesn’t give you any indication of future outcomes?
Therefore I second Basha’s testing suggestion and also recommend Dr. Aronson’s book “Evidence-Based Technical Analysis”.
TK–I do see your reply at the bottom, here. The flip side of that approach to backtesting (which I disagree with, too) is that every ticker may have its own personality due to the institutions that trade it. This would allow for certain strategies to work on some tickers but not others.
With regard to your post above, I’m going to mull it over for a few days. I hope to understand better if I can sleep on it a few times.
I did read Aronson’s book a few years ago. Good stuff but not very encouraging as far as finding systems that really work, as I remember. Now that I’m working toward putting all the pieces of system development together, though, I see it *is* that difficult and I see how many alluring dead ends await to trap me in systems I might think are likely profitable that actually are fluke.
Basha, thanks to your insightful comments on this thread too.
Thanks to Jeff as well for posting the Ivy Portfolio article in the first place!
We had an outstanding discussion in the comments below, TK, but upon rereading this over a month later I want to focus on another point. Você escreve:
& gt; If there is a general edge (here the assumption is that strength in the past is likely to be.
& gt; followed by further strength in the future) it is reasonable to expect that this behavior.
& gt; shows up in almost any instrument.
Isn’t this claim debatable?
As a challenge, I will state the hypothesis that each ticker has its own trading personality. Why might this be? I think we would all agree that institutions are the big players that command market action. For any ticker, the bulk of trading activity is commanded by X institutions. Suppose a number of those institutional traders, for example, follow 50/200-SMA crossovers. We are likely to see some edge when using a 50/200-SMA crossover trading system for that ticker. Different tickers are traded by different institutions (institutional traders) and so different tickers may be more or less influenced by different technical [or other types of] criteria applied by those traders. For this reason, I may find a trading system that works well for one ticker but no others. This trading may continue to work well for this one ticker until the institutions that trade that ticker significantly change or until the traders responsible for those institutions’ trades significantly change (e. g. fund managers are replaced).
Quais são seus pensamentos?
fyi, ETFreplay return should not be tested against other software — the returns should be tested against a source that has correct data in the first place. Such data is available on the ETF providers website — such as ishares and vanguard.
ETFreplays data matches those websites so if your other software doesn’t match ETFreplays — it is likely because your software is incorrect. or use Morningstar data. I tested 200 of the largest ETFs vs morningstar and they were all correct. clearly, effort is made to ensure data accuracy.
[…] would happen if we took these four ETFs and traded them with the trading logic used with the Ivy-10 trading system? Using ETF Replay I generated the following […]
Interesting stuff here. I’ve been looking at the Gone Fishin’ portfolio and the Permanent Portfolio and the Ivy but have not been completely impressed, as they all look like they need some tweaks. The 5 month MA makes sense, though I might change that to 200-day, simply because that is widely followed and triggers HFTs (high frequency trades based on algos) and is a compromise between 5 and 10 month MAs. I like the idea of combining a momentum strategy with asset diversification. What I have in mind is bonds, stocks (domestic and world), commodities (including gold), and REITS (domestic and world) as a basic asset structure. Add sector ETFs and country ETFs as an option to boost returns. Also as an option, add inverse (but not leveraged) ETFs. You want the best in class in each category, looking at 1-month, 3-month and 6-month returns, with more emphasis on 3-month. But also look at the charts because some of the ETFs that are lower down on the scale might be touching support and breaking out. Those would be better than the ones that are top ranking but overbought and headed for a correction. Monitor monthly or quarterly. Quarterly might be a better idea as you give things time to play out and don’t act hastily.
Ross, these are all great ideas to test. I tested a few ideas in this post. Some of your ideas could be tested in ETFReplay. In future articles I plan on testing how adding inverse ETFs changes the performance.
[…] do is expand to a basket of ETFs. In Jeff Swanson’s post “The Ivy Portfolio” (systemtradersuccess/the-ivy-portfolio/), he mentions use of these five […]
The IVY articles and portfolio risk/return are always good reads.
On the IVY 10 you use GSC and DBC. These both broad commodity tracking ETFs/ETNs so the back-test is backing doubling up on the allocation on commodities. It would be interesting to see if you remove one of these then run the back test again.
I think everyone is looking at ETFreplay and momentum in general, incorrectly. Momentum in general has no predictive quality in and of itself. One can simply confirm this by using the ETFreplay screener and choosing the top ETF out of all available. My back tests show this to be far less effective than using a smaller basket of uncorrelated ETF’s. I think you need to think of ETFreplay as a modified bye and hold strategy. You must want to hold all of the individual assets but you just don’t want to hold them in a down trend. You also want concentrate your money each month in the assets that are presently doing the best.
ETFreplay is without a doubt a curve fit, but that doesn’t mean it doesn’t work.
First of all, you should only be choosing asset classes that you want to invest in.
You want uncorrelated funds so that there is always something strong in any market condition. The Ivy Portfolio works because they are uncorrelated. An all currency momentum strategy doesn’t work well because sometimes all the currencies available as ETF’ go down together.
You also want types of funds that have lengthy trends. For instance. individual commodities tend to be poor funds to pick because the trends typically don’t last for months on end.
You also need funds that work well together. 2X funds rarely work well with 1X funds because of the volatility difference.
Remember, ETFreplay is looking for RELATIVE strength. Relative strength is a curve fit.
So yes, ETFreplay is very much a curve fit. Momentum is just investing in an asset in a uptrend. In my opinion it still works and beats bye and hold by a mile.
[…] futures? They will work on anything. Check out "The Ivy Portfolio" in Google or The Ivy Portfolio | System Trader Success for […]
[…] About a month ago, I wrote a post for One Step Removed about the Ivy Portfolio Allocation System. My post was based on the work done last year by Jeff Swanson from System Trader Success. Swanson wrote a very interesting article that provided the details on how to trade The Ivy Portfolio. [& # 8230;]
[…] reading Jeff’s article on The Ivy Porfolio over at System Trader Success, I have not been able to get the concept out of my head. I even wrote […]
Last attempt, it is removing my syntax which makes my scenarios appear illogical.
Obrigado Jeff. I am trying to understand the constraints of the GTAA 13 AGG 3 system. Faber writes “The assets are only included if they are.
above their long-term moving average, otherwise that portion of the portfolio is moved to cash. We also include the effects of only investing in the top three out of thirteen assets. & # 8221;
I don’t see how this is possible, surely I am missing something obvious. If you are investing only in the top 3 of the 13 assets then how is that not contradictory to “otherwise that portion of the portfolio is moved to cash”? Imagine you have $3 to invest. I am trying confirm what happens in each scenario:
1. All 13 10 Month SMA then you are 33% in that 1 asset and rest in cash?
3. 3 Assets > 10 month SMA and 10 assets < 10 month SMA then you are 100% invested with 1/3 in each asset in which case you have 0 in cash which contradicts the rule stated before.
Thanks for any clarity.
Your questions are a bit odd (some formatting lost in the posting?) but I think I can answer your questions and guess at what you meant. I believe the answers are as follows:
1. If all 13 are below the 10 month MA, then you are 100% in cash.
2. If, say, 6 are above the 10 month MA then you pick the best 3 of those 6 to invest in (and ditch other positions).
3. If only 2 of the 13 are above the MA then you are 33% cash and have positions in those 2.
Think of it like this:
1. Find “qualifying” ETFs from your list (i. e. above 10 month MA). Ignore the rest for now.
2. Rank the qualifiers using formula provided above.
3. Take top 3 qualifiers and allocate 33% to each. If list is smaller than 3, allocate 33% to each qualifier and hold the rest in cash until the next time you check the system.
Posts populares.
Atualização de RSI de 2 períodos do Connors para 2013.
Este indicador simples faz dinheiro de novo e de novo.
O portfólio Ivy.
Melhorando a estratégia do intervalo simples, parte 1.
Copyright © 2011-2018 pela Capital Evolution LLC. - projetado por prosperar temas | Alimentado por WordPress.
Por favor faça login novamente. A página de login será aberta em uma nova janela. Após o login, você pode fechá-lo e retornar a esta página.
System trader success ivy portfolio
The S&P 500 closed January with a monthly gain of 5.62% after a monthly gain in December of 0.98%. All three S&P 500 MAs are signaling "invested" and three of five Ivy Portfolio ETFs — Vanguard Total Stock Market ETF (VTI), Vanguard FTSE All-World ex-US ETF (VEU), and PowerShares DB Commodity Index (DBC) — are signaling "invested". In the table, monthly closes that are within 2% of a signal are highlighted in yellow.
The above table shows the current 10-month simple moving average (SMA) signal for each of the five ETFs featured in The Ivy Portfolio. We've also included a table of 12-month SMAs for the same ETFs for this popular alternative strategy.
For a fascinating analysis of the Ivy Portfolio strategy, see this article by Adam Butler, Mike Philbrick, and Rodrigo Gordillo:
Backtesting Moving Averages.
Over the past few years, we've used Excel to track the performance of various moving-average timing strategies. But now we use the backtesting tools available on the ETFReplay website. Anyone who is interested in market timing with ETFs should have a look at this website. Here are the two tools we most frequently use:
(requires a paid subscription)
Background on Moving Averages.
Buying and selling based on a moving average of monthly closes can be an effective strategy for managing the risk of severe loss from major bear markets. In essence, when the monthly close of the index is above the moving average value, you hold the index. When the index closes below, you move to cash. The disadvantage is that it never gets you out at the top or back in at the bottom. Also, it can produce the occasional whipsaw (short-term buy or sell signal), which we've seen most recently in 2016.
Nevertheless, a chart of the S&P 500 monthly closes since 1995 shows that a 10- or 12-month simple moving average (SMA) strategy would have ensured participation in most of the upside price movement while dramatically reducing losses.
Here is the 12-month variant:
The 10-month exponential moving average (EMA) is a slight variant on the simple moving average. This version mathematically increases the weighting of newer data in the 10-month sequence. Since 1995 it has produced fewer whipsaws than the equivalent simple moving average, although it was a month slower to signal a sell after these two market tops.
A look back at the 10- and 12-month moving averages in the Dow during the Crash of 1929 and Great Depression shows the effectiveness of these strategies during those dangerous times.
The Psychology of Momentum Signals.
Timing works because of a basic human trait. People imitate successful behavior. When they hear of others making money in the market, they buy in. Eventually, the trend reverses. It may be merely the normal expansions and contractions of the business cycle. Sometimes the cause is more dramatic — an asset bubble, a major war, a pandemic, or an unexpected financial shock. When the trend reverses, successful investors sell early. The imitation of success gradually turns the previous buying momentum into selling momentum.
Implementando a Estratégia.
Our illustrations from the S&P 500 are just that — illustrations. We use the S&P because of the extensive historical data that's readily available. However, followers of a moving average strategy should make buy/sell decisions on the signals for each specific investment, not a broad index. Even if you're investing in a fund that tracks the S&P 500 (e. g., Vanguard's VFINX or the SPY ETF) the moving average signals for the funds will occasionally differ from the underlying index because of dividend reinvestment. The S&P 500 numbers in our illustrations exclude dividends.
The strategy is most effective in a tax-advantaged account with a low-cost brokerage service. You want the gains for yourself, not your broker or your Uncle Sam.
Note : For anyone who would like to see the 10- and 12-month simple moving averages in the S&P 500 and the equity-versus-cash positions since 1950, here's an Excel file (xlsx format) of the data. If for some reason you cannot access the latest file, please email us and we will send you a copy. Our source for the monthly closes (Column B) is Yahoo! Finança. Columns D and F shows the positions signaled by the month-end close for the two SMA strategies.
In the past, we've recommended Mebane Faber's thoughtful article A Quantitative Approach to Tactical Asset Allocation. The article has now been updated and expanded as Part Three: Active Management in his book The Ivy Portfolio, coauthored with Eric Richardson. This is a "must read" for anyone contemplating the use of a timing signal for investment decisions.
The book analyzes the application of moving averages the S&P 500 and four additional asset classes: the Morgan Stanley Capital International EAFE Index (MSCI EAFE), Goldman Sachs Commodity Index (GSCI), National Association of Real Estate Investment Trusts Index (NAREIT), and United States government 10-year Treasury bonds.
As a regular feature of this website, we update the signals at the end of each month.
For additional insights from Mebane Faber, please visit his website, Mebane Faber Research.
Footnote on calculating monthly moving averages: If you're making your own calculations of moving averages for dividend-paying stocks or ETFs, you will occasionally get different results if you don't adjust for dividends. For example, in 2012 VNQ remained invested at the end of November based on adjusted monthly closes, but there was a sell signal if you ignored dividend adjustments. Because the data for earlier months will change when dividends are paid, you must update the data for all the months in the calculation if a dividend was paid since the previous monthly close. This will be the case for any dividend-paying stocks or funds.
No comments:
Post a Comment