Estratégias de negociação com r


Estratégias de negociação com r
Obter através da App Store Leia esta publicação em nosso aplicativo!
R: Backtesting uma estratégia de negociação. Iniciantes para quantmod e R.
Eu sou muito novo para a R e tentando testar uma estratégia que já programei no WealthLab.
Várias coisas que eu não entendo (e isso não funciona obviamente :)
Eu não consigo os Close Prices muito bem em um vetor. ou algum tipo de vetor, mas começa com estrutura e eu realmente não entendo o que essa função faz. É por isso que a minha série [1] provavelmente não funciona.
n & lt; - nrow (series) também não funciona, mas eu preciso disso para o Loop.
Então eu acho que se eu obtiver essas 2 perguntas respondidas, minha estratégia deve funcionar. Estou muito agradecido por qualquer ajuda ... R parece bastante complicado mesmo com a experiência de programação em outras línguas.
Começando com a segunda pergunta.
Então, se você quer trabalhar no objeto xts real, você precisa usar get.
Sobre sua primeira pergunta - eu não acho que você realmente precisa puxar os dados como um vetor - o objeto xts é uma matriz indexada por data e é fácil de trabalhar. Se você ainda deseja obter os dados que você pode usar.
Agora, para que você comece com um simples teste de respostas de estratégias, sugerirei trabalhar nas seguintes etapas.
defina sua estratégia. 2. Crie uma matriz ou adicione uma coluna ao seu objeto xts que representará sua posição para cada dia. 1 por muito tempo, 0 para nenhuma posição e -1 para breve (mais tarde você pode jogar com o número de alavancagem). 3. multiplique cada dia retorna com a posição e você obterá seu vetor de retorno de estratégia. 4. examine os resultados - minha recomendação é PerformanceAnalytics.
Estratégia simples - compre quando estiver perto da SMA20, venda abaixo.

Estratégia de Negociação Quantitativa Usando R: Um Guia Passo a Passo.
Nesta publicação, discutiremos sobre a construção de uma estratégia de negociação usando R. Antes de morar nos jargões comerciais usando R, vamos passar algum tempo entendendo o que R é. R é uma fonte aberta. Existem mais de 4000 extras em pacotes, mais 18000 membros do grupo do LinkedIn e perto de 80 R grupos Meetup atualmente existentes. É uma ferramenta perfeita para análise estatística, especialmente para análise de dados. A configuração concisa da Rede de Arquivo Abrangente R sabe que o CRAN fornece a lista de pacotes junto com a instalação básica necessária. Há muitos pacotes disponíveis dependendo da análise que precisa ser feita. Para implementar a estratégia de negociação, usaremos o pacote chamado quantstrat.
Processo em Quatro Passos de qualquer Estratégia de Negociação Básica.
Formação de hipóteses Testando a produção de refinação.
Nossa hipótese é formulada como “mercado é revertido à média”. A reversão à média é uma teoria que sugere que os preços acabam voltando ao valor médio. O segundo passo consiste em testar a hipótese para a qual formulamos uma estratégia em nossa hipótese e computamos indicadores, sinais e métricas de desempenho. A fase de teste pode ser dividida em três etapas, obter os dados, escrever a estratégia e analisar a saída. Neste exemplo, consideramos NIFTY-Bees. É um fundo negociado em bolsa administrado pela Goldman Sachs. A NSE tem um enorme volume para o instrumento, portanto, consideramos isso. A imagem abaixo mostra o preço Open-High-Low-Close do mesmo.
Nós estabelecemos um nível limiar para comparar as flutuações no preço. Se o preço aumenta / diminui, atualizamos a coluna de limite. O preço de fechamento é comparado com a faixa superior e com a faixa inferior. Quando a banda superior é cruzada, é um sinal para vender. Da mesma forma, quando a banda inferior é cruzada, é um sinal de venda.
A seção de codificação pode ser resumida como segue,
Uma visão de helicóptero para a saída da estratégia é dada no diagrama abaixo.
Assim, nossa hipótese de que o mercado é um retorno significativo é suportada. Como este é o back-testing, temos espaço para refinar os parâmetros de negociação que melhorariam nossos retornos médios e os lucros realizados. Isso pode ser feito definindo diferentes níveis de limite, regras de entrada mais rigorosas, stop loss etc. Pode-se escolher mais dados para back-testing, usar a abordagem bayseiana para configurar o limiar, considerar a volatilidade.
Uma vez que você está confiante sobre a estratégia de negociação apoiada pelos resultados dos back-testing, você pode entrar em negociação ao vivo. O ambiente de produção é um grande tópico em si e está fora do escopo no contexto do artigo. Para explicar em breve, isso envolveria escrever a estratégia em uma plataforma de negociação.
Como mencionado anteriormente, estaríamos construindo o modelo usando o pacote quantstrat. O Quantstrat fornece uma infra-estrutura genérica para modelo e estratégias quantitativas baseadas em sinal de backtest. É uma camada de abstração de alto nível (construída em xts, FinancialInstrument, blotter, etc.) que permite construir e testar estratégias em poucas linhas de código.
As principais características do quantstrat são,
Suporta estratégias que incluem indicadores, sinais e regras Permite que estratégias sejam aplicadas a portfólios de múltiplos ativos Suporta os tipos de pedidos de mercado, limite, stoplimit e stoptrailing Suporta o dimensionamento de pedidos e a otimização de parâmetros.
Neste post, construímos uma estratégia que inclui indicadores, sinais e regras.
Para um modelo baseado em sinal genérico, os seguintes objetos devem ser considerados,
Instrumentos - Contém indicadores de dados de mercado - Valores quantitativos derivados de dados de mercado Sinais - Resultado da interação entre dados de mercado e indicadores Regras - Gerar ordens usando dados de mercado, indicadores e sinais.
Sem muito tempo, vamos discutir a parte de codificação. Nós preferimos R studio para codificação e insistimos que você use o mesmo. Você precisa ter determinados pacotes instalados antes de programar a estratégia.
O seguinte conjunto de comandos instala os pacotes necessários.
Depois de instalar os pacotes, você os importa para uso posterior.
Leia os dados do arquivo csv e converta-o em objeto xts.
Inicializamos o portfólio com o estoque, moeda, capital inicial e o tipo de estratégia.
Adicione o limite de posição se você deseja negociar mais de uma vez no mesmo lado.
Crie o objeto de estratégia.
Construímos uma função que calcula os limiares que queremos negociar. Se o preço se move por thresh1, atualizamos o limite para o novo preço. Novas bandas para negociação são Threshold +/- Thresh2. A saída é um objeto xts, embora usemos a função reclass para garantir.
Adicione o indicador, o sinal e a regra de negociação.
Execute a estratégia e veja o caderno de pedidos.
Atualize o portfólio e veja as estatísticas comerciais.
Aqui está o código completo.
Uma vez que você esteja familiarizado com esses conceitos básicos, você poderia dar uma olhada em como começar a usar o pacote quantimod em R. Ou no caso de você ser bom no C ++, veja uma estratégia de exemplo codificada em C ++.
Se você é um profissional de varejo ou um profissional da área de tecnologia que deseja iniciar sua própria agência de negociação automatizada, comece a aprender o comércio de algoritmos hoje mesmo! Comece com conceitos básicos como arquitetura de negociação automatizada, microestrutura de mercado, sistema de backtesting de estratégia e sistema de gerenciamento de pedidos.
Comentários estão fechados.
Posts populares recentes.
Artigos mais visitados da semana.
Empregos para usuários R.
É alimentado pelo WordPress usando um design bavotasan.
Direitos autorais e cópia; 2017 R-bloggers. Todos os direitos reservados. Termos e Condições para este site.

Cursos recomendados.
Introdução ao Python para Data Science.
Domine os fundamentos da análise de dados no Python. Expanda seu conjunto de habilidades aprendendo computação científica com numpy.
Data Science Instructor na DataCamp.
Introdução a R.
Mestre os conceitos básicos de análise de dados, manipulando estruturas de dados comuns, como vetores, matrizes e quadros de dados.
Co-fundador e CEO da DataCamp.
Introdução ao SQL para Data Science.
Mestre os conceitos básicos de consulta de bancos de dados com SQL, o idioma de banco de dados mais popular do mundo.
Diretor de Conteúdo da DataCamp.
Explore a nossa Biblioteca de cursos.
Python intermediário para ciência de dados.
Aumente suas habilidades em ciência de dados criando visualizações usando o matplotlib e manipulando quadros de dados com Pandas.
Instrutor de ciência de dados no DataCamp.
R intermediária
Continue sua jornada para se tornar um R ninja aprendendo sobre declarações condicionais, loops e funções vetoriais.
Instrutor de ciência de dados no DataCamp.
Introdução ao Git for Data Science.
Este curso é uma introdução ao controle de versão com o Git para cientistas de dados.
Chefe de Treinamento de Instrutor no DataCamp.
Python Data Science Toolbox (Parte 1)
Aprenda a arte de escrever suas próprias funções no Python, além de conceitos importantes como escopo e tratamento de erros.
Data Scientist em DataCamp.
Aprendizado supervisionado com scikit-learn.
Aprenda como construir e ajustar modelos preditivos e avaliar o desempenho deles em dados não vistos.
Desenvolvedor central de scikit-learn; Professor na Universidade de Columbia.
Importando Dados em Python (Parte 1)
Aprenda a importar dados para o Python de várias fontes, como Excel, SQL, SAS e diretamente da web.
Data Scientist no DataCamp.
Navegue por Tópico.
Programação.
Importando & amp; Dados de limpeza.
Manipulação de dados.
Visualização de dados.
Probabilidade & amp; Estatisticas.
Aprendizado de máquinas.
Finanças Aplicadas.
Estudos de caso.
Navegue pela tecnologia.
Concha.
Próximos cursos
Computação Paralela com Dask.
O Python agora está bem estabelecido como uma plataforma importante para análise de dados e ciência dos dados. Para muitos cientistas de dados, o.
Diretor de Treinamento na Anaconda.
Pronto para aprender.
Junte-se a 2.040.000 Data Science Enthusiasts hoje mesmo!
Recursos.
Sobre.
O DataCamp oferece cursos interativos de R e Python sobre tópicos em ciência de dados, estatística e aprendizado de máquina. Aprenda com uma equipe de professores especializados no conforto do seu navegador com aulas de vídeo e divertidos desafios de codificação.

O R Trader.
Usando R e ferramentas relacionadas em Finanças Quantitativas.
Visualizando dados de séries temporais em R.
É com muito prazer que anuncio meu curso do DataCamp sobre Visualização de Dados de Séries Temporais em R. Esse curso também faz parte da série de Períodos Temporais com a faixa de habilidades R. Sinta-se livre para dar uma olhada, o primeiro capítulo é grátis!
Descrição do Curso.
Como diz o ditado, "Um gráfico vale mais que mil palavras". É por isso que a visualização é a maneira mais usada e poderosa de entender melhor seus dados. Após este curso, você terá uma visão geral muito boa dos recursos de visualização da série temporal R e poderá decidir melhor qual modelo escolher para a análise subsequente. Você também poderá transmitir a mensagem que deseja entregar de forma eficiente e linda.
Esboço de Curso.
Capítulo 1: R Time Series Visualization Tools.
Este capítulo apresentará as ferramentas básicas de visualização da série temporal R.
Capítulo 2: séries temporais univariadas.
Gráficos univariados são projetados para aprender o máximo possível sobre a distribuição, a tendência central e a disseminação dos dados disponíveis. Neste capítulo, você receberá algumas ferramentas visuais usadas para diagnosticar séries de tempos univariados.
Capítulo 3: séries temporais multivariadas.
O que fazer se você tiver que lidar com séries temporais multivariadas? Neste capítulo, você aprenderá como identificar padrões na distribuição, tendência central e propagação em pares ou grupos de dados.
Capítulo 4: Estudo de caso: selecionando visualmente um estoque que melhora sua carteira existente.
Deixe colocar tudo o que aprendeu até agora na prática! Imagine que você já possui um portfólio de ações e você tem algum dinheiro extra para investir, como você pode escolher com sabedoria um novo estoque para investir seu dinheiro adicional? Analisar as propriedades estatísticas das ações individuais versus um portfólio existente é uma boa maneira de abordar o problema.
Vinculando R ao 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. Eu uso o IQFeed há alguns anos e estou feliz com ele (não estou 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 que fiz alguns testes, mudei meu código que ainda estava em Python para R. Apenas para completar, aqui está um link que explica como baixar dados históricos do IQFeed usando 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 faz o download dos 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 facilita o processo de gerenciar e armazenar dados do mercado de ticks. 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 armazenar. 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 por uma das abaixo.
Agora, você deseja recuperar alguns dos dados armazenados, basta executar algo como:
Observe que apenas os ticks são suportados no armazenamento local, portanto, o período deve ser & # 8216; tick & # 8217;
O QuantTools fornece a função plot_ts para plotar dados de séries temporais sem fins de semana, feriados e lacunas durante a noite. No exemplo abaixo, primeiro recupero os dados armazenados acima, depois seleciono as primeiras 100 observações de preço e, finalmente, desenho o gráfico.
Duas coisas para notar: primeiro espião é um objeto data. table, portanto, a sintaxe acima. Para obter uma visão geral rápida dos recursos do data. table, confira esta excelente folha de dicas do 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, qualquer comentário é bem-vindo.
BERT: um recém-chegado na conexão 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. É gratuito (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 do Excel, é para escrever Funções definidas pelo usuário (UDFs) em R.
Neste post eu não vou mostrar como R e Excel interagem via BERT. Há muito bons tutoriais aqui, aqui e aqui. Em vez disso, quero mostrar como usei BERT para construir uma torre de controle & # 8220; & # 8221; para minha negociação.
Meus sinais de negociação são gerados usando uma longa lista de arquivos R, mas eu preciso da flexibilidade do Excel para exibir os resultados de forma rápida e eficiente. Como mostrado acima, o BERT pode fazer isso para mim, mas também quero adaptar o aplicativo às minhas necessidades. Combinando o poder do XML, VBA, R e BERT, posso criar um aplicativo bonito, mas poderoso, na forma de um arquivo do 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 pode ser dividida nos três passos 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 do VBA são encapsuladas em torno de funções R definidas usando 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 materializa 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: No 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 habilitado para 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. Quando terminar, 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 os novos.
6 & # 8211; Clique no botão New: Agora volte para a planilha e no menu RTrader, clique no botão & # 8220; New Button & # 8221; botão. Você deve ver algo como o abaixo aparece.
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. Por fim, gostaria de 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 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 os dados de amostra: a parte dos dados usada 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 usados ​​para calibração (ou seja, na amostra) e 30% para validação (ou seja, 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 de 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 populacionais são idênticas, sem presumir 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.
Este post é inspirado nos dois artigos seguintes:
Vigier Alexandre, Chmil Swann (2007), "Efeitos de várias funções de otimização no desempenho fora da amostra de estratégias de negociação geneticamente evoluídas", prevendo a conferência sobre mercados financeiros.
Vigier Alexandre, Chmil Swann (2010), "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 2010.
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: "O SOFTWARE É FORNECIDO" COMO ESTÁ, SEM GARANTIA DE NENHUM TIPO "# 8230; & # 8221;
Como instalar e usar o fidlr?
Você pode obter o addin / package do seu repositório Github aqui (eu vou registrá-lo no 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 provedor de dados no menu suspenso Origem. Selecione um intervalo de datas no menu Data Insira o símbolo que você 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 opção 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 a perfeição, mas esperamos que melhore com o tempo. Informe qualquer comentário, sugestão, erro, etc. & # 8230; para: thertradergmail.
Mantendo um banco de dados de arquivos de preços em R.
Fazer pesquisa quantitativa implica muita análise de dados e é preciso dados limpos e confiáveis ​​para conseguir isso. O que é realmente necessário são dados limpos que sejam facilmente acessíveis (mesmo sem uma conexão com a Internet). A maneira mais eficiente de fazer isso para mim foi 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 (de preço) do Yahoo, Google, etc & # 8230; toda vez que eu quiser testar uma nova ideia, mas mais importante, uma vez que eu identifiquei e consertei um problema, eu 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 é resumido no gráfico abaixo.
Em tudo o que se segue, presumo que os dados estão vindo 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 apenas para este instrumento.
3 & # 8211; Crie um arquivo em lote (updateDailyPrices. bat)
Outra parte importante do trabalho é criar um arquivo em lotes que automatize o processo de atualização acima (eu sou um usuário do Windows). Isso evita abrir o R ​​/ RStudio e executar o código a partir dele. O código abaixo é colocado em um arquivo. bat (o caminho deve ser alterado com a configuração do leitor). Note 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 tenho usado isso por um tempo e tem funcionado muito bem para mim até agora. Para dados mais avançados e / ou freqüências mais altas, as coisas podem ficar muito mais complicadas.
Como de costume, todos os comentários são bem-vindos.
The Rise of the Robots (Advisors & # 8230;)
A indústria de gerenciamento de ativos está à beira de uma grande mudança. Nos últimos dois anos, os Robots Advisors (RA) surgiram como novos jogadores. O termo em si é difícil de definir, pois engloba uma grande variedade de serviços. Alguns são projetados para ajudar consultores tradicionais a alocar melhor o dinheiro de seus clientes e outros são “black box” real. O usuário insere alguns critérios (idade, renda, filhos, etc. & # 8230;) e o robô propõe uma alocação personalizada. Entre esses dois extremos, uma gama completa de ofertas está disponível. Eu achei a definição da Wikipedia muito boa. & # 8220; Eles são uma classe de consultor financeiro que fornece gerenciamento de portfólio on-line com uma intervenção humana mínima & # 8221 ;. Mais precisamente, eles usam o gerenciamento de portfólio baseado em algoritmo para oferecer o espectro completo de serviços que um consultor tradicional ofereceria: reinvestimento de dividendos, relatórios de conformidade, rebalanceamento de carteira, extração de impostos etc. & # 8230; (Bem, isso é o que a comunidade de investimentos quantitativos está fazendo há décadas!). A indústria ainda está em sua infância, com a maioria dos jogadores ainda gerenciando uma pequena quantia de dinheiro, mas eu só percebi o quão profunda a mudança foi quando eu estava em Nova York há alguns dias. Quando RA colocar seus nomes na TV ou no telhado do táxi de NYC, você sabe que algo grande está acontecendo & # 8230;
Está ficando cada vez mais atenção da mídia e, acima de tudo, faz muito sentido da perspectiva do investidor. Na verdade, existem duas vantagens principais no uso do RA:
Taxas significativamente mais baixas sobre os conselheiros tradicionais O investimento é mais transparente e mais simples, o que é mais atraente para pessoas com conhecimentos financeiros limitados.
Nesta publicação, R é apenas uma desculpa para apresentar bem o que é uma grande tendência no setor de gerenciamento de ativos. O gráfico abaixo mostra as partes de mercado da RA mais popular do final de 2014. O código usado para gerar o gráfico abaixo pode ser encontrado no final desta publicação e os dados estão aqui.
Esses números são um pouco datados, desde a rapidez com que essa indústria evolui, mas ainda é muito informativa. Não é de surpreender que o mercado seja dominado por provedores dos EUA como Wealthfront e Betterment, mas RA surgem em todo o mundo: Ásia (8Now!), Suíça (InvestGlass), França (Marie Quantier) & # 8230; .. Está começando a afetar significativamente da forma como os gestores de ativos tradicionais estão fazendo negócios. Um exemplo proeminente é a parceria entre Fidelity e Betterment. Desde dezembro de 2014, além da marca AUM de US $ 2 bilhões.
Apesar de tudo acima, acho que a verdadeira mudança está à nossa frente. Como eles usam menos intermediários e produtos de baixa comissão (como ETFs) eles cobram taxas muito mais baixas do que os conselheiros tradicionais. A RA certamente ganhará quotas de mercado significativas, mas também reduzirá as taxas cobradas pela indústria como um todo. Em última análise, isso afetará o modo como as empresas de investimento tradicionais fazem negócios. O gerenciamento de portfólio ativo que está tendo um tempo difícil por alguns anos agora sofrerá ainda mais. As altas taxas que cobra serão ainda mais difíceis de justificar, a menos que se reinvente. Outro impacto potencial é o aumento de ETFs e produtos financeiros de baixa comissão em geral. Obviamente, isso começou há um tempo, mas acho que o efeito será ainda mais pronunciado nos próximos anos. Novas gerações de ETF acompanham índices mais complexos e estratégias customizadas. Essa tendência ficará mais forte inevitavelmente.
Como de costume, qualquer comentário é bem-vindo.
R dicas de séries temporais financeiras que todos devem conhecer.
Há muitos tutoriais de séries temporais de R circulando na web que este post não foi projetado para ser um deles. Em vez disso, eu quero apresentar uma lista dos truques mais úteis que encontrei ao lidar com séries temporais financeiras em R. Algumas das funções apresentadas aqui são incrivelmente poderosas, mas infelizmente enterradas na documentação, portanto, meu desejo de criar uma publicação dedicada. Eu só abordo séries de tempos diários ou de frequência mais baixa. Lidar com dados de freqüência mais alta requer ferramentas específicas: pacotes de dados ou de alta freqüência são alguns deles.
xts: O pacote xts é o que deve ter quando se trata de séries de tempos em R. O exemplo abaixo carrega o pacote e cria uma série de tempo diária de 400 dias, normalmente retornados distribuídos.
merge. xts (pacote xts): Isso é incrivelmente poderoso quando se trata de unir duas ou mais séries de tempo se elas têm o mesmo tamanho ou não. O argumento de união faz a mágica! determina como a ligação é feita.
apply. yearly / apply. monthly (pacote xts): aplique uma função específica para cada período distinto em um determinado objeto de séries temporais. O exemplo abaixo calcula retornos mensais e anuais da segunda série no objeto tsInter. Note que eu uso a soma dos retornos (sem composição)
pontos de extremidade (pacote xts): extrair valores de índice de um determinado objeto xts correspondente às últimas observações, dado um período especificado por on. O exemplo dá o último dia do mês retorna para cada série no objeto tsInter usando o ponto final para selecionar a data.
na. locf (pacote zoológico): função genérica para substituir cada NA com o mais recente não-NA antes dele. Extremamente útil ao lidar com uma série de tempo com alguns furos # 8221; e quando esta série temporal é subsequentemente usada como entrada para uma função R que não aceita argumentos com NAs. No exemplo, crio uma série temporal de preços aleatórios, em seguida, inclui artificialmente alguns NAs e substitui-los pelo valor mais recente.
charts. PerformanceSummary (package PerformanceAnalytics): Para um conjunto de devoluções, crie um gráfico de índice de riqueza, barras para desempenho por período e gráfico submerso para redução. Isso é incrivelmente útil, pois exibe em uma única janela todas as informações relevantes para uma rápida inspeção visual de uma estratégia de negociação. O exemplo abaixo transforma a série de preços em um objeto xts e exibe uma janela com os 3 gráficos descritos acima.
A lista acima não é de forma alguma exaustiva, mas uma vez que você domine as funções descritas neste post, torna a manipulação de séries temporais financeiras muito mais fácil, o código mais curto e a legibilidade do código melhor.
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, é preciso manter mais estoques do que no segundo, onde nenhuma ação pode ser mantida se não houver 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 para a frente. 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 atento, 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). Essa 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 obter uma estimativa mais precisa do fator poder preditivo, é necessário dar um passo além e agrupar os estoques por quantis de valores de fatores e, em seguida, analisar o retorno médio a termo (ou qualquer outra métrica de tendência central) de cada um deles. 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 & amp; P500 (no momento da redação). Obviamente, existe um viés de sobrevivência: a lista de ações no índice mudou significativamente entre o início e o final do período de amostragem, no entanto, é bom o suficiente apenas para fins ilustrativos.
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 o Coeficiente de Informação e o Retorno de Quantiles. 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, o Q1 é mais baixo nos últimos 12 meses e o Q5, o 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. This is very significant and powerful for such a simple factor (not really a surprise though…). Therefore there are greater chances to beat the index by overweighting the stocks falling into Q5 and underweighting those falling into Q1 relative to the benchmark.
An IC of 0.0206 might not mean a great deal in itself but it’s significantly different from 0 and indicates a good predictive power of the past 12 months return overall. Formal significance tests can be evaluated but this is beyond the scope of this article.
The above framework is excellent for evaluating investments factor’s quality however there are a number of practical limitations that have to be addressed for real life implementation:
Rebalancing : In the description above, it’s assumed that at the end of each month the portfolio is fully rebalanced. This means all stocks falling in Q1 are underweight and all stocks falling in Q5 are overweight relative to the benchmark. This is not always possible for practical reasons: some stocks might be excluded from the investment universe, there are constraints on industry or sector weight, there are constraints on turnover etc… Transaction Costs : This has not be taken into account in the analysis above and this is a serious brake to real life implementation. Turnover considerations are usually implemented in real life in a form of penalty on factor quality. Transfer coefficient : This is an extension of the fundamental law of active management and it relaxes the assumption of Grinold’s model that managers face no constraints which preclude them from translating their investments insights directly into portfolio bets.
And finally, I’m amazed by what can be achieved in less than 80 lines of code with R…
As usual any comments welcome.
Risk as a “Survival Variable”
I come across a lot of strategies on the blogosphere some are interesting some are a complete waste of time but most share a common feature: people developing those strategies do their homework in term of analyzing the return but much less attention is paid to the risk side its random nature. I’ve seen comment like “a 25% drawdown in 2011 but excellent return overall”. Well my bet is that no one on earth will let you experience a 25% loss with their money (unless special agreements are in place). In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so for a few months before you gain a bit of credibility.
First let’s say you have a bad start and you lose money at the beginning. With a 10% drawdown you’re most certainly out but even with a 5% drawdown the chances of seeing your allocation reduced are very high. This has significant implications on your strategies. Let’s assume that if you lose 5% your allocation is divided by 2 and you come back to your initial allocation only when you passed the high water mark again (e. g. the drawdown comes back to 0). In the chart below I simulated the experiment with one of my strategies.
You start trading in 1st June 2003 and all goes well until 23rd Jul. 2003 where your drawdown curve hits the -5% threshold (**1**). Your allocation is cut by 50% and you don’t cross back the high water mark level until 05th Dec. 2003 (**3**). If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. 2003 (**2**) and by the end of the year you would have made more money.
But let’s push the reasoning a bit further. Still on the chart above, assume you get really unlucky and you start trading toward mid-June 2003. You hit the 10% drawdown limit by the beginning of August and you’re most likely out of the game. You would have started in early August your allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date….
The trading success of any individual has some form of path dependency and there is not much you can do about it. However you can control the size of a strategy’s drawdown and this should be addressed with great care. A portfolio should be diversified in every possible dimension: asset classes, investment strategies, trading frequencies etc…. From that perspective risk is your “survival variable”. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. Otherwise you won’t be there next month to see what happens.

The R Trader.
Using R and related tools in Quantitative Finance.
Archive for the ‘Trading Strategies’ Categoria.
Linking R to IQFeed with the QuantTools package.
IQFeed provides streaming data services and trading solutions that cover the Agricultural, Energy and Financial marketplace. It is a well known and recognized data feed provider geared toward retail users and small institutions. The subscription price starts at around $80/month.
Stanislav Kovalevsky has developed a package called QuantTools. It is an all in one package designed to enhance quantitative trading modelling. It allows to download and organize historical market data from multiple sources like Yahoo, Google, Finam, MOEX and IQFeed. The feature that interests me the most is the ability to link IQFeed to R. I’ve been using IQFeed for a few years and I’m happy with it (I’m not affiliated to the company in any way). More information can be found here. I’ve been looking for an integration within R for a while and here it is. As a result, after I ran a few tests, I moved my code that was still in Python into R. Just for completeness, here’s a link that explains how to download historical data from IQFeed using Python.
QuantTools offers four main functionalities: Get market data, Store/Retrieve market data, Plot time series data and Back testing.
First make sure that IQfeed is open. You can either download daily or intraday data. The below code downloads daily prices (Open, High, Low, Close) for SPY from 1st Jan 2017 to 1st June 2017.
The below code downloads intraday data from 1st May 2017 to 3rd May 2017.
Note the period parameter. It can take any of the following values: tick, 1min, 5min, 10min, 15min, 30min, hour, day, week, month, depending on the frequency you need.
QuantTools makes the process of managing and storing tick market data easy. You just setup storage parameters and you are ready to go. The parameters are where, since what date and which symbols you would like to be stored. Any time you can add more symbols and if they are not present in a storage, QuantTools tries to get the data from specified start date. The code below will save the data in the following directory: “C:/Users/Arnaud/Documents/Market Data/iqfeed”. There is one sub folder by instrument and the data is aved in. rds files.
You can also store data between specific dates. Replace the last line of code above with one of the below.
Now should you want to get back some of the data you stored, just run something like:
Note that only ticks are supported in local storage so period must be ‘tick’
QuantTools provides plot_ts function to plot time series data without weekend, holidays and overnight gaps. In the example below, I first retrieve the data stored above, then select the first 100 price observations and finally draw the chart.
Two things to notice: First spy is a data. table object hence the syntax above. To get a quick overview of data. table capabilities have a look at this excellent cheat sheet from DataCamp. Second the local parameter is TRUE as the data is retrieved from internal storage.
QuantTools allows to write your own trading strategy using its C++ API. I’m not going to elaborate on this as this is basically C++ code. You can refer to the Examples section on QuantTools website.
Overall I find the package extremely useful and well documented. The only missing bit is the live feed between R and IQFeed which will make the package a real end to end solution.
As usual any comments welcome.
BERT: a newcomer in the R Excel connection.
A few months ago a reader point me out this new way of connecting R and Excel. I don’t know for how long this has been around, but I never came across it and I’ve never seen any blog post or article about it. So I decided to write a post as the tool is really worth it and before anyone asks, I’m not related to the company in any way.
BERT stands for Basic Excel R Toolkit. It’s free (licensed under the GPL v2) and it has been developed by Structured Data LLC. At the time of writing the current version of BERT is 1.07. More information can be found here. From a more technical perspective, BERT is designed to support running R functions from Excel spreadsheet cells. In Excel terms, it’s for writing User-Defined Functions (UDFs) in R.
In this post I’m not going to show you how R and Excel interact via BERT. There are very good tutorials here, here and here. Instead I want to show you how I used BERT to build a “control tower” for my trading.
My trading signals are generated using a long list of R files but I need the flexibility of Excel to display results quickly and efficiently. As shown above BERT can do this for me but I also want to tailor the application to my needs. By combining the power of XML, VBA, R and BERT I can create a good looking yet powerful application in the form of an Excel file with minimum VBA code. Ultimately I have a single Excel file gathering all the necessary tasks to manage my portfolio: database update, signal generation, orders submission etc… My approach could be broken down in the 3 steps below:
Use XML to build user defined menus and buttons in an Excel file. The above menus and buttons are essentially calls to VBA functions. Those VBA functions are wrapup around R functions defined using BERT.
With this approach I can keep a clear distinction between the core of my code kept in R, SQL and Python and everything used to display and format results kept in Excel, VBA & XML. In the next sections I present the prerequisite to developed such an approach and a step by step guide that explains how BERT could be used for simply passing data from R to Excel with minimal VBA code.
1 – Download and install BERT from this link . Once the installation has completed you should have a new Add-Ins menu in Excel with the buttons as shown below. This is how BERT materialized in Excel.
2 & # 8211; Download and install Custom UI editor : The Custom UI Editor allows to create user defined menus and buttons in Excel ribbon. A step by step procedure is available here.
1 – R Code: The below R function is a very simple piece of code for illustration purposes only. It calculates and return the residuals from a linear regression. This is what we want to retrieve in Excel. Save this in a file called myRCode. R (any other name is fine) in a directory of your choice.
2 & # 8211; functions. R in BERT : From Excel select Add-Ins -> Home Directory and open the file called functions. R . In this file paste the following code. Make sure you insert the correct path.
This is just sourcing into BERT the R file you created above. Then save and close the file functions. R. Should you want to make any change to the R file created in step 1 you will have to reload it using the BERT button “Reload Startup File” from the Add-Ins menu in Excel.
3 & # 8211; In Excel: Create and save a file called myFile. xslm (any other name is fine). This is a macro-enabled file that you save in the directory of your choice. Once the file is saved close it.
4 & # 8211; Open the file created above in Custom UI editor : Once the file is open, paste the below code.
You should have something like this in the XML editor:
Essentially this piece of XML code creates an additional menu (RTrader), a new group (My Group) and a user defined button (New Button) in the Excel ribbon. Once you’re done, open myFile. xslm in Excel and close the Custom UI Editor. You should see something like this.
5 & ​​# 8211; Open VBA editor : In myFile. xlsm insert a new module. Paste the code below in the newly created module.
This erases previous results in the worksheet prior to coping new ones.
6 & # 8211; Click New Button : Now go back to the spreadsheet and in the RTrader menu click the “New Button” botão. You should see something like the below appearing.
The guide above is a very basic version of what can be achieved using BERT but it shows you how to combine the power of several specific tools to build your own custom application. From my perspective the interest of such an approach is the ability to glue together R and Excel obviously but also to include via XML (and batch) pieces of code from Python, SQL and more. This is exactly what I needed. Finally I would be curious to know if anyone has any experience with BERT?
Trading strategy: Making the most of the out of sample data.
When testing trading strategies a common approach is to divide the initial data set into in sample data: the part of the data designed to calibrate the model and out of sample data: the part of the data used to validate the calibration and ensure that the performance created in sample will be reflected in the real world. As a rule of thumb around 70% of the initial data can be used for calibration (i. e. in sample) and 30% for validation (i. e. out of sample). Then a comparison of the in and out of sample data help to decide whether the model is robust enough. This post aims at going a step further and provides a statistical method to decide whether the out of sample data is in line with what was created in sample.
In the chart below the blue area represents the out of sample performance for one of my strategies.
A simple visual inspection reveals a good fit between the in and out of sample performance but what degree of confidence do I have in this? At this stage not much and this is the issue. What is truly needed is a measure of similarity between the in and out of sample data sets. In statistical terms this could be translated as the likelihood that the in and out of sample performance figures coming from the same distribution. There is a non-parametric statistical test that does exactly this: the Kruskall-Wallis Test . A good definition of this test could be found on R-Tutor “A collection of data samples are independent if they come from unrelated populations and the samples do not affect each other. Using the Kruskal-Wallis Test , we can decide whether the population distributions are identical without assuming them to follow the normal distribution.” The added benefit of this test is not assuming a normal distribution.
It exists other tests of the same nature that could fit into that framework. The Mann-Whitney-Wilcoxon test or the Kolmogorov-Smirnov tests would perfectly suits the framework describes here however this is beyond the scope of this article to discuss the pros and cons of each of these tests. A good description along with R examples can be found here.
Here’s the code used to generate the chart above and the analysis:
In the example above the in sample period is longer than the out of sample period therefore I randomly created 1000 subsets of the in sample data each of them having the same length as the out of sample data. Then I tested each in sample subset against the out of sample data and I recorded the p-values. This process creates not a single p-value for the Kruskall-Wallis test but a distribution making the analysis more robust. In this example the mean of the p-values is well above zero (0.478) indicating that the null hypothesis should be accepted: there are strong evidences that the in and out of sample data is coming from the same distribution.
As usual what is presented in this post is a toy example that only scratches the surface of the problem and should be tailored to individual needs. However I think it proposes an interesting and rational statistical framework to evaluate out of sample results.
This post is inspired by the following two papers:
Vigier Alexandre, Chmil Swann (2007), “Effects of Various Optimization Functions on the Out of Sample Performance of Genetically Evolved Trading Strategies”, Forecasting Financial Markets Conference.
Vigier Alexandre, Chmil Swann (2010), « An optimization process to improve in/out of sample consistency, a Stock Market case», JP Morgan Cazenove Equity Quantitative Conference, London October 2010.
Introducing fidlr: FInancial Data LoadeR.
fidlr is an RStudio addin designed to simplify the financial data downloading process from various providers. This initial version is a wrapper around the getSymbols function in the quantmod package and only Yahoo, Google, FRED and Oanda are supported. I will probably add functionalities over time. As usual with those things just a kind reminder: “THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND…”
How to install and use fidlr?
You can get the addin/package from its Github repository here (I will register it on CRAN later on) Install the addin. There is an excellent tutorial to install RStudio Addins here. Once the addin is installed it should appear in the Addin menu. Just chose fidlr in the menu and a window as pictured below should appear. Choose a data provider from the the Source dropdown menu. Select a date range from the Date menu Enter the symbol you wish to download in the instrument text box. To download several symbols just enter the symbols separated by commas. Use the Radio buttons to choose whether you want to download the instrument in a csv file or in the global environment. The csv file will be saved in the working directory and there will be one csv file per instrument. Press Run to get the data or Close to close down the addin.
Error messages and warnings are handled by the underlying packages (quantmod and Shiny) and can be read from the console.
This is a very first version of the project so do not expect perfection but hopefully it will get better over time. Please report any comment, suggestion, bug etc… to: thertradergmail.
Maintaining a database of price files in R.
Doing quantitative research implies a lot of data crunching and one needs clean and reliable data to achieve this. What is really needed is clean data that is easily accessible (even without an internet connection). The most efficient way to do this for me has been to maintain a set of csv files. Obviously this process can be handled in many ways but I found very efficient and simple overtime to maintain a directory where I store and update csv files. I have one csv file per instrument and each file is named after the instrument it contains. The reason I do so is twofold: First, I don’t want to download (price) data from Yahoo, Google etc… every time I want to test a new idea but more importantly once I identified and fixed a problem, I don’t want to have to do it again the next time I need the same instrument. Simple yet very efficient so far. The process is summarized in the chart below.
In everything that follows, I assume that data is coming from Yahoo. The code will have to be amended for data from Google, Quandl etc… In addition I present the process of updating daily price data. The setup will be different for higher frequency data and other type of dataset (i. e. different from prices).
1 – Initial data downloading (listOfInstruments. R & historicalData. R)
The file listOfInstruments. R is a file containing only the list of all instruments.
If an instrument isn’t part of my list (i. e. no csv file in my data folder) or if you do it for the very first time you have to download the initial historical data set. The example below downloads a set of ETFs daily prices from Yahoo Finance back to January 2000 and store the data in a csv file.
2 & # 8211; Update existing data (updateData. R)
The below code starts from existing files in the dedicated folder and updates all of them one after the other. I usually run this process everyday except when I’m on holiday. To add a new instrument, simply run step 1 above for this instrument alone.
3 & # 8211; Create a batch file (updateDailyPrices. bat)
Another important part of the job is creating a batch file that automates the updating process above (I’m a Windows user). This avoids opening R/RStudio and run the code from there. The code below is placed on a. bat file (the path has to be amended with the reader’s setup). Note that I added an output file (updateLog. txt) to track the execution.
The process above is extremely simple because it only describes how to update daily price data. I’ve been using this for a while and it has been working very smoothly for me so far. For more advanced data and/or higher frequencies, things can get much trickier.
As usual any comments welcome.
Factor Evaluation in Quantitative Portfolio Management.
When it comes to managing a portfolio of stocks versus a benchmark the problem is very different from defining an absolute return strategy. In the former one has to hold more stocks than in the later where no stocks at all can be held if there is not good enough opportunity. The reason for that is the tracking error . This is defined as the standard deviation of the portfolio return minus the benchmark return. The less stocks is held vs. a benchmark the higher the tracking error (e. g higher risk).
The analysis that follows is largely inspired by the book “Active Portfolio Management” by Grinold & Kahn. This is the bible for anyone interested in running a portfolio against a benchmark. I strongly encourage anyone with an interest in the topic to read the book from the beginning to the end. It’s very well written and lays the foundations of systematic active portfolio management (I have no affiliation to the editor or the authors).
Here we’re trying to rank as accurately as possible the stocks in the investment universe on a forward return basis. Many people came up with many tools and countless variant of those tools have been developed to achieve this. In this post I focus on two simple and widely used metrics: Information Coefficient (IC) and Quantiles Return (QR).
The IC gives an overview of the factor forecasting ability. More precisely, this is a measure of how well the factor ranks the stocks on a forward return basis. The IC is defined as the rank correlation ( ρ ) between the metric (e. g. factor) and the forward return. In statistical terms the rank correlation is a nonparametric measure of dependance between two variables. For a sample of size n , the n raw scores are converted to ranks , and ρ is computed from:
The horizon for the forward return has to be defined by the analyst and it’s a function of the strategy’s turnover and the alpha decay (this has been the subject of extensive research). Obviously ICs must be as high as possible in absolute terms.
For the keen reader, in the book by Grinold & Kahn a formula linking Information Ratio (IR) and IC is given: with breadth being the number of independent bets (trades). This formula is known as the fundamental law of active management . The problem is that often, defining breadth accurately is not as easy as it sounds.
In order to have a more accurate estimate of the factor predictive power it’s necessary to go a step further and group stocks by quantile of factor values then analyse the average forward return (or any other central tendency metric) of each of those quantiles. The usefulness of this tool is straightforward. A factor can have a good IC but its predictive power might be limited to a small number of stocks. This is not good as a portfolio manager will have to pick stocks within the entire universe in order to meet its tracking error constraint. Good quantiles return are characterised by a monotonous relationship between the individual quantiles and forward returns.
All the stocks in the S&P500 index (at the time of writing). Obviously there is a survival ship bias: the list of stocks in the index has changed significantly between the start and the end of the sample period, however it’s good enough for illustration purposes only.
The code below downloads individual stock prices in the S&P500 between Jan 2005 and today (it takes a while) and turns the raw prices into return over the last 12 months and the last month. The former is our factor, the latter will be used as the forward return measure.
Below is the code to compute Information Coefficient and Quantiles Return. Note that I used quintiles in this example but any other grouping method (terciles, deciles etc…) can be used. it really depends on the sample size, what you want to capture and wether you want to have a broad overview or focus on distribution tails. For estimating returns within each quintile, median has been used as the central tendency estimator. This measure is much less sensitive to outliers than arithmetic mean.
And finally the code to produce the Quantiles Return chart.
3 & # 8211; How to exploit the information above?
In the chart above Q1 is lowest past 12 months return and Q5 highest. There is an almost monotonic increase in the quantiles return between Q1 and Q5 which clearly indicates that stocks falling into Q5 outperform those falling into Q1 by about 1% per month. This is very significant and powerful for such a simple factor (not really a surprise though…). Therefore there are greater chances to beat the index by overweighting the stocks falling into Q5 and underweighting those falling into Q1 relative to the benchmark.
An IC of 0.0206 might not mean a great deal in itself but it’s significantly different from 0 and indicates a good predictive power of the past 12 months return overall. Formal significance tests can be evaluated but this is beyond the scope of this article.
The above framework is excellent for evaluating investments factor’s quality however there are a number of practical limitations that have to be addressed for real life implementation:
Rebalancing : In the description above, it’s assumed that at the end of each month the portfolio is fully rebalanced. This means all stocks falling in Q1 are underweight and all stocks falling in Q5 are overweight relative to the benchmark. This is not always possible for practical reasons: some stocks might be excluded from the investment universe, there are constraints on industry or sector weight, there are constraints on turnover etc… Transaction Costs : This has not be taken into account in the analysis above and this is a serious brake to real life implementation. Turnover considerations are usually implemented in real life in a form of penalty on factor quality. Transfer coefficient : This is an extension of the fundamental law of active management and it relaxes the assumption of Grinold’s model that managers face no constraints which preclude them from translating their investments insights directly into portfolio bets.
And finally, I’m amazed by what can be achieved in less than 80 lines of code with R…
As usual any comments welcome.
Risk as a “Survival Variable”
I come across a lot of strategies on the blogosphere some are interesting some are a complete waste of time but most share a common feature: people developing those strategies do their homework in term of analyzing the return but much less attention is paid to the risk side its random nature. I’ve seen comment like “a 25% drawdown in 2011 but excellent return overall”. Well my bet is that no one on earth will let you experience a 25% loss with their money (unless special agreements are in place). In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so for a few months before you gain a bit of credibility.
First let’s say you have a bad start and you lose money at the beginning. With a 10% drawdown you’re most certainly out but even with a 5% drawdown the chances of seeing your allocation reduced are very high. This has significant implications on your strategies. Let’s assume that if you lose 5% your allocation is divided by 2 and you come back to your initial allocation only when you passed the high water mark again (e. g. the drawdown comes back to 0). In the chart below I simulated the experiment with one of my strategies.
You start trading in 1st June 2003 and all goes well until 23rd Jul. 2003 where your drawdown curve hits the -5% threshold (**1**). Your allocation is cut by 50% and you don’t cross back the high water mark level until 05th Dec. 2003 (**3**). If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. 2003 (**2**) and by the end of the year you would have made more money.
But let’s push the reasoning a bit further. Still on the chart above, assume you get really unlucky and you start trading toward mid-June 2003. You hit the 10% drawdown limit by the beginning of August and you’re most likely out of the game. You would have started in early August your allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date….
The trading success of any individual has some form of path dependency and there is not much you can do about it. However you can control the size of a strategy’s drawdown and this should be addressed with great care. A portfolio should be diversified in every possible dimension: asset classes, investment strategies, trading frequencies etc…. From that perspective risk is your “survival variable”. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. Otherwise you won’t be there next month to see what happens.
As usual any comments welcome.
A Simple Shiny App for Monitoring Trading Strategies – Parte II.
This is a follow up on my previous post “A Simple Shiny App for Monitoring Trading Strategies“. I added a few improvements that make the app a bit better (at least for me!). Below is the list of new features :
A sample. csv file (the one that contains the raw data) A “EndDate” drop down box allowing to specify the end of the period. A “Risk” page containing a VaR analysis and a chart of worst performance over various horizons A “How To” page explaining how to use and tailor the app to individual needs.
I also made the app totally self contained. It is now available as a stand alone product and there is no need to have R/RStudio installed on your computer to run it. It can be downloaded from the R Trader Google drive account. This version of the app runs using portable R and portable Chrome. For the keen reader, this link explains in full details how to package a Shiny app into a desktop app (Windows only for now).
1 – How to install & run the app on your computer.
Create a specific folder Unzip the contain of the. zip file onto that new folder. Change the paths in the runShinyApp file to match your setings To run the app, you just have launch the run. vbs file. I also included an icon (RTraderTradingApp. ico) should you want to create a shortcut on your desktop.
ui. R: controls the layout and appearance of the app server. R: contains the instructions needed to build the app. You can load as much strategies as you want as long as the corresponding csv file has the right format (see below). shinyStrategyGeneral. R: loads the required packages and launches the app.
3 & # 8211; How to add a trading strategy?
Create the corresponding. csv file in the right directory Create a new input in the data reactive function (within the server. R file) Add an extra element to the choice parameter in the first selectInput in the sidebarPanel (within the ui. R file). The element’s name should match the name of the new input above.
Remove the input in the data reactive function corresponding to the strategy you want to remove (within the server. R file) Remove the element in the choice parameter in the first selectInput in the sidebarPanel corresponding to the strategy you want to remove (within the ui. R file).
Please feel free to get in touch should you have any suggestion.
A Simple Shiny App for Monitoring Trading Strategies.
In a previous post I showed how to use R, Knitr and LaTeX to build a template strategy report. This post goes a step further by making the analysis interactive. Besides the interactivity, the Shiny App also solves two problems :
I can now access all my trading strategies from a single point regardless of the instrument traded. Coupled with the Shiny interactivity, it allows easier comparison. I can focus on a specific time period.
The code used in this post is available on a Gist/Github repository. There are essentially 3 files.
ui. R : controls the layout and appearance of the app. server. R : contains the instructions needed to build the app. It loads the data and format it. There is one csv file per strategy each containing at least two columns: date and return with the following format: (“2010-12-22″,”0.04%” ). You can load as much strategies as you want as long as they have the right format. shinyStrategyG eneral. R : loads the required packages and launches the app.
This app is probably far from perfect and I will certainly improve it in the future. Feel free to get in touch should you have any suggestion.
A big thank you to the RStudio/Shiny team for such a great tool.
Using Genetic Algorithms in Quantitative Trading.
The question one should always asked him/herself when using technical indicators is what would be an objective criteria to select indicators parameters (e. g., why using a 14 days RSI rather than 15 or 20 days?). Genetic algorithms (GA) are well suited tools to answer that question. In this post I’ll show you how to set up the problem in R. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. It’s not a finished strategy either but a research idea that needs to be further researched, developed and tailored to individual needs.
What are genetic algorithms?
The best description of GA I came across comes from Cybernatic Trading a book by Murray A. Ruggiero. “Genetic Algorithms were invented by John Holland in the mid-1970 to solve hard optimisation problems. This method uses natural selection, survival of the fittest”. The general process follows the steps below:
Encode the problem into chromosomes Using the encoding, develop a fitness function for use in evaluating each chromosome’s value in solving a given problem Initialize a population of chromosomes Evaluate each chromosome in the population Create new chromosomes by mating two chromosomes. This is done by muting and recombining two parents to form two children (parents are selected randomly but biased by their fitness) Evaluate the new chromosome Delete a member of the population that is less fit than the new chromosome and insert the new chromosome in the population. If the stop criteria is reached (maximum number of generations, fitness criteria is good enough…) then return the best chromosome alternatively go to step 4.
From a trading perspective GA are very useful because they are good at dealing with highly nonlinear problems. However they exhibit some nasty features that are worth mentioning:
Over fitting: This is the main problem and 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 2010. The Out of sample period starts on January 2011.
The logic is as following: the fitness function is optimised over the in sample period to obtain a set of optimal parameters for the selected technical indicators. The performance of those indicators is then evaluated in the out of sample period. But before doing so the technical indicators have to be selected.
The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: moving averages cross over and RSI. This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes . The other key element is the fitness function . We might want to use something like: maximum return or Sharpe ratio or minimum average Drawdown. In what follows, I chose to maximise the Sharpe ratio.
The R implementation is a set of 3 functions:
fitnessFunction : defines the fitness function (e. g., maximum Sharpe ratio) to be used within the GA engine tradingStatistics : summary of trading statistics for the in and out of sample periods for comparison purposes genoud : the GA engine from the rgenoud package.
The genoud function is rather complex but 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.

Backtesting trading strategies with R.
Few weeks back I gave a talk about Backtesting trading strategies with R, got a few requests for the slides so here they are:
Você pode gostar também:
Pairs Trading Issues A few words for those of you who are not familiar with the “pairs trading” concept. First you should understand that the movement of every. Price is right, part two – Estratégia de negociação. Having stock market in mind, in the previous post: “Price is right, part one.”, I stated that we should not think in terms of “the. Most profitable hedge fund style This is not an investment advice!! Couple of weeks back, during amst-R-dam user group talk on backtesting trading strategies using R, I mentioned the most. Intra-day Volatility Pattern When we speak about volatility we generally refer to the relative movement of an instrument, say stock, from its center, say average. So high volatility.

Comments