estratégias de negociação de código 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 ele começa com a 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, acho que se eu receber essas 2 perguntas respondidas, minha estratégia deveria 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ê quiser 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.
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.
Visualizando dados da série temporal em R.
Estou muito satisfeito em anunciar o meu curso DataCamp sobre Visualização de Dados da Série Temporal em R. Este curso também faz parte da série Time com R habilidades. Sinta-se livre para dar uma olhada, o primeiro capítulo é gratuito!
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 utilizada e poderosa de obter uma melhor compreensão dos seus dados. Após este curso, você terá uma ótima visão geral das capacidades de visualização da série R e você poderá decidir melhor o modelo a ser escolhido para análise subseqüente. 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 irá apresentá-lo às ferramentas básicas de visualização da série R.
Capítulo 2: séries temporais univariadas.
Os 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 em questão. 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 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. 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.
Como de costume, todos os comentários são bem-vindos.
The Rise of the Robots (Advisors…)
The Asset Management industry is on the verge of a major change. Over the last couple of years Robots Advisors (RA) have emerged as new players. The term itself is hard to define as it encompasses a large variety of services. Some are designed to help traditional advisers to better allocate their clients money and some are real “black box”. The user enter a few criteria (age , income, children etc…) and the robot proposes a tailor-made allocation. Between those two extremes a full range of offers is available. I found the Wikipedia definition pretty good. “They are a class of financial adviser that provides portfolio management online with minimal human intervention”. More precisely they use algorithm-based portfolio management to offer the full spectrum of services a traditional adviser would offer: dividend reinvesting, compliance reports, portfolio rebalancing, tax loss harvesting etc… (well this is what the quantitative investment community is doing for decades!). The industry is still in its infancy with most players still managing a small amount of money but I only realised how profound the change was when I was in NYC a few days ago. When RA get their names on TV adds or on the roof of NYC cab you know something big is happening…
it is getting more and more attention from the media and above all it makes a lot of sense from an investor perspective. There are actually two main advantages in using RA:
Significantly lower fees over traditional advisers Investment is made more transparent and simpler which is more appealing to people with limited financial knowledge.
In this post R is just an excuse to present nicely what is a major trend in the asset management industry. The chart below shows the market shares of most popular RA as of the end of 2017. The code used to generate the chart below can be found at the end of this post and the data is here.
Those figures are a bit dated given how fast this industry evolves but are still very informative. Not surprisingly the market is dominated by US providers like Wealthfront and Betterment but RA do emerge all over the world: Asia (8Now!), Switzerland (InvestGlass), France (Marie Quantier)….. It is starting to significantly affect the way traditional asset managers are doing business. A prominent example is the partnership between Fidelity and Betterment. Since December 2017 Betterment past the $2 billion AUM mark.
Despite all the above, I think the real change is ahead of us. Because they use less intermediaries and low commission products (like ETFs) they charge much lower fees than traditional advisers. RA will certainly gain significant market shares but they will also lowers fees charged by the industry as a whole. Ultimately it will affect the way traditional investment firms do business. Active portfolio management which is having a tough time for some years now will suffer even more. The high fees it charges will be even harder to justify unless it reinvents itself. Another potential impact is the rise of ETFs and low commission financial products in general. Obviously this has started a while ago but I do think the effect will be even more pronounced in the coming years. New generations of ETFs track more complex indices and custom made strategies. This trend will get stronger inevitably.
Como de costume, todos os comentários são bem-vindos.
R financial time series tips everyone should know about.
There are many R time series tutorials floating around on the web this post is not designed to be one of them. Instead I want to introduce a list of the most useful tricks I came across when dealing with financial time series in R. Some of the functions presented here are incredibly powerful but unfortunately buried in the documentation hence my desire to create a dedicated post. I only address daily or lower frequency times series. Dealing with higher frequency data requires specific tools: data. table or highfrequency packages are some of them.
xts : The xts package is the must have when it comes to times series in R. The example below loads the package and creates a daily time series of 400 days normaly distributed returns.
merge. xts (package xts): This is incredibly powerful when it comes to binding two or more times series together whether they have the same length or not. The join argument does the magic! it determines how the binding is done.
apply. yearly/apply. monthly (package xts): Apply a specified function to each distinct period in a given time series object. The example below calculates monthly and yearly returns of the second series in the tsInter object. Note that I use the sum of returns (no compounding)
endpoints (package xts): Extract index values of a given xts object corresponding to the last observations given a period specified by on. The example gives the last day of the month returns for each series in the tsInter object using endpoint to select the date.
na. locf (package zoo): Generic function for replacing each NA with the most recent non-NA prior to it. Extremely useful when dealing with a time series with a few “holes” and when this time series is subsequently used as input for an R functions that does not accept arguments with NAs. In the example I create a time series of random prices then artificially includes a few NAs in it and replace them with the most recent value.
charts. PerformanceSummary (package PerformanceAnalytics): For a set of returns, create a wealth index chart, bars for per-period performance, and underwater chart for drawdown. This is incredibly useful as it displays on a single window all the relevant information for a quick visual inspection of a trading strategy. The example below turns the prices series into an xts object then displays a window with the 3 charts described above.
The list above is by no means exhaustive but once you master the functions describe in this post it makes the manipulation of financial time series a lot easier, the code shorter and the readability of the code better.
Como de costume, todos os comentários são bem-vindos.
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…
Como de costume, todos os comentários são bem-vindos.
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 2018 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.
O R Trader.
Usando R e ferramentas relacionadas em Finanças Quantitativas.
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). Mais informações podem ser encontradas aqui. 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.
Como de costume, todos os comentários são bem-vindos.
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. Mais informações podem ser encontradas aqui. 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 & # 8211; 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 & # 8211; 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 (2018), « An optimization process to improve in/out of sample consistency, a Stock Market case», JP Morgan Cazenove Equity Quantitative Conference, London October 2018.
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: thertrader@gmail.
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 & # 8211; 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.
Como de costume, todos os comentários são bem-vindos.
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…
Como de costume, todos os comentários são bem-vindos.
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 2018 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.
Como de costume, todos os comentários são bem-vindos.
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 & # 8211; 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: (“2018-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.
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. No entanto, eles exibem algumas características desagradáveis que merecem destaque:
Sobreposição: Este é o principal problema e é para o analista configurar o problema de forma a minimizar esse risco. Tempo de computação: se o problema não for definido corretamente, pode ser extremamente longo para alcançar uma solução decente e a complexidade aumenta exponencialmente com o número de variáveis. Daí a necessidade de selecionar cuidadosamente os parâmetros.
Existem vários pacotes R que lidam com GA, eu escolhi usar o mais comum: rgenoud.
Os preços de fechamento diários para a maioria dos ETFs líquidos de finanças do Yahoo voltam a janeiro de 2000. O período de amostragem vai de janeiro de 2000 a dezembro de 2018. O período fora da amostra começa em janeiro de 2018.
A lógica é a seguinte: a função de aptidão é otimizada durante o período de amostra para obter um conjunto de parâmetros ótimos para os indicadores técnicos selecionados. O desempenho desses indicadores é então avaliado no período fora da amostra. Mas, antes disso, os indicadores técnicos devem ser selecionados.
O mercado de ações exibe duas características principais que são familiares para qualquer pessoa com alguma experiência comercial. Momento a longo prazo e reversão de curto prazo. Essas características podem ser traduzidas em termos de indicadores técnicos por: médias móveis cruzadas e RSI. Isso representa um conjunto de 4 parâmetros: períodos de retorno para médias móveis a longo e curto prazo, período de retorno para RSI e RSI. Os conjuntos de parâmetros são os cromossomos. O outro elemento-chave é a função de fitness. Podemos querer usar algo como: retorno máximo ou taxa Sharpe ou redução média mínima. No que se segue, escolhi maximizar a proporção de Sharpe.
A implementação do R é um conjunto de 3 funções:
fitnessFunction: define a função de fitness (por exemplo, taxa máxima de Sharpe) para ser usado no comércio de motores GA: estatísticas de negociação para os períodos de entrada e saída de amostra para fins de comparação genoud: o mecanismo GA do pacote rgenoud.
A função genoud é bastante complexa, mas eu não vou explicar o que cada parâmetro significa que eu quero manter esta publicação curta (e a documentação é realmente boa).
Na tabela abaixo, apresento para cada instrumento os parâmetros ótimos (período de retorno de RSI, limite de RSI, Média de Mudança de Curto Prazo e Média de Mudança de Longo Prazo), juntamente com as estatísticas de negociação dentro e fora da amostra.
Antes de comentar os resultados acima, quero explicar alguns pontos importantes. Para combinar a lógica definida acima, limitei os parâmetros para garantir que o período de look-back para a média móvel a longo prazo seja sempre mais longo que a média móvel mais curta. Eu também obriguei o otimizador a escolher apenas as soluções com mais de 50 trades no período de amostra (por exemplo, significância estatística).
Em geral, os resultados fora da amostra estão longe de serem impressionantes. Os retornos são baixos, mesmo que o número de negócios seja pequeno para tornar o resultado realmente significativo. No entanto, existe uma perda significativa de eficiência entre o período de entrada e saída do Japão (EWJ), o que muito provavelmente significa uma sobreposição.
Esta publicação destina-se a fornecer ao leitor as ferramentas para usar adequadamente o GA em uma estrutura de negociação quantitativa. Mais uma vez, é apenas um exemplo que precisa ser aperfeiçoado. Algumas possíveis melhorias a serem exploradas seriam:
Função de fitness: maximizar a relação Sharpe é muito simplista. A & # 8220; smarter & # 8221; A função certamente melhoraria o padrão de estatísticas comerciais de amostra: tentamos capturar um padrão muito direto. Uma pesquisa de padrão mais detalhada é definitivamente necessária. Otimização: há muitas maneiras de melhorar a forma como a otimização é conduzida. Isso melhoraria a velocidade de computação e a racionalidade dos resultados.
O código usado nesta publicação está disponível em um repositório Gist.
Quantitative Trading Strategy Using R: A Step by Step Guide.
In this post we will discuss about building a trading strategy using R. Before dwelling into the trading jargons using R let us spend some time understanding what R is. R é uma fonte aberta. There are more than 4000 add on packages,18000 plus members of LinkedIn’s group and close to 80 R Meetup groups currently in existence. É 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 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 "o mercado é reversão". A reversão média é uma teoria que sugere que os preços eventualmente retornem ao seu 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 aumentar / diminuir, atualizamos a coluna do limite. O preço de fechamento é comparado com a banda superior e com a banda inferior. Quando a banda superior é cruzada, é um sinal para venda. Similarly when the lower band is crossed, it is a signal for sell.
A seção de codificação pode ser resumida da seguinte forma,
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. Uma vez que este é o teste de volta, 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 configurando níveis de limiar diferentes, regras de entrada mais rígidas, perda de parada, etc. Pode-se escolher mais dados para back-testing, usar a abordagem bayseiana para configuração de limite, ter em conta 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 que você crie e teste 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 carteiras de ativos múltiplos Suporta tipos de ordem de mercado, limite, stoplimit e stoptrailing Suporta dimensionamento de ordem e otimização de parâmetros.
Nesta publicação, 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 dados de mercado Indicadores - 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. Preferimos o estúdio R para codificação e insistimos em usar 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 desejar 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.
Once you are familiar with these basics you could take a look at how to start using quantimod package in R. Or in case you’re good at C++, take a look at an example strategy coded in C++.
Se você é um comerciante de varejo ou um profissional de tecnologia que procura iniciar sua própria mesa de negociação automatizada, comece a aprender algo trading hoje! 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.
Comments
Post a Comment