Thursday 22 March 2018

Estratégias de negociação de código r


Tarefa Algorítmica de Negociação em R.


Nesta publicação, vou mostrar como usar R para coletar os estoques listados em leais3, obter dados históricos do Yahoo e depois executar uma estratégia de negociação algorítmica simples. Ao longo do caminho, você aprenderá alguma raspagem na web, uma função atingindo uma API de finanças e um htmlwidget para fazer um gráfico de séries de tempo interativo.


Para esta publicação, um algoritmo de negociação é definido como um conjunto de regras que desencadeiam um evento de compra ou venda, em vez de um modelo preditivo ou uma previsão de séries temporais. Este é o tipo mais simples de troca de algo, mas se você estiver interessado em investigar mais profundamente em finanças com R, eu encorajaria você a tomar o curso da DataCamp na modelagem de uma estratégia de negociação quantitativa em R.


Fundo.


Em 2018, comecei a investir um pouco em loyal3. O seu serviço é incomum e um ótimo lugar para iniciar sua jornada de investimento. Em vez de cobrar ao investidor por negociações, leal3 cobra as empresas para listar em sua plataforma. A premissa é que as pessoas que gostam do serviço de uma empresa também comprarão o estoque e, assim, se tornarão defensoras fortes da marca. Fazer a plataforma mais atraente é que você pode comprar partes fracionárias. Então, você pode entrar nesse estoque de $ 800 amazon por apenas US $ 10 e comprar outra fração de US $ 10 cada vez que você tiver um pouco de dinheiro extra no final do mês. Claro que há custos de fricção, uma vez que você precisa negociar no Windows e seu portfólio inteiro está limitado.


70 ações, mas leais3 representa uma maneira divertida e de baixo custo para explorar o treinamento de capital. Você pode colocar a pele real no jogo por apenas US $ 10!


Para ser claro, tenho as contas típicas de aposentadoria e investimento, mas eu gosto da interface limpa do leal no aplicativo e da falta de taxas. Eu acabo checando minha carteira de lealdade e diversão mais frequentemente do que meus fundos mútuos, simplesmente porque é fácil e divertida ver o desempenho dos estoques que escolhi diretamente.


Os estoques disponíveis em loyal3.


Configurando seu espaço de trabalho.


Para começar, carregue as bibliotecas no seu ambiente. Eu quase sempre uso rvest for web scraping estes dias. Existem outros pacotes que funcionam, incluindo o RSelenium, mas eu gosto do quão fácil pode ser executado.


O segundo pacote, pbapply, é opcional porque simplesmente adiciona uma barra de progresso às funções de aplicação. Como você poderia estar raspando centenas de páginas da web, uma barra de progresso pode ser útil para estimar o tempo.


Em seguida, a TTR é um pacote que acabei de começar a explorar. A biblioteca é usada para construir "Regras de Negociação Técnicas". Embora você aprenda um algoritmo de negociação simples nesta publicação, o pacote TTR pode realizar cálculos mais sofisticados e vale a pena aprender.


A biblioteca dygraphs é um invólucro para uma biblioteca de gráficos de JavaScript rápida e aberta. É um dos htmlwidgets que torna o R mais dinâmico e faz parte de um arquivo html em vez de uma imagem estática. Por fim, o pacote lubridate é usado para facilitar a manipulação da data.


Coleção de dados.


Todos os estoques loyal3 estão todos listados em uma única página. Antes de pesquisar os preços diários individuais das ações para construir seu algoritmo de negociação, você precisa coletar todos os tickers disponíveis. A primeira coisa a fazer é declarar stock. list como uma string de URL. O próximo uso read_html () para que sua sessão R crie uma sessão na Internet e colete todas as informações html na página como um conjunto de nós XML. A página CSS tem uma ID chamada "nome da empresa". Use isso como um parâmetro ao chamar html_nodes () para selecionar apenas os dados XML associados a este nó. Por fim, use html_text () para que os valores de texto reais para os nomes das empresas sejam coletados.


Para examinar os estoques disponíveis em loyal3, você pode imprimir o objeto stocks. names no seu console. Isso retorna o nome da empresa como um vetor de texto.


Para pesquisar os preços das ações, você precisa primeiro obter o símbolo do ticker. Quando você está no site leal3, você pode clicar no tile da empresa para carregar uma página com um símbolo de ticker e outras informações da empresa.


Usando html_nodes () em ações, você puxa todos os nós marcados com um "Em HTML" & lt; a & gt; tag define um hiperlink que é usado para vincular a página de um formulário a outro. Dentro da tag de hiperlink, o "href" refere-se ao endereço de URL exato. Então, html_attr () irá extrair o URL de TODOS os links na página, se você passar em "href ...".


Depois de fazer uma inspeção manual, achei que os links 54 a 123 na página representam as páginas da empresa que eu preciso para raspar as informações do ticker. A última linha usa paste0 () para concatenar a seqüência de URL base "loyal3" para as páginas específicas da empresa, como "/ WALMART". Por exemplo, loyal3 / WALMART:


Em cada uma das páginas da empresa, há uma descrição, um preço de fechamento recente e o ticker. Todas as páginas da empresa são organizadas o mesmo, de modo que a função personalizada get. ticker () pode ser usada para extrair o símbolo do ticker.


Dentro de uma página da empresa, há uma tabela chamada "preço-marcador". A função irá navegar para uma página da empresa, identificar a tabela apropriada, extrair o texto com html_text (). Por fim, usando sub () juntamente com a expressão regular ^ ([[: alpha:]] *). * E \\ 1 manterão todos os caracteres alfabéticos. O resultado é que todos os caracteres especiais, como $, e quaisquer caracteres numéricos, como o preço de fechamento, são removidos. Como a função lê cada uma das 70 páginas, ela somente coletará o ticker de estoque.


A página de estoque leal3 para Alibaba, onde você vê a tabela que contém o ticker do estoque, BABA, está abaixo do texto em negrito.


Armado com sua função personalizada, use pblapply () para aplicá-lo a cada um dos stock. links que contêm a página de cada empresa. O objeto resultante, stock. tickers, é uma lista de tickers de ações individuais com cada elemento correspondente a uma empresa individual.


Uma maneira de alterar uma lista de elementos em um objeto plano é com do. call (). Aqui, você está aplicando rbind para row bind cada elemento de lista em um único vetor. Por fim, você cria um quadro de dados com o símbolo e a informação do nome da empresa.


Para ser consistente em sua análise, você pode querer limitar a quantidade de informações históricas que você coleciona em cada estoque. A função Sys. Data () armazenará um objeto de data como ano, mês e dia. Usar anos com um número inteiro é uma maneira de subtrair uma quantidade de tempo específica do objeto start. date.


Para obter os dados de finanças do Yahoo, o objeto da data deve ser alterado para objetos de personagem simples sem um traço. Usando a função de substituição global gsub () em start. date e end. date mudará a classe e simultaneamente removerá traços. Dentro de gsub (), passe o padrão de personagem para procurar, então os caracteres de substituição. Neste caso, o padrão de substituição é um caractere vazio entre citações. O último parâmetro é o objeto ao qual gsub () será aplicado.


A função TTR () getYahooData () aceita um símbolo de estoque e uma data inicial e final. A função retorna um quadro de dados que possui informações de séries temporais. Cada linha é uma data e as colunas contêm informações como o "Por favor", "Alto", "Por favor" e "encerrando" o preço por uma equidade. Como você está pesquisando várias empresas, você pode usar o lapply () ou o pblapply (). Passe no vetor dos símbolos da empresa, então a função, getYahooData (), e depois a data da informação. Os objetos de data são parâmetros reciclado sempre que getYahooData () é aplicado a um símbolo de estoque.


Para fazer a seleção da lista retornada, stocks. ts, mais fácil de navegar, você pode adicionar nomes aos elementos da lista. O uso de nomes com o objeto stocks. ts declara os nomes como o vetor de símbolo $ original.


Ao trabalhar com grandes listas, eu gosto de examinar o objeto resultante para garantir que o resultado seja o que eu esperava. Agora que os elementos têm nomes, você pode fazer referência diretamente a eles. Neste exemplo, você está examinando as 6 primeiras linhas para AMC Entertainment Holdings (AMC). Usar head () na lista ao fazer referência a $ AMC retornará uma parte da série temporal para este estoque:


Examinando os dados de estoque.


Quando eu ouço as notícias financeiras, os comentadores geralmente se referem a gráficos. Apesar da negociação de alta freqüência e da gestão ativa realizada por outros, muitos pequenos investidores ainda se referem a gráficos para obter informações. O objeto da série temporal pode ser exibido rapidamente com o enredo. Passe na lista referente ao elemento nomeado, como $ AMC e depois a coluna que deseja exibir, aqui $ Close.


O enredo anterior é estático e não muito interessante.


Vamos usar uma biblioteca de JavaScript para criar um gráfico que você possa explorar. Neste trecho de código, você pode observar o "% & gt;%" ou operador de tubulação. O operador de tubulação é uma boa maneira de escrever um código conciso. Ele encaminha um objeto para a próxima função sem forçar você a reescrever um nome de objeto como você fez anteriormente nesta publicação.


Neste exemplo, você cria um dygraph referente ao estoque do Twitter, $ TWTR e, em seguida, a coluna que deseja traçar, $ Close. Dentro do dygraph, main adiciona um título especificado entre as cotações. Usando o "% & gt;%" este objeto inteiro é encaminhado para a próxima função dyRangeSelector (). Você pode especificar um intervalo de datas padrão usando c () com uma string de data de início e fim. O objeto HTML resultante é uma série de tempo dinâmico para o estoque do Twitter com um controle deslizante de data na parte inferior.


Lembre-se, para alterar o patrimônio exibido, altere o símbolo do ticker na lista stocks. ts e, em seguida, o título do gráfico.


Este é um dígrafo básico para o estoque do Twitter.


Uma Estratégia de Negociação Simples: Trend Following.


Os comerciantes de alta freqüência e os hedge funds usam modelos sofisticados e abordagens baseadas em regras para executar negócios. Se você quiser saber mais, sugiro visitar a parapian para abordagens avançadas. Para abordagens mais simples, comece com esta página na Investopedia.


No código abaixo, você irá visualizar uma estratégia de negociação de impulso simples. Basicamente, você gostaria de calcular as médias móveis de 200 dias e 50 dias para um preço de ações. Em qualquer dia em que a média móvel de 50 dias esteja acima da média móvel de 200 dias, você compraria ou manteria sua posição. Nos dias em que a média de 200 dias é superior à média móvel de 50 dias, você venderia suas ações. Esta estratégia é chamada de estratégia seguindo estratégia. A natureza positiva ou negativa entre as duas médias médias temporais representa o impulso do estoque.


O pacote TTR fornece SMA () para calcular a média móvel simples. Neste trecho de código, você está examinando os primeiros 6 valores para as médias móveis de Twitter e 200 dias. SMA () funciona passando os dados da série temporal para um estoque e uma coluna específica como Close. Este é um único vetor de preços de fechamento do estoque TWTR. O segundo parâmetro é um número inteiro que representa o número de observações para a média móvel. Sem usar head (), a função SMA () retornará todos os valores.


Agora que você examinou detalhadamente a função da média móvel, você precisa se inscrever para cada uma das 70 ações. stocks. ts é uma lista de 70 quadros de dados contendo dados de estoque individuais. A quarta coluna de cada quadro de dados contém o preço de fechamento que queremos usar para as médias móveis.


A função personalizada mov. avgs () aceita um único quadro de dados de estoque para calcular as médias móveis. A primeira linha seleciona os preços de fechamento porque indexa [, 4] para criar stock. close. Em seguida, a função usa ifelse para verificar o número de linhas no quadro de dados. Especificamente se o nrow no quadro de dados for inferior a (2 * 260), então a função criará uma moldura de dados de médias móveis com “NA”.


Eu escolhi esse número porque há cerca de 250 dias de negociação por ano, então isso irá verificar se a série temporal tem cerca de 2 anos ou mais de duração. Loyal3 às vezes pode ter acesso a IPOs e, se o estoque for recém-público, não haverá dados suficientes para uma média móvel de 200 dias. No entanto, se o valor nrow for superior a 2 * 260, a função criará um quadro de dados com os dados originais juntamente com médias móveis de 200 e 50 dias como novas colunas. Usando colnames, eu declaro os nomes das colunas. A última parte da função usa full. cases para verificar os valores na coluna média móvel de 200 dias. Quaisquer linhas que não tenham um valor são descartadas no resultado final.


Armado com esta função mov. avgs (), você pode usar o pblapply () para adicionar os cálculos da média móvel a cada um dos 70 quadros de dados.


Use o código abaixo para visualizar as médias móveis de um estoque usando um dígrafo. Mais uma vez, esse código está usando o operador "% & gt;%" para encaminhar objetos. A função dygraph () aceita a estrutura de dados stocks. ts $ FOX. Especificamente, o quadro de dados é indexado pelo nome da coluna com c ('sma_200', 'sma_50'). Este objeto é passado para dySeries () nas próximas 2 linhas. Você pode se referir a uma coluna por nome para que dySeries () traçam uma linha para os valores "40 e 40" nas linhas 2 e 3. Este objeto é reenviado novamente para o dyRangeSelector () para ajustar a altura do seletor. Por fim, adicionei algum sombreamento para definir períodos em que você quisesse comprar ou manter o patrimônio líquido e um período em que você deveria ter vendido suas ações ou ficado afastado, dependendo da sua posição.


Aqui está o resultado final em uma série de tempo interativa.


As médias móveis FOX com regiões sombreadas para comprar / segurar versus vender.


Conclusão.


Como comerciante algorítmico de brotação, você não precisa traçar todos os 70 compartilhamentos. Em vez disso, você gostaria de executar o código todos os dias e adicionar uma maneira programática para identificar estoques que se encaixam no método baseado em regras, "compre se a média móvel de 50 dias está acima da média móvel de 200 dias". À medida que você revisa o gráfico anterior, a seção verde é uma hora em que você compraria o capital da FOX. A seção vermelha representa o tempo para vender suas ações e não voltar a entrar.


Como o gráfico é interativo, você pode usar o controle deslizante para redimensionar o visual. Com base nesta abordagem simples de troca de algo, agora pode ser um bom momento para comprar FOX! 30 de dezembro de 2018 foi um dia de negociação em que a média móvel de 50 dias mudou US $ 0,01 maior do que a média móvel de 200 dias!


A seção ampliada da equidade FOX.


Claro, lembre-se de todos os investimentos podem perder valor. Para saber mais sobre finanças e trocas comerciais, cheque os cursos da DataCamp aqui.


O R Trader.


Usando R e ferramentas relacionadas em Finanças Quantitativas.


Arquivo para as estratégias de negociação & # 8216; & # 8217; Categoria.


Vinculando R para IQFeed com o pacote QuantTools.


O IQFeed fornece serviços de transmissão de dados e soluções de negociação que cobrem o mercado agrícola, energético e financeiro. É um fornecedor bem conhecido e reconhecido de feed de dados voltado para usuários de varejo e pequenas instituições. O preço da assinatura começa em torno de US $ 80 / mês.


Stanislav Kovalevsky desenvolveu um pacote chamado QuantTools. É um pacote tudo em um projetado para melhorar a modelagem de negociação quantitativa. Ele permite baixar e organizar dados históricos de mercado de várias fontes como Yahoo, Google, Finam, MOEX e IQFeed. O recurso que mais me interessa é a capacidade de vincular o IQFeed à R. I & # 8217; tenho usado o IQFeed há alguns anos e estou feliz com ele (eu não sou afiliado à empresa em nenhum caminho). Mais informações podem ser encontradas aqui. Eu procurei uma integração dentro de R por um tempo e aqui está. Como resultado, depois de executar alguns testes, mudei meu código que ainda estava em Python em R. Apenas por completude, aqui é um link que explica como baixar dados históricos do IQFeed usando o Python.


O QuantTools oferece quatro funcionalidades principais: Obter dados de mercado, armazenar / recuperar dados do mercado, traçar dados da série temporal e testar as costas.


Primeiro, certifique-se de que o IQfeed esteja aberto. Você pode baixar dados diários ou intraday. O código abaixo baixa os preços diários (Open, High, Low, Close) para a SPY de 1 de janeiro de 2017 a 1 de junho de 2017.


O código abaixo baixa dados intraday de 1 de maio de 2017 a 3 de maio de 2017.


Observe o parâmetro do período. Pode levar qualquer um dos seguintes valores: tick, 1min, 5min, 10min, 15min, 30min, hora, dia, semana, mês, dependendo da frequência que você precisa.


O QuantTools torna o processo de gerenciamento e armazenamento de dados do mercado de tiques fácil. Você apenas configura parâmetros de armazenamento e está pronto para ir. Os parâmetros são onde, desde que data e quais símbolos você gostaria de ser armazenado. Sempre que você pode adicionar mais símbolos e se eles não estiverem presentes em um armazenamento, o QuantTools tenta obter os dados da data de início especificada. O código abaixo salvará os dados no seguinte diretório: & # 8220; C: / Usuários / Arnaud / Documents / Market Data / iqfeed & # 8221 ;. Existe uma sub-pasta por instrumento e os dados são aved em arquivos. rds.


Você também pode armazenar dados entre datas específicas. Substitua a última linha de código acima com uma das seguintes.


Agora, você deseja recuperar alguns dos dados armazenados, basta executar algo como:


Observe que apenas os tiques são suportados no armazenamento local, pelo que o período deve ser & # 8216; assinalar & # 8217;


O QuantTools fornece a função plot_ts para traçar dados da série temporal sem fins de semana, feriados e intervalos overnight. No exemplo abaixo, primeiro recupero os dados armazenados acima, selecione as primeiras 100 observações de preços e, finalmente, desenhe o gráfico.


Duas coisas a notar: primeiro espião é um objeto data. table daí a sintaxe acima. Para obter uma visão geral rápida das capacidades de data. table, veja esta excelente folha de truques da DataCamp. Segundo, o parâmetro local é VERDADEIRO à medida que os dados são recuperados do armazenamento interno.


O QuantTools permite escrever sua própria estratégia comercial usando sua API C ++. Eu não vou elaborar sobre isso, pois este é basicamente o código C ++. Você pode consultar a seção Exemplos no site QuantTools.


No geral, considero o pacote extremamente útil e bem documentado. O único bit faltante é o feed ao vivo entre R e IQFeed, o que tornará o pacote uma solução de fim a fim real.


Como de costume, todos os comentários são bem-vindos.


BERT: um recém-chegado na conexão do R Excel.


Alguns meses atrás, um leitor me apontou essa nova maneira de conectar R e Excel. Eu não sei por quanto tempo isso aconteceu, mas nunca encontrei isso e eu nunca vi nenhuma postagem no blog ou artigo sobre isso. Então eu decidi escrever uma publicação, pois a ferramenta realmente vale a pena e, antes que alguém pergunte, eu não estou relacionado à empresa de nenhuma maneira.


BERT significa Basic Excel R Toolkit. É grátis (licenciado sob a GPL v2) e foi desenvolvido pela Structured Data LLC. No momento da redação, a versão atual do BERT é 1.07. Mais informações podem ser encontradas aqui. De uma perspectiva mais técnica, o BERT foi projetado para suportar a execução de funções R a partir de células da planilha do Excel. Em termos de Excel, ele é para escrever funções definidas pelo usuário (UDFs) em R.


Nesta publicação, não vou mostrar-lhe como o R e o Excel interagem através do BERT. Há muito bons tutoriais aqui, aqui e aqui. Em vez disso, quero mostrar-lhe como usei o BERT para criar uma torre de controle # 8222; para minha negociação.


Meus sinais comerciais são gerados usando uma longa lista de arquivos R, mas eu preciso da flexibilidade do Excel para exibir resultados de forma rápida e eficiente. Como mostrado acima, o BERT pode fazer isso por mim, mas eu também quero adaptar o aplicativo às minhas necessidades. Ao combinar o poder de XML, VBA, R e BERT, posso criar uma aplicação bem parecida e poderosa na forma de um arquivo Excel com código VBA mínimo. Em última análise, tenho um único arquivo do Excel reunindo todas as tarefas necessárias para gerenciar meu portfólio: atualização do banco de dados, geração de sinal, envio de ordens etc e # 8230; Minha abordagem poderia ser dividida nas 3 etapas abaixo:


Use XML para criar menus e botões definidos pelo usuário em um arquivo do Excel. Os menus e botões acima são essencialmente chamadas para funções VBA. Essas funções VBA estão envolvidas em torno de funções R definidas usando o BERT.


Com esta abordagem, posso manter uma distinção clara entre o núcleo do meu código mantido em R, SQL e Python e tudo usado para exibir e formatar resultados mantidos no Excel, VBA e amp; XML. Nas próximas seções, apresento o pré-requisito para desenvolver essa abordagem e um guia passo a passo que explica como o BERT poderia ser usado para simplesmente passar dados de R para Excel com um código mínimo de VBA.


1 & # 8211; Baixe e instale o BERT a partir deste link. Uma vez que a instalação foi concluída, você deve ter um novo menu de suplementos no Excel com os botões como mostrado abaixo. É assim que o BERT se materializou no Excel.


2 & # 8211; Baixe e instale o editor de UI personalizado: O Editor de UI personalizado permite criar menus e botões definidos pelo usuário na faixa de Excel. Um procedimento passo a passo está disponível aqui.


1 & # 8211; Código R: A função R abaixo é um código muito simples apenas para fins ilustrativos. Ele calcula e retorna os resíduos de uma regressão linear. Isto é o que queremos recuperar no Excel. Salve isso em um arquivo chamado myRCode. R (qualquer outro nome está bem) em um diretório de sua escolha.


2 & # 8211; functions. R em BERT: do Excel, selecione Add-Ins - & gt; Diretório inicial e abra o arquivo chamado functions. R. Neste arquivo cole o seguinte código. Certifique-se de inserir o caminho correto.


Isso está apenas fornecendo o arquivo RERT que você criou acima. Em seguida, salve e feche as funções do arquivo. R. Se você quiser fazer alguma alteração no arquivo R criado na etapa 1, você terá que recarregá-lo usando o botão BERT & # 8220; Recarregar arquivo de inicialização e # 8221; no menu Complementos no Excel.


3 & # 8211; No Excel: Crie e salve um arquivo chamado myFile. xslm (qualquer outro nome está bem). Este é um arquivo ativado por macro que você salva no diretório de sua escolha. Uma vez que o arquivo é salvo, feche-o.


4 & # 8211; Abra o arquivo criado acima no editor UI personalizado: depois que o arquivo estiver aberto, cole o código abaixo.


Você deve ter algo assim no editor XML:


Essencialmente, essa parte do código XML cria um menu adicional (RTrader), um novo grupo (Meu Grupo) e um botão definido pelo usuário (Novo botão) na faixa do Excel. Depois de concluir, abra myFile. xslm no Excel e feche o Editor de UI personalizado. Você deve ver algo assim.


5 & ​​# 8211; Abra o editor VBA: no myFile. xlsm insira um novo módulo. Cole o código abaixo no módulo recém-criado.


Isso apaga os resultados anteriores na planilha antes de lidar com novos.


6 & # 8211; Clique no botão Novo: Agora volte para a planilha e no menu do RTrader clique no & # 8220; Novo botão & # 8221; botão. Você deve ver algo como o que aparece abaixo.


O guia acima é uma versão muito básica do que pode ser alcançado usando o BERT, mas mostra como combinar o poder de várias ferramentas específicas para criar sua própria aplicação personalizada. Do meu ponto de vista, o interesse de tal abordagem é a capacidade de colar R e Excel, obviamente, mas também para incluir via XML (e lote) partes de código de Python, SQL e muito mais. Isso é exatamente o que eu precisava. Finalmente, ficaria curioso para saber se alguém tem alguma experiência com o BERT?


Estratégia de negociação: aproveitando ao máximo os dados da amostra.


Ao testar as estratégias de negociação, uma abordagem comum é dividir o conjunto de dados inicial em dados de amostra: a parte dos dados projetados para calibrar o modelo e fora dos dados de amostra: a parte dos dados utilizados para validar a calibração e garantir que o desempenho criado na amostra será refletido no mundo real. Como regra geral, cerca de 70% dos dados iniciais podem ser utilizados para calibração (isto é, na amostra) e 30% para validação (isto é, fora da amostra). Em seguida, uma comparação dos dados de entrada e saída da amostra ajuda a decidir se o modelo é robusto o suficiente. Esta publicação pretende dar um passo adiante e fornece um método estatístico para decidir se os dados fora da amostra estão alinhados com o que foi criado na amostra.


No gráfico abaixo, a área azul representa o desempenho fora da amostra para uma das minhas estratégias.


Uma simples inspeção visual revela um bom ajuste entre o desempenho dentro e fora da amostra, mas o grau de confiança que tenho nisso? Nesta fase não muito e esta é a questão. O que é realmente necessário é uma medida de similaridade entre os conjuntos de dados dentro e fora da amostra. Em termos estatísticos, isso pode ser traduzido como a probabilidade de os números de desempenho dentro e fora da amostra serem provenientes da mesma distribuição. Existe um teste estatístico não paramétrico que faz exatamente isso: o teste Kruskall-Wallis. Uma boa definição deste teste pode ser encontrada no R-Tutor & # 8220; Uma coleção de amostras de dados são independentes se elas vierem de populações não relacionadas e as amostras não se afetam. Usando o teste de Kruskal-Wallis, podemos decidir se as distribuições de população são idênticas sem assumir que elas sigam a distribuição normal. & # 8221; O benefício adicional deste teste não está assumindo uma distribuição normal.


Existe outros testes da mesma natureza que podem enquadrar-se nesse quadro. O teste de Mann-Whitney-Wilcoxon ou os testes de Kolmogorov-Smirnov adequam-se perfeitamente à estrutura descreve aqui no entanto, isso está além do escopo deste artigo para discutir os prós e contras de cada um desses testes. Uma boa descrição junto com exemplos R podem ser encontradas aqui.


Aqui, o código usado para gerar o gráfico acima e a análise:


No exemplo acima, o período de amostra é mais longo do que o período fora da amostra, portanto, criei aleatoriamente 1000 subconjuntos dos dados de amostra, cada um deles com o mesmo comprimento que os dados fora da amostra. Então eu testei cada um em subconjunto de amostra contra os dados fora da amostra e gravei os valores p. Este processo não cria um único valor de p para o teste de Kruskall-Wallis, mas uma distribuição que torna a análise mais robusta. Neste exemplo, a média dos valores de p é bem acima de zero (0.478) indicando que a hipótese nula deve ser aceita: existem fortes evidências de que os dados dentro e fora da amostra são provenientes da mesma distribuição.


Como de costume, o que é apresentado nesta publicação é um exemplo de brinquedo que apenas arranha a superfície do problema e deve ser adaptado às necessidades individuais. No entanto, acho que propõe um quadro estatístico interessante e racional para avaliar os resultados da amostra.


Esta publicação é inspirada nos dois artigos seguintes:


Vigier Alexandre, Chmil Swann (2007), "Efeitos de várias funções de otimização sobre o desempenho da amostra de estratégias de negociação desenvolvidas genéticamente", Conferência de mercados financeiros de previsão.


Vigier Alexandre, Chmil Swann (2018), "Um processo de otimização para melhorar dentro / fora da consistência da amostra, um caso do mercado de ações", JP Morgan Cazenove Equity Quantitative Conference, Londres, outubro de 2018.


Apresentando fidlr: FInancial Data LoadeR.


fidlr é um complemento do RStudio projetado para simplificar o processo de download de dados financeiros de vários provedores. Esta versão inicial é um invólucro em torno da função getSymbols no pacote quantmod e apenas o Yahoo, Google, FRED e Oanda são suportados. Provavelmente vou adicionar funcionalidades ao longo do tempo. Como de costume com essas coisas apenas um lembrete amável: & # 8220; O SOFTWARE É FORNECIDO & # 8220; COMO ESTÁ & # 8221 ;, SEM GARANTIA DE QUALQUER TIPO & # 8230; & # 8221;


Como instalar e usar o fidlr?


Você pode obter o addin / pacote de seu repositório Github aqui (Eu vou registrá-lo em CRAN mais tarde) Instale o addin. Existe um excelente tutorial para instalar o RStudio Addins aqui. Uma vez que o addin está instalado, ele deve aparecer no menu Addin. Basta escolher fidlr no menu e uma janela como ilustrada abaixo deve aparecer. Escolha um fornecedor de dados no menu suspenso Origem. Selecione um intervalo de datas no menu Data Digite o símbolo que deseja baixar na caixa de texto do instrumento. Para baixar vários símbolos, basta inserir os símbolos separados por vírgulas. Use os botões de rádio para escolher se deseja baixar o instrumento em um arquivo csv ou no ambiente global. O arquivo csv será salvo no diretório de trabalho e haverá um arquivo csv por instrumento. Pressione Executar para obter os dados ou Fechar para fechar o addin.


Mensagens de erro e avisos são tratados pelos pacotes subjacentes (quantmod e Shiny) e podem ser lidos a partir do console.


Esta é uma primeira versão do projeto, então não espere perfeição, mas espero que melhore com o tempo. Informe qualquer comentário, sugestão, erro, etc. & # 8230; para: thertrader @ gmail.


Mantendo um banco de dados de arquivos de preços em R.


Fazer pesquisas quantitativas implica uma grande quantidade de dados crunching e um precisa de dados limpos e confiáveis ​​para conseguir isso. O que é realmente necessário é a limpeza de dados facilmente acessíveis (mesmo sem conexão à internet). A maneira mais eficiente de fazer isso por mim tem sido manter um conjunto de arquivos csv. Obviamente, esse processo pode ser tratado de várias maneiras, mas eu encontrei horas extras muito eficientes e simples para manter um diretório onde eu armazeno e atualize arquivos csv. Eu tenho um arquivo csv por instrumento e cada arquivo é nomeado após o instrumento que ele contém. A razão pela qual eu faço isso é dupla: primeiro, eu não quero baixar dados (preço) do Yahoo, Google etc e # 8230; Toda vez que eu quero testar uma nova ideia, mas mais importante, uma vez que eu identifiquei e corrigi um problema, não quero ter que fazer isso novamente na próxima vez que eu precisar do mesmo instrumento. Simples, mas muito eficiente até agora. O processo está resumido no quadro abaixo.


Em tudo o que se segue, suponho que os dados sejam provenientes do Yahoo. O código terá que ser alterado para dados do Google, Quandl etc e # 8230; Além disso, apresento o processo de atualização dos dados diários de preços. A configuração será diferente para dados de freqüência mais alta e outro tipo de conjunto de dados (ou seja, diferente dos preços).


1 & # 8211; Transferência inicial de dados (listOfInstruments. R & amp; historicalData. R)


O arquivo fileOfInstruments. R é um arquivo contendo apenas a lista de todos os instrumentos.


Se um instrumento não é parte da minha lista (ou seja, nenhum arquivo csv na minha pasta de dados) ou se você fizer isso pela primeira vez que você precisa baixar o conjunto de dados históricos inicial. O exemplo abaixo baixa um conjunto de preços diários dos ETFs do Yahoo Finance de volta para janeiro de 2000 e armazena os dados em um arquivo csv.


2 & # 8211; Atualizar dados existentes (updateData. R)


O código abaixo começa a partir de arquivos existentes na pasta dedicada e atualiza todos eles um após o outro. Costumo executar esse processo todos os dias, exceto quando eu estiver no feriado. Para adicionar um novo instrumento, basta executar o passo 1 acima para este instrumento sozinho.


3 & # 8211; Crie um arquivo em lote (updateDailyPrices. bat)


Outra parte importante do trabalho é criar um arquivo em lote que automatiza o processo de atualização acima (I & # 8217; m um usuário do Windows). Isso evita abrir o R ​​/ RStudio e executar o código a partir daí. O código abaixo é colocado em um arquivo. bat (o caminho deve ser alterado com a configuração do leitor). Observe que eu adicionei um arquivo de saída (updateLog. txt) para rastrear a execução.


O processo acima é extremamente simples porque ele apenas descreve como atualizar os dados de preços diários. Eu já usei isso por um tempo e tem funcionado muito bem para mim até agora. Para dados mais avançados e / ou frequências mais elevadas, as coisas podem ficar muito mais complicadas.


Como de costume, todos os comentários são bem-vindos.


Avaliação do fator na gestão quantitativa da carteira.


Quando se trata de gerenciar um portfólio de ações versus um benchmark, o problema é muito diferente de definir uma estratégia de retorno absoluto. No primeiro, é necessário manter mais ações do que no final, onde nenhum estoque pode ser realizado se não houver uma oportunidade suficiente. A razão para isso é o erro de rastreamento. Isso é definido como o desvio padrão do retorno da carteira menos o retorno do benchmark. Menos estoques são mantidos em comparação com um benchmark quanto maior o erro de rastreamento (por exemplo, maior risco).


A análise que se segue é amplamente inspirada no livro # 8220; Gerenciamento de portfólio ativo # 8221; por Grinold & amp; Kahn. Esta é a Bíblia para qualquer pessoa interessada em administrar um portfólio em relação a um benchmark. Eu encorajo fortemente qualquer pessoa interessada no tópico a ler o livro desde o início até o fim. É muito bem escrito e estabelece as bases do gerenciamento sistemático de portfólio ativo (não tenho afiliação ao editor ou aos autores).


Aqui, estamos tentando classificar com a maior precisão possível as ações no universo de investimento em uma base de retorno para a frente. Muitas pessoas criaram muitas ferramentas e inúmeras variantes dessas ferramentas foram desenvolvidas para conseguir isso. Nesta publicação, foco em duas métricas simples e amplamente utilizadas: Coeficiente de Informações (IC) e Quantiles Return (QR).


O IC fornece uma visão geral da capacidade de previsão de fator. Mais precisamente, esta é uma medida de quão bem o fator classifica os estoques em uma base de retorno para a frente. O IC é definido como a correlação de classificação (ρ) entre a métrica (por exemplo, fator) e o retorno direto. Em termos estatísticos, a correlação de classificação é uma medida não paramétrica de dependência entre duas variáveis. Para uma amostra de tamanho n, as n pontuações brutas são convertidas em classificações e ρ é calculado a partir de:


O horizonte para o retorno para a frente deve ser definido pelo analista e é uma função da rotação da estratégia e da decaimento alfa (este tem sido objeto de pesquisa extensiva). Obviamente, os ICs devem ser o mais alto possível em termos absolutos.


Para o leitor afiado, no livro de Grinold & amp; Kahn é dada uma fórmula que liga Relação de informação (IR) e IC: com a amplitude sendo o número de apostas independentes (trades). Esta fórmula é conhecida como a lei fundamental do gerenciamento ativo. O problema é que muitas vezes, definir a amplitude com precisão não é tão fácil quanto parece.


Para ter uma estimativa mais precisa do poder preditivo do fator, é necessário avançar um pouco e agrupar os estoques por quantile de fatores de fator, em seguida, analise o retorno direto médio (ou qualquer outra métrica de tendência central) de cada um desses quantiles. A utilidade desta ferramenta é direta. Um fator pode ter um bom IC, mas seu poder preditivo pode ser limitado a um pequeno número de ações. Isso não é bom, pois um gerente de portfólio terá que escolher ações dentro do universo inteiro para atender a sua restrição de erro de rastreamento. O bom retorno dos quantiles é caracterizado por uma relação monótona entre os quantiles individuais e os retornos diretos.


Todas as ações no índice S & P500 (no momento da redação). Obviamente, há um viés de navio de sobrevivência: a lista de ações no índice mudou significativamente entre o início e o final do período de amostragem, porém é bom o suficiente para fins de ilustração apenas.


O código abaixo baixa os preços das ações individuais no S & P500 entre janeiro de 2005 e hoje (leva um tempo) e transforma os preços brutos em retorno nos últimos 12 meses e no último mês. O primeiro é o nosso fator, o último será usado como a medida de retorno direto.


Abaixo está o código para calcular Coeficiente de Informações e Quantiles Return. Note-se que usei quintios neste exemplo, mas qualquer outro método de agrupamento (terciles, deciles, etc. & # 8230;) pode ser usado. Depende realmente do tamanho da amostra, do que você deseja capturar e da sua vontade de ter uma visão ampla ou foco nas caudas de distribuição. Para estimar os retornos dentro de cada quintil, a mediana foi utilizada como estimador de tendência central. Esta medida é muito menos sensível a valores aberrantes do que a média aritmética.


E, finalmente, o código para produzir o gráfico de retorno Quantiles.


3 & # 8211; Como explorar as informações acima?


No gráfico acima Q1 é mais baixo após 12 meses de retorno e Q5 mais alto. Existe um aumento quase monotônico no retorno de quantiles entre Q1 e Q5, o que indica claramente que os estoques que caíram em Q5 superam aqueles que caíram em Q1 em cerca de 1% por mês. Isso é muito significativo e poderoso para um fator tão simples (não é realmente uma surpresa e # 8230;). Portanto, há maiores chances de vencer o índice por sobreponderar os estoques caindo no Q5 e subponderar aqueles que caem no Q1 em relação ao benchmark.


Um IC de 0,0206 pode não significar um ótimo negócio em si, mas é significativamente diferente de 0 e indica um bom poder preditivo dos últimos 12 meses em geral. Os testes de significância formal podem ser avaliados, mas isso está além do escopo deste artigo.


A estrutura acima é excelente para avaliar a qualidade do fator de investimento, porém existem várias limitações práticas que devem ser abordadas para a implementação da vida real:


Reequilíbrio: na descrição acima, considerou que, no final de cada mês, o portfólio é totalmente reequilibrado. Isso significa que todas as ações que caem no primeiro trimestre estão abaixo do peso e todas as ações que caem no Q5 estão com sobrepeso em relação ao benchmark. Isso nem sempre é possível por razões práticas: alguns estoques podem ser excluídos do universo de investimento, existem restrições ao peso da indústria ou do setor, existem restrições sobre o roteamento etc & # 8230; Custos de transação: isso não foi levado em consideração na análise acima e isso é um travão grave para a implementação da vida real. As considerações sobre o volume de negócios geralmente são implementadas na vida real sob uma forma de penalidade na qualidade dos fatores. Coeficiente de transferência: esta é uma extensão da lei fundamental da gestão ativa e relaxa a suposição do modelo de Grinold & # 8217; que os gerentes não enfrentam restrições que impedem que eles traduzam seus insights de investimentos diretamente em apostas de portfólio.


E, finalmente, estou impressionado com o que pode ser alcançado em menos de 80 linhas de código com R & # 8230;


Como de costume, todos os comentários são bem-vindos.


Risco como uma Variação de Sobrevivência & # 8220; # 8221;


Eu me deparo com muitas estratégias na blogosfera, algumas são interessantes, algumas são um completo desperdício de tempo, mas a maioria compartilha uma característica comum: as pessoas que desenvolvem essas estratégias fazem seu dever de casa em termos de análise do retorno, mas muito menos atenção é paga ao lado do risco é natureza aleatória. Eu comentei um comentário como "# 8220; uma redução de 25% em 2018, mas excelente retorno em geral" # 8221 ;. Bem, minha aposta é que ninguém na terra vai deixar você experimentar uma perda de 25% com seu dinheiro (a menos que acordos especiais estejam em vigor). No fundo hedge, as pessoas do mundo têm uma tolerância muito baixa para redução. Geralmente, como um novo comerciante em um hedge fund, assumindo que você não possui reputação, você tem muito pouco tempo para provar a si mesmo. Você deve ganhar dinheiro a partir do dia 1 e continuar fazendo isso por alguns meses antes de ganhar um pouco de credibilidade.


Diga primeiro que você tenha um mau começo e você perca dinheiro no início. Com uma redução de 10%, você certamente estará fora, mas mesmo com uma redução de 5%, as chances de ver sua alocação reduzida são muito altas. Isso tem implicações significativas em suas estratégias. Deixe assumir que, se você perder 5%, sua alocação é dividida por 2 e você retorna à sua alocação inicial somente quando você passou a marca de água alta novamente (por exemplo, a retirada volta para 0). No gráfico abaixo, simulei a experiência com uma das minhas estratégias.


Você começa a operar em 1º de junho de 2003 e tudo corre bem até 23 de julho de 2003, onde sua curva de retirada atinge o limite de -5% (** 1 **). Sua alocação é reduzida em 50% e você não recupera o nível da marca de água até o 05 de dezembro de 2003 (** 3 **). Se você manteve a alocação inalterada, o nível da marca de água alta teria sido cruzado em 28 de outubro de 2003 (** 2 **) e, no final do ano, você teria feito mais dinheiro.


Mas vamos empurrar o raciocínio um pouco mais. Ainda no gráfico acima, suponha que você tenha realmente uma azarada e você começa a operar até meados de junho de 2003. Você atingiu o limite de retirada de 10% no início de agosto e você provavelmente estará fora do jogo. Você teria começado no início de agosto sua alocação não teria sido cortada e você acabou fazendo um bom ano em apenas 4 meses completos de negociação. Nesses dois exemplos, nada mudou, mas sua data de início e # 8230 ;.


O sucesso comercial de qualquer indivíduo tem alguma forma de dependência do caminho e não há muito que você possa fazer sobre isso. No entanto, você pode controlar o tamanho da retirada de uma estratégia e isso deve ser abordado com muito cuidado. Um portfólio deve ser diversificado em todas as dimensões possíveis: classes de ativos, estratégias de investimento, freqüências de negociação, etc. & # 8230 ;. A partir dessa perspectiva, o risco é a sua variável de sobrevivência # 8221 ;. Se for gerenciado adequadamente, você tem a chance de permanecer no jogo o suficiente para perceber o potencial de sua estratégia. Caso contrário, você ganhou o mês que vem para ver o que acontece.


Como de costume, todos os comentários são bem-vindos.


Uma aplicação simples e brilhante para monitorar estratégias de negociação e # 8211; Parte II.


Este é um seguimento na minha publicação anterior & # 8220; Uma aplicação simples brilhante para monitorar estratégias de negociação & # 8220 ;. Eu adicionei algumas melhorias que tornam o aplicativo um pouco melhor (pelo menos para mim!). Abaixo está a lista de novos recursos:


Um exemplo de arquivo. csv (aquele que contém os dados brutos) A & # 8220; EndDate & # 8221; drop down box permitindo especificar o final do período. A & # 8220; Risk & # 8221; página contendo uma análise de VaR e um gráfico de pior desempenho em vários horizontes A & # 8220; How To & # 8221; página explicando como usar e adaptar o aplicativo às necessidades individuais.


Eu também fiz o aplicativo totalmente independente. Agora está disponível como um produto autônomo e não há necessidade de ter o R ​​/ RStudio instalado em seu computador para executá-lo. Pode ser baixado da conta da unidade R Trader Google. Esta versão do aplicativo corre usando o R portátil e o Chrome portátil. Para o leitor afiado, este link explica em detalhes completos como empacotar um aplicativo brilhante em um aplicativo de área de trabalho (somente Windows por agora).


1 & # 8211; Como instalar & amp; Execute o aplicativo no seu computador.


Crie uma pasta específica Descompacte a contém do arquivo. zip na nova pasta. Altere os caminhos no arquivo runShinyApp para combinar suas configurações Para executar o aplicativo, você apenas iniciou o arquivo run. vbs. Eu também incluí um ícone (RTraderTradingApp. ico) se você quiser criar um atalho na sua área de trabalho.


ui. R: controla o layout e a aparência do servidor do aplicativo. R: contém as instruções necessárias para criar o aplicativo. Você pode carregar tantas estratégias quanto desejar, desde que o arquivo csv correspondente tenha o formato certo (veja abaixo). ShinyStrategyGeneral. R: carrega os pacotes necessários e lança o aplicativo.


3 & # 8211; Como adicionar uma estratégia de negociação?


Crie o arquivo. csv correspondente no diretório direto Crie uma nova entrada na função reativa de dados (dentro do arquivo server. R) Adicione um elemento extra ao parâmetro de escolha no primeiro selectInput na barra lateralPanel (dentro do arquivo ui. R) . O nome do elemento deve corresponder ao nome da nova entrada acima.


Remova a entrada na função de resposta de dados correspondente à estratégia que deseja remover (dentro do arquivo server. R) Remova o elemento no parâmetro de escolha no primeiro selectInput na barra lateralPanel correspondente à estratégia que deseja remover (dentro do ui Arquivo. R).


Sinta-se à vontade para entrar em contato se você tiver alguma sugestão.


Um aplicativo simples e brilhante para monitorar estratégias de negociação.


Em uma publicação anterior, mostrei como usar R, Knitr e LaTeX para criar um relatório de estratégia de modelo. Esta publicação dá um passo adiante, tornando a análise interativa. Além da interatividade, o aplicativo brilhante também resolve dois problemas:


Agora posso acessar todas as minhas estratégias de negociação de um único ponto, independentemente do instrumento negociado. Juntamente com a interatividade Brilhante, permite uma comparação mais fácil. Posso me concentrar em um período de tempo específico.


O código usado nesta publicação está disponível em um repositório Gist / Github. Existem essencialmente 3 arquivos.


ui. R: controla o layout ea aparência do aplicativo. server. R: contém as instruções necessárias para criar o aplicativo. Carrega os dados e formata-o. Há um arquivo csv por estratégia, cada um contendo pelo menos duas colunas: data e retorno com o seguinte formato: (& # 8220; 2018-12-22 & # 8243 ;, & # 8221; 0.04% & # 8221;)). Você pode carregar tantas estratégias quanto quiser, desde que tenham o formato certo. ShinyStrategyG eneral. R: carrega os pacotes necessários e lança o aplicativo.


Este aplicativo provavelmente está longe de ser perfeito e certamente o melhorarei no futuro. Sinta-se livre para entrar em contato se você tiver alguma sugestão.


Um grande agradecimento ao time RStudio / Shiny por uma ótima ferramenta.


Usando Algoritmos Genéticos em Negociação Quantitativa.


A questão que sempre deve ser feita ao usar indicadores técnicos é o que seria um critério objetivo para selecionar os parâmetros dos indicadores (por exemplo, por que usar um RSI de 14 dias em vez de 15 ou 20 dias?). Os algoritmos genéticos (GA) são ferramentas adequadas para responder a essa pergunta. Nesta publicação, eu mostro como configurar o problema em R. Antes de prosseguir o lembrete habitual: O que eu apresento nesta publicação é apenas um exemplo de brinquedo e não um convite para investir. Também não é uma estratégia concluída, mas uma idéia de pesquisa que precisa ser pesquisada, desenvolvida e adaptada às necessidades individuais.


O que são algoritmos genéticos?


A melhor descrição do GA que encontrei vem da Cybernatic Trading, um livro de Murray A. Ruggiero. Algoritmos genéticos foram inventados por John Holland em meados de 1970 para resolver problemas difíceis de otimização. Este método usa a seleção natural, a sobrevivência do mais forte # 8221 ;. O processo geral segue os passos abaixo:


Codifique o problema nos cromossomos Usando a codificação, desenvolva uma função de aptidão para uso na avaliação do valor de cada cromossomo na resolução de um determinado problema. Inicialize uma população de cromossomos. Avalie cada cromossomo na população. Crie novos cromossomos acoplando dois cromossomos. Isso é feito por muting e recombinação de dois pais para formar dois filhos (os pais são selecionados aleatoriamente, mas tendenciosos por sua aptidão) Avalie o novo cromossomo Exclua um membro da população que seja menos adequado do que o novo cromossomo e insira o novo cromossomo na população . Se o critério de parada for atingido (número máximo de gerações, o critério de aptidão é bom o suficiente e # 8230;), então, retorne o melhor cromossomo, alternativamente, vá para o passo 4.


A partir de uma perspectiva comercial, a GA é muito útil porque são boas em lidar com problemas altamente não-lineares. However they exhibit some nasty features that are worth mentioning:


Over fitting: This is the main problem and it’s down to the analyst to set up the problem in a way that minimises this risk. Computing time : If the problem isn’t properly defined, it can be extremely long to reach a decent solution and the complexity increases exponentially with the number of variables. Hence the necessity to carefully select the parameters.


There are several R packages dealing with GA, I chose to use the most common one: rgenoud.


Daily closing prices for most liquid ETFs from Yahoo finance going back to January 2000. The in sample period goes from January 2000 to December 2018. The Out of sample period starts on January 2018.


The logic is as following: the fitness function is optimised over the in sample period to obtain a set of optimal parameters for the selected technical indicators. The performance of those indicators is then evaluated in the out of sample period. But before doing so the technical indicators have to be selected.


The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: moving averages cross over and RSI. This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes . The other key element is the fitness function . We might want to use something like: maximum return or Sharpe ratio or minimum average Drawdown. In what follows, I chose to maximise the Sharpe ratio.


The R implementation is a set of 3 functions:


fitnessFunction : defines the fitness function (e. g., maximum Sharpe ratio) to be used within the GA engine tradingStatistics : summary of trading statistics for the in and out of sample periods for comparison purposes genoud : the GA engine from the rgenoud package.


The genoud function is rather complex but I’m not going to explain what each parameter means as I want to keep this post short (and the documentation is really good).


In the table below I present for each instrument the optimal parameters (RSI look-back period, RSI threshold, Short Term Moving Average, and Long Term Moving Average) along with the in and out of sample trading statistics.


Before commenting the above results, I want to explain a few important points. To match the logic defined above, I bounded the parameters to make sure the look-back period for the long term moving average is always longer that the shorter moving average. I also constrained the optimiser to choose only the solutions with more than 50 trades in the in sample period (e. g;, statistical significance).


Overall the out of sample results are far from impressive. The returns are low even if the number of trades is small to make the outcome really significant. However there’s a significant loss of efficiency between in and out of sample period for Japan (EWJ) which very likely means over fitting.


This post is intended to give the reader the tools to properly use GA in a quantitative trading framework. Once again, It’s just an example that needs to be further refined. A few potential improvement to explore would be:


fitness function : maximising the Sharpe ratio is very simplistic. A “smarter” function would certainly improve the out of sample trading statistics pattern : we try to capture a very straightforward pattern. A more in depth pattern research is definitely needed. optimisation : there are many ways to improve the way the optimisation is conducted. This would improve both the computation speed and the rationality of the results.


The code used in this post is available on a Gist repository.


Gekko Quant - Negociação Quantitativa.


Comércio Quantitativo, Arbitragem Estatística, Aprendizado de Máquinas e Opções Binárias.


Category Archives: R Code.


Pós-navegação.


RNeat – Square Root Neural Net trained using Augmenting Topologies – Simple Example.


A simple tutorial demonstrating how to train a neural network to square root numbers using a genetic algorithm that searches through the topological structure space. The algorithm is called NEAT (Neuro Evolution of Augmenting Topologies) available in the RNeat package (not yet on CRAN).


The training is very similar to other machine learning / regression packages in R. The training function takes a data frame and a formula. The formula is used to specify what columns in the data frame are the dependent variables and which are the explanatory variable. The code is commented and should be simple enough for new R users.


The performance of the network can be seen in the bottom left chart of the image above, there is considerable differences between the expected output and the actual output. It is likely that with more training the magnitude of these errors will reduce, it can be seen in the bottom right chart that the maximum, mean and median fitness are generally increasing with each generation.


Inverted Pendulum Simulation in R.


This post will derive the equations of motion and simulate the classic inverted pendulum control problem. Subsequent posts will apply machine learning to figure out how to control the pendulum and keep it up in the air.


A video of the simulation can be found at:


The derivation of the maths follows the approach outlined in the following video, however I have decided to model the friction between the cart and track.


Free body diagram of cart.


Free body diagram of pendulum.


Resolve the forces on the free body diagrams and set equal to their acceleration.


Definition of e co-ordinate system.


The acceleration of the pendulum is the acceleration of the cart plus the acceleration of the pendulum relative to the cart.


Convert the co-ordinate system back into the and components.


Substitute the accelerations into equation (1) and (2)


It is undesirable to have an unknown tension T so eliminate using a trick.


Substitute equation (1) into equation (0)


Rearranging equation (6) and (5) gives the system equations in known measurable variables.


Both the acceleration terms and depend on each other which is undesirable, substitute the equation for into the equation for to remove the dependency.


The system can then be simulated using Euler update equations:


Animation in R – Bouncing Ball Simulation.


This post fill focus on how to create an animation to visualise the simulation of a physical system, in this case a bouncing ball. Whilst this post is unrelated to trading it will form the basis of future articles. In my next post I will show how to simulate the classic pole balancing / inverted pendulum problem. Machine learning will then be applied to develop a control system for the dynamic systems.


A video of the simulation is below:


The R package “animation” has been used to create videos of the simulated process. This package requires that FFMpeg is installed on your machine and added to your environmental path. To learn how to add items to your path follow this tutorial at Geeks With Blogs.


The code below demonstrated how to generate a video:


ani. width is the width of the video ani. height is the height of the video other. opts are command line arguments that are passed to ffmpeg and can be used to control the bitrate and other quality settings interval specifies in seconds how long to wait between frames runSimulationFunc() is a function that should run your simulation, and charts plotted during the simulation will be added to the video.


I have written some functions to make drawing basic graphics easy.


createSceneFunc(bottomLeftX, bottomLeftY, width, height) creates a brand new scene to draw objects on, bottomLeftX and bottomLeftY are Cartesian co-ordinates to specify the bottom left corner of the canvas. The width and height variables are used to specify the canvas dimensions. createBoxFunc(topLeftX, topLeftY, width, height, fillColour) draws a box to the current canvas, topLeftX and topLeftY specify the Cartesian co-ordinate of the top left of the box, width and height specify the dimensions and fillColour specifies the colour that fills in the box. createCircleFunc(centerX, centerY, radius, fillColour) draws a circle to the current canvas, centerX and centerY specify the Cartesian co-ordinate of the center on the circle, the radius specifies the radius of the circle and fillColour specifies the colour that fills in the circle.


The following single period update equations are used:


When a collision is made between the ball and the platform the following update is used:


High Probability Credit Spreads – Using Linear Regression Curves.


I came across this video series over the weekend, an option trader discusses how he trades credit spreads (mainly looks for mean reversion). Most of you will be familiar with bollinger bands as a common mean reversion strategy, essentially you take the moving average and moving standard deviation of the stock. You then plot on to your chart the moving average and an upper and lower band(moving average +/- n*standard deviations).


It is assumed that the price will revert to the moving average hence any price move to the bands is a good entry point. A common problem with this strategy is that the moving average is a LAGGING indicator and is often very slow to track the price moves if a long lookback period is used.


Video 1 presents a technique called “linear regression curves” about 10mins in. Linear regression curves aim to solve the problem of the moving average being slow to track the price.


Linear Regression Curve vs Simple Moving Average.


See how tightly the blue linear regression curve follows the close price, it’s significantly quicker to identify turns in the market where as the simple moving average has considerable tracking error. The MSE could be taken to quantify the tightness.


How to calculate the linear regression curve:


In this example you have 100 closing prices for your given stock. Bar 1 is the oldest price, bar 100 is the most recent price. We will use a 20day regression.


1. Take prices 1-20 and draw the line of best fit through them.


2. At the end of your best fit line (so bar 20), draw a little circle.


3. Take prices 2-21 and draw the line of best fit through them.


4. At the end of your best fit line (so bar 21) draw a little circle.


5. Repeat upto bar 100.


6. Join all of your little circles, this is your ‘linear regression curve’


So in a nutshell you just join the ends of a rolling linear regression.


Parameter Optimisation & Backtesting – Parte 2.


The code presented here will aim to optimise a strategy based upon the simple moving average indicator. The strategy will go Long when moving average A > moving average B. The optimisation is to determine what period to make each of the moving averages A & B.


Please note that this isn’t intended to be a good strategy, it is merely here to give an example of how to optimise a parameter.


TradingStrategy this function implements the trading logic and calculates the returns RunIterativeStrategy this function iterates through possible parameter combinations and calls TradingStrategy for each new parameter set CalculatePerformanceMetric takes in a table of returns (from RunIterativeStrategy) and runs a function/metric over each set of returns. PerformanceTable calls CalculatePerformanceMetric for lots of different metric and compiles the results into a table OrderPerformanceTable lets us order the performance table by a given metric, ie order by highest sharpe ratio SelectTopNStrategies selects the best N strategies for a specified performance metric (charts. PerformanceSummary can only plot.


20 strategies, hence this function to select a sample) FindOptimumStrategy does what it says on the tin.


QuantStrat TradeR.


Comércio, QuantStrat, R e muito mais.


Which Implied Volatility Ratio Is Best?


This post will be about comparing a volatility signal using three different variations of implied volatility indices to predict when to enter a short volatility position.


In volatility trading, there are three separate implied volatility indices that have a somewhat long history for trading–the VIX (everyone knows this one), the VXV (more recently changed to be called the VIX3M), which is like the VIX, except for a three-month period), and the VXMT, which is the implied six-month volatility period.


This relationship gives investigation into three separate implied volatility ratios: VIX/VIX3M (aka VXV), VIX/VXMT, and VIX3M/VXMT, as predictors for entering a short (or long) volatility position.


So, let’s get the data.


One quick strategy to investigate is simple–the idea that the ratio should be below 1 (I. E. contango in implied volatility term structure) and decreasing (below a moving average). So when the ratio will be below 1 (that is, with longer-term implied volatility greater than shorter-term), and the ratio will be below its 60-day moving average, the strategy will take a position in XIV.


Here’s the code to do that.


With the following performance:


In other words, the VIX3M/VXMT sports the lowest drawdowns (by a large margin) with higher returns.


So, when people talk about which implied volatility ratio to use, I think this offers some strong evidence for the longer-out horizon as a predictor for which implied vol term structure to use. It’s also why it forms the basis of my subscription strategy.


Obrigado pela leitura.


NOTE: I am currently seeking a full-time position (remote or in the northeast U. S.) related to my skill set demonstrated on this blog. Please message me on LinkedIn if you know of any opportunities which may benefit from my skill set.


Replicating Volatility ETN Returns From CBOE Futures.


This post will demonstrate how to replicate the volatility ETNs (XIV, VXX, ZIV, VXZ) from CBOE futures, thereby allowing any individual to create synthetic ETF returns from before their inception, free of cost.


So, before I get to the actual algorithm, it depends on an update to the term structure algorithm I shared some months back.


In that algorithm, mistakenly (or for the purpose of simplicity), I used calendar days as the time to expiry, when it should have been business days, which also accounts for weekends, and holidays, which are an irritating artifact to keep track of.


So here’s the salient change, in the loop that calculates times to expiry:


The one salient line in particular, is this:


What is this bizdays function? It comes from the bizdays package in R.


There’s also the tradingHolidays. R script, which makes further use of the bizdays package. Here’s what goes on under the hood in tradingHolidays. R, for those that wish to replicate the code:


There are two CSVs that I manually compiled, but will share screenshots of–they are the easter holidays (because they have to be adjusted for turning Sunday to Friday because of Easter Fridays), and the rest of the national holidays.


Here is what the easters csv looks like:


And the nonEasterHolidays, which contains New Year’s Day, MLK Jr. Day, President’s Day, Memorial Day, Independence Day, Labor Day, Thanksgiving Day, and Christmas Day (along with their observed dates) CSV:


Furthermore, we need to adjust for the two days that equities were not trading due to Hurricane Sandy.


So then, the list of holidays looks like this:


So once we have a list of holidays, we use the bizdays package to set the holidays and weekends (Saturday and Sunday) as our non-business days, and use that function to calculate the correct times to expiry.


So, now that we have the updated expiry structure, we can write a function that will correctly replicate the four main volatility ETNs–XIV, VXX, ZIV, and VXZ.


Here’s the English explanation:


VXX is made up of two contracts–the front month, and the back month, and has a certain number of trading days (AKA business days) that it trades until expiry, say, 17. During that timeframe, the front month (let’s call it M1) goes from being the entire allocation of funds, to being none of the allocation of funds, as the front month contract approaches expiry. That is, as a contract approaches expiry, the second contract gradually receives more and more weight, until, at expiry of the front month contract, the second month contract contains all of the funds–just as it *becomes* the front month contract. So, say you have 17 days to expiry on the front month. At the expiry of the previous contract, the second month will have a weight of 17/17–100%, as it becomes the front month. Then, the next day, that contract, now the front month, will have a weight of 16/17 at settle, then 15/17, and so on. That numerator is called dr, and the denominator is called dt.


However, beyond this, there’s a second mechanism that’s responsible for the VXX looking like it does as compared to a basic futures contract (that is, the decay responsible for short volatility’s profits), and that is the “instantaneous” rebalancing. That is, the returns for a given day are today’s settles multiplied by yesterday’s weights, over yesterday’s settles multiplied by yesterday’s weights, minus one. That is, (S_1_t * dr/dt_t-1 + S_2_t * 1-dr/dt_t-1) / (S_1_t-1 * dr/dt_t-1 + S_2_t-1 * 1-dr/dt_t-1) – 1 (I could use a tutorial on LaTeX). So, when you move forward a day, well, tomorrow, today’s weights become t-1. Yet, when were the assets able to be rebalanced? Well, in the ETNs such as VXX and VXZ, the “hand-waving” is that it happens instantaneously. That is, the weight for the front month was 93%, the return was realized at settlement (that is, from settle to settle), and immediately after that return was realized, the front month’s weight shifts from 93%, to, say, 88%. So, say Credit Suisse (that issues these ETNs ), has $10,000 (just to keep the arithmetic and number of zeroes tolerable, obviously there are a lot more in reality) worth of XIV outstanding after immediately realizing returns, it will sell $500 of its $9300 in the front month, and immediately move them to the second month, so it will immediately go from $9300 in M1 and $700 in M2 to $8800 in M1 and $1200 in M2. When did those $500 move? Immediately, instantaneously, and if you like, you can apply Clarke’s Third Law and call it “magically”.


The only exception is the day after roll day, in which the second month simply becomes the front month as the previous front month expires, so what was a 100% weight on the second month will now be a 100% weight on the front month, so there’s some extra code that needs to be written to make that distinction.


That’s the way it works for VXX and XIV. What’s the difference for VXZ and ZIV? It’s really simple–instead of M1 and M2, VXZ uses the exact same weightings (that is, the time remaining on front month vs. how many days exist for that contract to be the front month), uses M4, M5, M6, and M7, with M4 taking dr/dt, M5 and M6 always being 1, and M7 being 1-dr/dt.


In any case, here’s the code.


So, a big thank you goes out to Michael Kapler of Systematic Investor Toolbox for originally doing the replication and providing his code. My code essentially does the same thing, in, hopefully a more commented way.


So, ultimately, does it work? Well, using my updated term structure code, I can test that.


While I’m not going to paste my entire term structure code (again, available here, just update the script with my updates from this post), here’s how you’d run the new function:


And since it returns both the vxx returns and the vxz returns, we can compare them both.


With the result:


Basically, a perfect match.


Let’s do the same thing, with ZIV.


So, rebuilding from the futures does a tiny bit better than the ETN. But the trajectory is largely identical.


That concludes this post. I hope it has shed some light on how these volatility ETNs work, and how to obtain them directly from the futures data published by the CBOE, which are the inputs to my term structure algorithm.


This also means that for institutions interested in trading my strategy, that they can obtain leverage to trade the futures-composite replicated variants of these ETNs, at greater volume.


Obrigado pela leitura.


NOTES: For those interested in a retail subscription strategy to trading volatility, do not hesitate to subscribe to my volatility-trading strategy. For those interested in employing me full-time or for long-term consulting projects, I can be reached on my LinkedIn, or my email: ilya. kipnis@gmail.


(Don’t Get) Contangled Up In Noise.


This post will be about investigating the efficacy of contango as a volatility trading signal.


For those that trade volatility (like me), a term you may see that’s somewhat ubiquitous is the term “contango”. What does this term mean?


Well, simple: it just means the ratio of the second month of VIX futures over the first. The idea being is that when the second month of futures is more than the first, that people’s outlook for volatility is greater in the future than it is for the present, and therefore, the futures are “in contango”, which is most of the time.


Furthermore, those that try to find decent volatility trading ideas may have often seen that futures in contango implies that holding a short volatility position will be profitable.


Is this the case?


Well, there’s an easy way to answer that.


First off, refer back to my post on obtaining free futures data from the CBOE.


Using this data, we can obtain our signal (that is, in order to run the code in this post, run the code in that post).


Now, let’s get our XIV data (again, big thanks to Mr. Helmuth Vollmeier for so kindly providing it.


Now, here’s how this works: as the CBOE doesn’t update its settles until around 9:45 AM EST on the day after (EG a Tuesday’s settle data won’t release until Wednesday at 9:45 AM EST), we have to enter at close of the day after the signal fires. (For those wondering, my subscription strategy uses this mechanism, giving subscribers ample time to execute throughout the day.)


So, let’s calculate our backtest returns. Here’s a stratStats function to compute some summary statistics.


With the following results:


So, this is obviously a disaster. Visual inspection will show devastating, multi-year drawdowns. Using the table. Drawdowns command, we can view the worst ones.


So, the top 3 are horrendous, and then anything above 30% is still pretty awful. A couple of those drawdowns lasted multiple years as well, with a massive length to the trough. 458 trading days is nearly two years, and 364 is about one and a half years. Imagine seeing a strategy be consistently on the wrong side of the trade for nearly two years, and when all is said and done, you’ve lost three-fourths of everything in that strategy.


There’s no sugar-coating this: such a strategy can only be called utter trash.


Let’s try one modification: we’ll require both contango (C2 > C1), and that contango be above its 60-day simple moving average, similar to my VXV/VXMT strategy.


With the results:


So, a Calmar still safely below 1, an Ulcer Performance Index still in the basement, a maximum drawdown that’s long past the point that people will have abandoned the strategy, and so on.


So, even though it was improved, it’s still safe to say this strategy doesn’t perform too well. Even after the large 2007-2008 drawdown, it still gets some things pretty badly wrong, like being exposed to all of August 2017.


While I think there are applications to contango in volatility investing, I don’t think its use is in generating the long/short volatility signal on its own. Rather, I think other indices and sources of data do a better job of that. Such as the VXV/VXMT, which has since been iterated on to form my subscription strategy.


Obrigado pela leitura.


NOTE: I am currently seeking networking opportunities, long-term projects, and full-time positions related to my skill set. My linkedIn profile can be found here.


Comparing Some Strategies from Easy Volatility Investing, and the Table. Drawdowns Command.


This post will be about comparing strategies from the paper “Easy Volatility Investing”, along with a demonstration of R’s table. Drawdowns command.


First off, before going further, while I think the execution assumptions found in EVI don’t lend the strategies well to actual live trading (although their risk/reward tradeoffs also leave a lot of room for improvement), I think these strategies are great as benchmarks.


So, some time ago, I did an out-of-sample test for one of the strategies found in EVI, which can be found here.


Using the same source of data, I also obtained data for SPY (though, again, AlphaVantage can also provide this service for free for those that don’t use Quandl).


Here’s the new code.


So, an explanation: there are four return streams here–buy and hold XIV, the DDN momentum from a previous post, and two other strategies.


The simpler one, called the VRatio is simply the ratio of the VIX over the VXV. Near the close, check this quantity. If this is less than one, buy XIV, otherwise, buy VXX.


The other one, called the Volatility Risk Premium strategy (or VRP for short), compares the 10 day historical volatility (that is, the annualized running ten day standard deviation) of the S&P 500, subtracts it from the VIX, and takes a 5 day moving average of that. Near the close, when that’s above zero (that is, VIX is higher than historical volatility), go long XIV, otherwise, go long VXX.


Again, all of these strategies are effectively “observe near/at the close, buy at the close”, so are useful for demonstration purposes, though not for implementation purposes on any large account without incurring market impact.


Here are the results, since 2018 (that is, around the time of XIV’s actual inception):


To note, both the momentum and the VRP strategy underperform buying and holding XIV since 2018. The VRatio strategy, on the other hand, does outperform.


Here’s a summary statistics function that compiles some top-level performance metrics.


To note, all of the benchmark strategies suffered very large drawdowns since XIV’s inception, which we can examine using the table. Drawdowns command, as seen below:


Note that the table. Drawdowns command only examines one return stream at a time. Furthermore, the top argument specifies how many drawdowns to look at, sorted by greatest drawdown first.


One reason I think that these strategies seem to suffer the drawdowns they do is that they’re either all-in on one asset, or its exact opposite, with no room for error.


One last thing, for the curious, here is the comparison with my strategy since 2018 (essentially XIV inception) benchmarked against the strategies in EVI (which I have been trading with live capital since September, and have recently opened a subscription service for):


Obrigado pela leitura.


NOTE: I am currently looking for networking and full-time opportunities related to my skill set. My LinkedIn profile can be found here.


Launching My Subscription Service.


After gauging interest from my readers, I’ve decided to open up a subscription service. I’ll copy and paste the FAQs, or my best attempt at trying to answer as many questions as possible ahead of time, and may answer more in the future.


I’m choosing to use Patreon just to outsource all of the technicalities of handling subscriptions and creating a centralized source to post subscription-based content.


FAQs (copied from the subscription page):


Obrigado pela visita. After gauging interest from my readership on my main site (quantstrattrader. wordpress), I created this as a subscription page for quantitative investment strategies, with the goal of having subscribers turn their cash into more cash, net of subscription fees (hopefully). The systems I develop come from a background of learning from experienced quantitative trading professionals, and senior researchers at large firms. The current system I initially published a prototype for several years back and watched it being tracked, before finally starting to deploy my own capital earlier this year, and making the most recent modifications even more recently.


And while past performance doesn’t guarantee future results and the past doesn’t repeat itself, it often rhymes, so let’s turn money into more money.


Some FAQs about the strategy:


​What is the subscription price for this strategy?


​Currently, after gauging interest from readers and doing research based on other sites, the tentative pricing is $50/month. As this strategy builds a track record, that may be subject to change in the future, and notifications will be made in such an event.


What is the description of the strategy?


The strategy is mainly a short volatility system that trades XIV, ZIV, and VXX. As far as volatility strategies go, it’s fairly conservative in that it uses several different checks in order to ensure a position.


What is the strategy’s edge?


In two words: risk management. Essentially, there are a few separate criteria to select an investment, and the system spends a not-insignificant time with no exposure when some of these criteria provide contradictory signals. Furthermore, the system uses disciplined methodologies in its construction in order to avoid unnecessary free parameters, and to keep the strategy as parsimonious as possible.


Do you trade your own capital with this strategy?


When was the in-sample training period for this system?


A site that no longer updates its blog (volatility made simple) once tracked a more rudimentary strategy that I wrote about several years ago. I was particularly pleased with the results of that vetting, and recently have received input to improve my system to a much greater degree, as well as gained the confidence to invest live capital into it.


How many trades per year does the system make?


In the backtest from April 20, 2008 through the end of 2018, the system made 187 transactions in XIV (both buy and sell), 160 in ZIV, and 52 in VXX. Meaning over the course of approximately 9 years, there was on average 43 transactions per year. In some cases, this may simply be switching from XIV to ZIV or vice versa. In other words, trades last approximately a week (some may be longer, some shorter).


When will signals be posted?


Signals will be posted sometime between 12 PM and market close (4 PM EST). In backtesting, they are tested as market on close orders, so individuals assume any risk/reward by executing earlier.


How often is this system in the market?


About 56%. However, over the course of backtesting (and live trading), only about 9% of months have zero return.


What are the distribution of winning, losing, and zero return months?


As of late October 2017, there have been about 65% winning months (with an average gain of 12.8%), 26% losing months (with an average loss of 4.9%), and 9% zero months.


What are some other statistics about the strategy?


Since 2018 (around the time that XIV officially came into inception as opposed to using synthetic data), the strategy has boasted an 82% annualized return, with a 24.8% maximum drawdown and an annualized standard deviation of 35%. This means a Sharpe ratio (return to standard deviation) higher than 2, and a Calmar ratio higher than 3. It also has an Ulcer Performance Index of 10.


What are the strategy’s worst drawdowns?


Since 2018 (again, around the time of XIV’s inception), the largest drawdown was 24.8%, starting on October 31, 2018, and making a new equity high on January 12, 2018. The longest drawdown started on August 21, 2018 and recovered on April 10, 2018, and lasted for 160 trading days.


Will the subscription price change in the future?


If the strategy continues to deliver strong returns, then there may be reason to increase the price so long as the returns bear it out.


Can a conservative risk signal be provided for those who might not be able to tolerate a 25% drawdown?


A variant of the strategy that targets about half of the annualized standard deviation of the strategy boasts a 40% annualized return for about 12% drawdown since 2018. Overall, this has slightly higher reward to risk statistics, but at the cost of cutting aggregate returns in half.


Can’t XIV have a termination event?


This refers to the idea of the XIV ETN terminating if it loses 80% of its value in a single day. To give an idea of the likelihood of this event, using synthetic data, the XIV ETN had a massive drawdown of 92% over the course of the 2008 financial crisis. For the history of that synthetic (pre-inception) and realized (post-inception) data, the absolute worst day was a down day of 26.8%. To note, the strategy was not in XIV during that day.


What was the strategy’s worst day?


On September 16, 2018, the strategy lost 16% in one day. This was at the tail end of a stretch of positive days that made about 40%.


What are the strategy’s risks?


The first risk is that given that this strategy is naturally biased towards short volatility, that it can have potential for some sharp drawdowns due to the nature of volatility spikes. The other risk is that given that this strategy sometimes spends its time in ZIV, that it will underperform XIV on some good days. This second risk is a consequence of additional layers of risk management in the strategy.


How complex is this strategy?


Not overly. It’s only slightly more complex than a basic momentum strategy when counting free parameters, and can be explained in a couple of minutes.


Does this strategy use any complex machine learning methodologies?


No. The data requirements for such algorithms and the noise in the financial world make it very risky to apply these methodologies, and research as of yet did not bear fruit to justify incorporating them.


Will instrument volume ever be a concern (particularly ZIV)?


According to one individual who worked on the creation of the original VXX ETN (and by extension, its inverse, XIV), new shares of ETNs can be created by the issuer (in ZIV’s case, Credit Suisse) on demand. In short, the concern of volume is more of a concern of the reputability of the person making the request. In other words, it depends on how well the strategy does.


Can the strategy be held liable/accountable/responsible for a subscriber’s loss/drawdown?


​Let this serve as a disclaimer: by subscribing, you agree to waive any legal claim against the strategy, or its creator(s) in the event of drawdowns, losses, etc. The subscription is for viewing the output of a program, and this service does not actively manage a penny of subscribers’ actual assets. Subscribers can choose to ignore the strategy’s signals at a moment’s notice at their discretion. The program’s output should not be thought of as the investment advice coming from a CFP, CFA, RIA, etc.


Why should these signals be trusted?


Because my work on other topics has been on full, public display for several years. Unlike other websites, I have shown “bad backtests”, thus breaking the adage of “you’ll never see a bad backtest”. I have shown thoroughness in my research, and the same thoroughness has been applied towards this system as well. Until there is a longer track record such that the system can stand on its own, the trust in the system is the trust in the system’s creator.


Who is the intended audience for these signals?


The intended audience is individual, retail investors with a certain risk tolerance, and is priced accordingly.


​Isn’t volatility investing very risky?


​It’s risky from the perspective of the underlying instrument having the capacity to realize very large drawdowns (greater than 60%, and even greater than 90%). However, from a purely numerical standpoint, the company taking over so much of shopping, Amazon, since inception has had a 37.1% annualized rate of return, a standard deviation of 61.5%, a worst drawdown of 94%, and an Ulcer Performance Index of 0.9. By comparison, XIV, from 2008 (using synthetic data), has had a 35.5% annualized rate of return, a standard deviation of 57.7%, a worst drawdown of 92%, and an Ulcer Performance Index of 0.6. If Amazon is considered a top-notch asset, then from a quantitative comparison, a system looking to capitalize on volatility bets should be viewed from a similar perspective. To be sure, the strategy’s performance vastly outperforms that of buying and holding XIV (which nobody should do). However, the philosophy of volatility products being much riskier than household tech names just does not hold true unless the future wildly differs from the past.


​Is there a possibility for collaborating with other strategy creators?


​Feel free to contact me at my email ilya. kipnis@gmail to discuss that possibility. I request a daily stream of returns before starting any discussion.


Because past all the artsy-craftsy window dressing and interesting choice of vocabulary, Patreon is simply a platform that processes payments and creates a centralized platform from which to post subscription-based content, as opposed to maintaining mailing lists and other technical headaches. Essentially, it’s simply a way to outsource the technical end of running a business, even if the window dressing is a bit unorthodox.


Obrigado pela leitura.


NOTE: I am currently interested in networking and full-time roles based on my skills. My LinkedIn profile can be found here.


The Return of Free Data and Possible Volatility Trading Subscription.


This post will be about pulling free data from AlphaVantage, and gauging interest for a volatility trading subscription service.


So first off, ever since the yahoos at Yahoo decided to turn off their free data, the world of free daily data has been in somewhat of a dark age. Well, thanks to blog. fosstrading/2017/10/getsymbols-and-alpha-vantage. html#gpluscommentsJosh Ulrich, Paul Teetor, and other R/Finance individuals, the latest edition of quantmod (which can be installed from CRAN) now contains a way to get free financial data from AlphaVantage since the year 2000, which is usually enough for most backtests, as that date predates the inception of most ETFs.


Here’s how to do it.


Once you do that, downloading data is simple, if not slightly slow. Here’s how to do it.


And the results:


Which means if any one of my old posts on asset allocation has been somewhat defunct thanks to bad yahoo data, it will now work again with a slight modification to the data input algorithms.


Beyond demonstrating this routine, one other thing I’d like to do is to gauge interest for a volatility signal subscription service, for a system I have personally started trading a couple of months ago.


Simply, I have seen other websites with subscription services with worse risk/reward than the strategy I currently trade, which switches between XIV, ZIV, and VXX. Currently, the equity curve, in log 10, looks like this:


That is, $1000 in 2008 would have become approximately $1,000,000 today, if one was able to trade this strategy since then.


Since 2018 (around the time of inception for XIV), the performance has been:


Considering that some websites out there charge upwards of $50 a month for either a single tactical asset rotation strategy (and a lot more for a combination) with inferior risk/return profiles, or a volatility strategy that may have had a massive and historically record-breaking drawdown, I was hoping to gauge a price point for what readers would consider paying for signals from a better strategy than those.


Obrigado pela leitura.


NOTE: I am currently interested in networking and am seeking full-time opportunities related to my skill set. My LinkedIn profile can be found here.


The Kelly Criterion — Funciona?


This post will be about implementing and investigating the running Kelly Criterion — that is, a constantly adjusted Kelly Criterion that changes as a strategy realizes returns.


For those not familiar with the Kelly Criterion, it’s the idea of adjusting a bet size to maximize a strategy’s long term growth rate. Both https://en. wikipedia/wiki/Kelly_criterionWikipedia and Investopedia have entries on the Kelly Criterion. Essentially, it’s about maximizing your long-run expectation of a betting system, by sizing bets higher when the edge is higher, and vice versa.


There are two formulations for the Kelly criterion: the Wikipedia result presents it as mean over sigma squared. The Investopedia definition is P-[(1-P)/winLossRatio], where P is the probability of a winning bet, and the winLossRatio is the average win over the average loss.


In any case, here are the two implementations.


Let’s try this with some data. At this point in time, I’m going to show a non-replicable volatility strategy that I currently trade.


For the record, here are its statistics:


Now, let’s see what the Wikipedia version does:


The results are simply ridiculous. And here would be why: say you have a mean return of .0005 per day (5 bps/day), and a standard deviation equal to that (that is, a Sharpe ratio of 1). You would have 1/.0005 = 2000. In other words, a leverage of 2000 times. This clearly makes no sense.


The other variant is the more particular Investopedia definition.


Looks a bit more reasonable. However, how does it stack up against not using it at all?


Turns out, the fabled Kelly Criterion doesn’t really change things all that much.


For the record, here are the statistical comparisons:


Obrigado pela leitura.


NOTE: I am currently looking for my next full-time opportunity, preferably in New York City or Philadelphia relating to the skills I have demonstrated on this blog. My LinkedIn profile can be found here. If you know of such opportunities, do not hesitate to reach out to me.


Leverage Up When You’re Down?


This post will investigate the idea of reducing leverage when drawdowns are small, and increasing leverage as losses accumulate. It’s based on the idea that whatever goes up must come down, and whatever comes down generally goes back up.


I originally came across this idea from this blog post.


So, first off, let’s write an easy function that allows replication of this idea. Essentially, we have several arguments:


One: the default leverage (that is, when your drawdown is zero, what’s your exposure)? For reference, in the original post, it’s 10%.


Next: the various leverage levels. In the original post, the leverage levels are 25%, 50%, and 100%.


And lastly, we need the corresponding thresholds at which to apply those leverage levels. In the original post, those levels are 20%, 40%, and 55%.


So, now we can create a function to implement that in R. The idea being that we have R compute the drawdowns, and then use that information to determine leverage levels as precisely and frequently as possible.


Here’s a quick piece of code to do so:


So, let’s replicate some results.


And our results look something like this:


That said, what would happen if one were to extend the data for all available XIV data?


A different story.


In this case, I think the takeaway is that such a mechanism does well when the drawdowns for the benchmark in question occur sharply, so that the lower exposure protects from those sharp drawdowns, and then the benchmark spends much of the time in a recovery mode, so that the increased exposure has time to earn outsized returns, and then draws down again. When the benchmark continues to see drawdowns after maximum leverage is reached, or continues to perform well when not in drawdown, such a mechanism falls behind quickly.


As always, there is no free lunch when it comes to drawdowns, as trying to lower exposure in preparation for a correction will necessarily mean forfeiting a painful amount of upside in the good times, at least as presented in the original post.


Obrigado pela leitura.


NOTE: I am currently looking for my next full-time opportunity, preferably in New York City or Philadelphia relating to the skills I have demonstrated on this blog. My LinkedIn profile can be found here. If you know of such opportunities, do not hesitate to reach out to me.


Let’s Talk Drawdowns (And Affiliates)


This post will be directed towards those newer in investing, with an explanation of drawdowns–in my opinion, a simple and highly important risk statistic.


Would you invest in this?


As it turns out, millions of people do, and did. That is the S&P 500, from 2000 through 2018, more colloquially referred to as “the stock market”. Plenty of people around the world invest in it, and for a risk to reward payoff that is very bad, in my opinion. This is an investment that, in ten years, lost half of its value–twice!


At its simplest, an investment–placing your money in an asset like a stock, a savings account, and so on, instead of spending it, has two things you need to look at.


First, what’s your reward? If you open up a bank CD, you might be fortunate to get 3%. If you invest it in the stock market, you might get 8% per year (on average) if you held it for 20 years. In other words, you stow away $100 on January 1st, and you might come back and find $108 in your account on December 31st. This is often called the compound annualized growth rate (CAGR)–meaning that if you have $100 one year, earn 8%, you have 108, and then earn 8% on that, and so on.


The second thing to look at is the risk. What can you lose? The simplest answer to this is “the maximum drawdown”. If this sounds complicated, it simply means “the biggest loss”. So, if you had $100 one month, $120 next month, and $90 the month after that, your maximum drawdown (that is, your maximum loss) would be 1 – 90/120 = 25%.


When you put the reward and risk together, you can create a ratio, to see how your rewards and risks line up. This is called a Calmar ratio, and you get it by dividing your CAGR by your maximum drawdown. The Calmar Ratio is a ratio that I interpret as “for every dollar you lose in your investment’s worst performance, how many dollars can you make back in a year?” For my own investments, I prefer this number to be at least 1, and know of a strategy for which that number is above 2 since 2018, or higher than 3 if simulated back to 2008.


Most stocks don’t even have a Calmar ratio of 1, which means that on average, an investment makes more than it can possibly lose in a year. Even Amazon, the company whose stock made Jeff Bezos now the richest man in the world, only has a Calmar Ratio of less than 2/5, with a maximum loss of more than 90% in the dot-com crash. The S&P 500, again, “the stock market”, since 1993, has a Calmar Ratio of around 1/6. That is, the worst losses can take *years* to make back.


A lot of wealth advisers like to say that they recommend a large holding of stocks for young people. In my opinion, whether you’re young or old, losing half of everything hurts, and there are much better ways to make money than to simply buy and hold a collection of stocks.


For those with coding skills, one way to gauge just how good or bad an investment is, is this:


An investment has a history–that is, in January, it made 3%, in February, it lost 2%, in March, it made 5%, and so on. By shuffling that history around, so that say, January loses 2%, February makes 5%, and March makes 3%, you can create an alternate history of the investment. It will start and end in the same place, but the journey will be different. For investments that have existed for a few years, it is possible to create many different histories, and compare the Calmar ratio of the original investment to its shuffled “alternate histories”. Ideally, you want the investment to be ranked among the highest possible ways to have made the money it did.


To put it simply: would you rather fall one inch a thousand times, or fall a thousand inches once? Well, the first one is no different than jumping rope. The second one will kill you.


Here is some code I wrote in R (if you don’t code in R, don’t worry) to see just how the S&P 500 (the stock market) did compared to how it could have done.


This is the resulting plot:


That red line is the actual performance of the S&P 500 compared to what could have been. And of the 1000 different simulations, only 91 did worse than what happened in reality.


This means that the stock market isn’t a particularly good investment, and that you can do much better using tactical asset allocation strategies.


One site I’m affiliated with, is AllocateSmartly. It is a cheap investment subscription service ($30 a month) that compiles a collection of asset allocation strategies that perform better than many wealth advisers. When you combine some of those strategies, the performance is better still. To put it into perspective, one model strategy I’ve come up with has this performance:


In this case, the compound annualized growth rate is nearly double that of the maximum loss. For those interested in something a bit more aggressive, this strategy ensemble uses some fairly conservative strategies in its approach.


In conclusion, when considering how to invest your money, keep in mind both the reward, and the risk. One very simple and important way to understand risk is how much an investment can possibly lose, from its highest, to its lowest value following that peak. When you combine the reward and the risk, you can get a ratio that tells you about how much you can stand to make for every dollar lost in an investment’s worst performance.


Obrigado pela leitura.


NOTE: I am interested in networking opportunities, projects, and full-time positions related to my skill set. If you are looking to collaborate, please contact me on my LinkedIn here.


An Out of Sample Update on DDN’s Volatility Momentum Trading Strategy and Beta Convexity.


The first part of this post is a quick update on Tony Cooper’s of Double Digit Numerics’s volatility ETN momentum strategy from the volatility made simple blog (which has stopped updating as of a year and a half ago). The second part will cover Dr. Jonathan Kinlay’s Beta Convexity concept.


So, now that I have the ability to generate a term structure and constant expiry contracts, I decided to revisit some of the strategies on Volatility Made Simple and see if any of them are any good (long story short: all of the publicly detailed ones aren’t so hot besides mine–they either have a massive drawdown in-sample around the time of the crisis, or a massive drawdown out-of-sample).


Why this strategy? Because it seemed different from most of the usual term structure ratio trades (of which mine is an example), so I thought I’d check out how it did since its first publishing date, and because it’s rather easy to understand.


Here’s the strategy:


Take XIV, VXX, ZIV, VXZ, and SHY (this last one as the “risk free” asset), and at the close, invest in whichever has had the highest 83 day momentum (this was the result of optimization done on volatilityMadeSimple).


Here’s the code to do this in R, using the Quandl EOD database. There are two variants tested–observe the close, buy the close (AKA magical thinking), and observe the close, buy tomorrow’s close.


Here are the results.


Looks like this strategy didn’t pan out too well. Just a daily reminder that if you’re using fine grid-search to select a particularly good parameter (EG n = 83 days? Maybe 4 21-day trading months, but even that would have been n = 82), you’re asking for a visit from, in the words of Mr. Tony Cooper, a visit from the grim reaper.


Moving onto another topic, whenever Dr. Jonathan Kinlay posts something that I think I can replicate that I’d be very wise to do so, as he is a very skilled and experienced practitioner (and also includes me on his blogroll).


A topic that Dr. Kinlay covered is the idea of beta convexity–namely, that an asset’s beta to a benchmark may be different when the benchmark is up as compared to when it’s down. Essentially, it’s the idea that we want to weed out firms that are what I’d deem as “losers in disguise”–I. E. those that act fine when times are good (which is when we really don’t care about diversification, since everything is going up anyway), but do nothing during bad times.


The beta convexity is calculated quite simply: it’s the beta of an asset to a benchmark when the benchmark has a positive return, minus the beta of an asset to a benchmark when the benchmark has a negative return, then squaring the difference. That is, (beta_bench_positive – beta_bench_negative) ^ 2.


Here’s some R code to demonstrate this, using IBM vs. the S&P 500 since 1995.


Obrigado pela leitura.


NOTE: I am always looking to network, and am currently actively looking for full-time opportunities which may benefit from my skill set. If you have a position which may benefit from my skills, do not hesitate to reach out to me. My LinkedIn profile can be found here.


Um exemplo de uma estratégia comercial codificada usando o pacote Quantmod em R.


O back-testing de uma estratégia de negociação pode ser implementado em quatro etapas.


Obtendo os dados históricos Formule a estratégia de negociação e especifique as regras Execute a estratégia nos dados históricos Avalie as métricas de desempenho.


Nesta publicação, voltaremos a testar a nossa estratégia de negociação em R. O pacote quantmod tornou muito fácil extrair dados históricos do Yahoo Finance. O código de uma linha abaixo obtém dados NSE (Nifty).


O Quantmod fornece vários recursos para visualizar dados. O comando abaixo cria um gráfico para os dados NSE.


TA = "Nulo" indica não usar nenhum indicador técnico. Veremos logo a aplicação de um indicador técnico em um gráfico. O próximo passo é escolher uma estratégia de negociação. Nós escolheremos MACD (Divergência de Convergência Médica em Movimento) para este exemplo. Em uma estratégia de cruzamento média móvel, duas médias são calculadas, uma média lenta e uma média móvel rápida. A diferença entre a média móvel rápida e a média lenta média é chamada de linha MACD. Uma terceira média chamada linha de sinal; uma média móvel exponencial de 9 dias do sinal MACD, também é calculada. Se a linha MACD cruza acima da linha de sinal, então é um sinal de alta e nós ficamos longos. Se a linha MACD cruza abaixo da linha de sinal, então é um sinal de baixa e ficamos curtos. Escolhemos o preço de fechamento dos dados NSE para calcular as médias. O comando seguinte cumpre esta tarefa.


O comando abaixo calcula o MACD para o preço de fechamento.


Pode-se escolher parâmetros variáveis ​​para médias rápidas, lentas e de sinal, dependendo dos requisitos de negociação. Aqui ficamos com os parâmetros padrão. MACD é a função em quantmod que calcula a divergência de convergência média móvel, os dados são o preço de fechamento para NSE, nFast é a média em movimento rápido, nSlow é a média lenta, maType = SMA indica que escolhemos média móvel simples, percentagem = FALSO implica que estamos calculando a diferença entre média em movimento rápido e média lenta. Defini-lo VERDADEIRO retornaria a diferença percentual entre a média móvel rápida e a média lenta.


O comando a seguir traça o gráfico para o preço de fechamento da NSE, juntamente com os parâmetros do MACD.


Conforme discutido anteriormente, definimos nosso sinal de negociação da seguinte forma:


Se o sinal MACD se cruzou acima da linha de sinal, vamos longamente NSE Se o sinal MACD cruzado abaixo da linha de sinal, ficamos curtos em NSE.


O comando seguinte gera o sinal de negociação de acordo. Utilizamos o operador de desfasamento para eliminar o viés de avanço.


sinal = Lag (ifelse (macd $ macd & lt; macd $ signal, -1, 1))


Vamos aplicar essa estratégia nos dados históricos da NSE de 2007-09-17 a 2018-09-22. O sinal de negociação é aplicado ao preço de fechamento para obter os retornos de nossa estratégia.


A função ROC fornece a diferença percentual entre os dois preços de fechamento. Podemos escolher a duração para a qual queremos ver os retornos. O seguinte comando escolhe os retornos entre 2008-06-02 e 2018-09-22.


Os retornos cumulativos podem ser calculados e plotados usando os seguintes comandos: -


O 4º passo do back-testing é avaliar métricas de desempenho. O pacote de análise de desempenho em R fornece uma plataforma consolidada para observar os parâmetros relacionados ao desempenho. Várias métricas, como retrabalhos, risco de queda podem ser observadas em R.


O comando seguinte fornece um resumo dos parâmetros acima mencionados e muito mais!


Aqui está a versão sucinta do código.


macd = MACD (data, nFast = 12, nSlow = 26, nSig = 9, maType = SMA, percent = FALSE)


sinal = Lag (ifelse (macd $ macd & lt; macd $ signal, -1, 1))


Depois de passar por esse exemplo, você aprendeu os conceitos básicos sobre como projetar uma estratégia de comércio de quantos usando R. Agora, você pode começar a aprender sobre como começar com o pacote Quantmod em R. Depois de aprender e aprender esses princípios você pode testar suas habilidades em nosso curso interativo de 10 horas de duração do caminho de dados do modelo de "modelo de estratégia quantitativa de negociação em R"


Posts Relacionados:


Um pensamento sobre "Um exemplo de uma estratégia comercial codificada usando o pacote Quantmod em R"


20 de dezembro de 2018.


Executei o script R acima e traçam os 3 gráficos, mas como interpretá-los.

No comments:

Post a Comment