воскресенье, 10 июня 2018 г.

Estratégia de negociação sql


Estratégia comercial Sql
Obter através da App Store Leia esta publicação em nosso aplicativo!
Personalizando a nova estratégia de negociação em R usando o quantmod.
Eu quero criar um novo indicador de TA personalizado para o símbolo de estoque em R. Mas não tenho idéia de como converter minha estratégia condicional SQL em função autodefinida R e adicioná-la ao ChartSeries em R.
A questão está listada no seguinte código como a explicação.
Pergunta: Como posso reescrever o código abaixo para disponibilizá-lo como uma função em R?
Eu não acho que você precisa de sql neste caso.
Não tenho certeza do que REF significa, mas tenho certeza que você pode fazer isso sozinho.
Este é o resultado (eu não consigo carregar a foto, mas você vê um gráfico com linhas horizontais onde o sinal eq 1)
Use a função como um wrapper para sqldf () no pacote sqldf. O argumento para sqldf () será uma declaração seletiva no quadro de dados que possui os dados.
Um bom tutorial para isso pode ser encontrado em Burns Statistics.

Estratégia comercial Sql
Obter através da App Store Leia esta publicação em nosso aplicativo!
Cálculos do sistema de negociação de ações via SQL.
Precisa calcular um portfólio de mercado de ações com base em negócios em um banco de dados. O cálculo que eu procuro fazer via SQL é o preço médio, a taxa de retorno, o valor do portfólio, etc.
Eu não consegui fazê-lo com o SQL, então acho que talvez seja necessário script do resultado, então qualquer ajuda que tenha sido apreciada.
Observe que o preço atual é codificado (38), uma vez que não é fornecido, ele precisaria ser fornecido em outra tabela que seria unida à tabela de estoques, mas o princípio é o mesmo.

QUANTLABS.
Quant Resources for Traders.
O SQL Server StreamInsights CEP habilita o novo tipo de estratégias comerciais de quant com Joins and Projection.
O SQL Server StreamInsights CEP habilita o novo tipo de estratégias comerciais de quant com Joins and Projection.
Eu nunca teria pensado nisso, mas eu acho que sua plataforma não pode fazer isso:
Na nossa primeira consulta, ericRecalcCepStream, combinamos o preço das ações da Ericsson em dólares americanos com taxa de câmbio (do mesmo dia) e recalculamos o preço na coroa sueca. Em nossa segunda consulta, ericCompareCepStream, tomamos a diferença entre o preço recalculado e o preço das ações da Ericsson na Coroa sueca. Esses tipos de cálculos são exemplos de projeções.
OBSERVAÇÃO Eu agora posto minhas ALERTAS DE NEGOCIAÇÃO na minha conta pessoal de FACEBOOK e TWITTER. Não se preocupe, pois não publico vídeos estúpidos sobre gatos ou o que eu como!

Usando a análise de dados do SQL Server para estratégias de negociação de estoque.
Por: Rick Dobson | Leia Comentários (2) | Dicas relacionadas: 1 | Mais> T-SQL.
Nosso negócio administra um serviço de consultoria de ações. Alguns de nossos clientes negociam nossas ações recomendadas com prejuízo comprando a um preço alto e vendendo a um preço baixo. Precisamos de modelos de negociação muito simples com resultados comparativos para mostrar aos clientes como eles podem aumentar o valor de suas contas de investimento com nossas escolhas de estoque.
A mineração de dados - especialmente o pré-processamento, análise preliminar de dados e etapas de relatórios - pode ser muito útil para resolver seu problema. Esta dica examina seis ações, como as que podem ser recomendadas pela sua empresa, para apresentar o resultado de três estratégias comerciais diferentes. As estratégias de negociação de ações são propositadamente simples para que possam ser prontamente programadas com o T-SQL, além de serem entendidas pelos seus clientes comerciais. Todas as estratégias cobertas são consistentes com mostrar aos clientes como eles podem aumentar o valor de suas contas de investimento.
Os dados de origem da dica são os preços das ações do site Google Finance. Estes dados estão disponíveis gratuitamente. A dica ilustra como baixar os preços das ações nos arquivos csv. Em seguida, os dados são transferidos para tabelas do SQL Server.
Depois de transferir os dados de preço das ações para um banco de dados do SQL Server, eles são pré-processados ​​para torná-los adequados para examinar o desempenho de cada uma das três estratégias de negociação de ações. Uma estratégia de negociação de ações depende das médias móveis para os preços das ações. Esta dica inclui uma explicação simples das médias móveis, bem como uma maneira fácil de computá-las para obter dados sobre os preços das ações.
O elemento da ponta final compara ganhos e perdas das três estratégias de negociação. As comparações são para as seis ações individualmente e em geral. As comparações são calculadas numa base por ação, bem como base de lotes compartilhados. Um lote de ações é um conjunto de ações para um estoque que é comprado e vendido como uma unidade.
Baixando os dados do site Google Finance.
Você pode baixar o preço e o volume do final do dia para um estoque no site do Google Finance. Basta inserir um URL com parâmetros, incluindo o símbolo do estoque, bem como as datas de início e término para o intervalo de dados que você procura. Você também precisa especificar o formato de saída. Seu navegador, como o Chrome ou o Internet Explorer, recuperará os preços e os volumes diários de ações em um arquivo em seu computador.
O seguinte URL especifica a recuperação de dados históricos de preço e volume para um estoque com o símbolo crus. Os dados começam a partir do primeiro dia de negociação em ou após 1º de janeiro de 2008 até o último dia de negociação para o qual os dados estão disponíveis até 31 de agosto de 2016. O download foi feito durante a manhã de 24 de agosto de 2016. O Google Finance site nomeia automaticamente o arquivo baixado com o símbolo especificado na URL (por exemplo, crus. csv).
Aqui está uma captura de tela do Excel que mostra as 20 primeiras linhas de dados no arquivo csv chamado crus. csv. Observe que há uma linha separada para cada dia de negociação que termina em 23 de agosto de 2016, o último dia de negociação para o qual os dados de fim de dia estavam disponíveis. Além da coluna Data, existem quatro colunas que especificam valores de dinheiro (Abrir, Alto, Baixo, Fechar) e uma quinta coluna mostra ações negociadas em uma data para o estoque designado pelo símbolo. Enquanto o Excel transforma automaticamente os dados de caracteres no arquivo crus. csv para data e valores numéricos, é importante ter em mente que os dados no arquivo csv são dados de caractere.
Os dados para seis símbolos de estoque foram baixados para esta dica. As seguintes balas mostram e os símbolos juntamente com os nomes das empresas correspondentes e descrições curtas. Você pode ver as descrições de que a grande diversidade está prontamente disponível.
Crus é para a Cirrus Logic, Inc. A empresa fornece circuitos para aplicações de consumo e energia para consumo, automotivo e profissional edu é para New Oriental Education & amp; Tech Grp (ADR). Este símbolo representa um ADR para New Oriental Education & amp; Technology Group - uma empresa que opera na China e é fornecedora de serviços educacionais privados. Um ADR é um estoque que negocia nos Estados Unidos, mas representa um número especificado de ações em uma empresa estrangeira. O encontro é para MeetMe, Inc. A empresa disponibiliza redes sociais para conhecer pessoas novas nos EUA e na América Latina orly é para O 'Reilly Automotive Inc, um varejista de peças e acessórios automotivos, é para Stamps, um fornecedor de serviços de envio e envio de internet ulta é para Ulta Salon, Cosmetics & amp; Fragrance, Inc. Esta empresa vende produtos cosméticos, perfumes, pele e cabelos, produtos, eletrodomésticos e acessórios. A empresa também oferece serviços de cabeleireiro e tratamentos de spa.
Migrando os arquivos csv para as tabelas do SQL Server.
Esta dica cria as tabelas para armazenar o conteúdo do arquivo csv em um banco de dados chamado stock_history_data. Em seguida, ele preenche as tabelas do SQL Server a partir dos arquivos csv baixados - uma tabela por arquivo. O código fornecido para a dica não funcionará como está, a menos que você tenha o banco de dados stock_history_data criado em sua instância do SQL Server. Se você não possui o banco de dados em seu servidor, executar o script a seguir pode criar o banco de dados.
Como os dados nos arquivos csv são baseados em caracteres, você deve transformá-los antes de poder usá-los como datas, dinheiro ou números inteiros no SQL Server. Existem várias maneiras de realizar as transformações. Uma dica anterior que trabalha com os preços históricos do índice S & P 500 (Criando um Relatório Sparkline da Matriz SSRS com Dados da Oracle 11g) descreve uma abordagem na qual os dados são importados para o SQL Server como dados de caracteres e depois transformados por funções T-SQL até a data , dinheiro ou valores inteiros. Esta dica demonstra como usar recursos de transformação SSIS embutidos para converter os dados em um tipo de dados apropriado.
A captura de tela a seguir mostra uma visão do fluxo de controle do projeto SSIS para a mineração de dados, os dados do preço da ação baixados do site do Google Finance. Alguns textos de anotação e duas etapas são destacados. O conteúdo destacado é para importar os dados baixados para o SQL Server.
Além disso, existem 7 gerentes de conexão exibidos abaixo da área de fluxo de controle.
Um é e o gerenciador de conexões OLEDB apontando para o banco de dados stock_history_data Seis são para gerentes de conexão de arquivos planos que apontam para os arquivos csv baixados.
A captura de tela a seguir mostra o T-SQL na tabela create orly ohlcv Execute SQL Task dentro do pacote de sequências de tabelas Ohlcv. Existem seis etapas de Execute SQL Task no contêiner - uma para cada tabela para receber dados baixados de um arquivo csv. Todas as tabelas têm a mesma especificação, exceto o nome do símbolo.
Quando você abre um gerenciador de conexões de arquivo simples para o arquivo orly. csv, o SSIS vê automaticamente os códigos de caracteres UTF-8 enviados do site do Google Finance e designa a página de código do Microsoft 65001 para ler os códigos de caracteres. Ele também espera cabeçalhos de coluna na primeira linha, que corresponde ao formato baixado. Portanto, nenhuma alteração é necessária para a guia Geral padrão que aparece abaixo (além de atribuir um nome de gerenciador de conexão).
Esta dica usa configurações na guia Avançado para indicar os tipos de dados SSIS para ler os dados do arquivo csv de forma adequada para transferi-los para tipos de dados em tabelas do SQL Server. Três formatos distintos são designados como indicado nas capturas de tela abaixo.
O tipo de dados DT_DBTIMESTAMP pode ler caracteres de data UTF-8 O tipo de dados DT_CY pode ler campos de caracteres UTF-8 que representam dinheiro; essa designação de tipo de dados é apropriada para as colunas Open, High, Low e Close nos arquivos csv O tipo de dados DT_I8 pode ler campos de caracteres UTF-8 que representam inteiros que estão indo para uma coluna com um tipo de dados bigint em uma tabela do SQL Server .
Com a exceção dos dados para o símbolo orly, o conteúdo do arquivo csv para os estoques importados com sucesso para as tabelas do SQL Server. No entanto, os dados para o símbolo orly não foram carregados com sucesso na primeira tentativa. Depois de examinar os registros SSIS e os dados baixados no Notepad ++, descobriu-se que as colunas selecionadas nos dados orly para três datas (24 de novembro de 2010, 23 de dezembro de 2010 e 29 de dezembro de 2010) foram especificadas incorretamente.
Veja a tela abaixo para visualizar do Notepad ++ os dados defeituosos no arquivo orly. csv. Observe que os dados incorretos foram para as colunas Open, High e Low. Os dados dos valores da coluna Data e Fechar apareceram válidos, mas os dados para a coluna Volume não apareceram válidos. No entanto, esta dica só requer valores de coluna de Data e Fechar válidos.
Foram os dados ruins para as colunas Open, High e Low que causaram a importação dos dados do arquivo orly. csv para falhar inicialmente. Você pode ignorar a falha configurando as configurações dentro da Origem do Arquivo Flat para o passo cly de orly para atribuir valores NULL a colunas com dados inválidos durante o processo de importação. A captura de tela a seguir mostra as configurações de falha Ignore para as colunas Open, High e Low no arquivo orly. csv. Com essas mudanças de configuração na guia Saída de erro da Origem Flat File for orly csv, foi possível carregar o arquivo orly. csv juntamente com dados baixados para os outros cinco símbolos.
Pré-processamento dos dados importados para avaliações da estratégia de negociação.
Até este ponto, os dados importados existem em seis tabelas separadas com datas que retornam à primeira data de negociação em 2008 ou sempre que o site do Google Finance começou a informar os preços das ações de um símbolo. Além das variações na data de início para diferentes símbolos, às vezes notei datas com linhas de dados para um símbolo que faltava para outros símbolos. Para os seis símbolos de ações usados ​​nesta dica, essas datas faltantes eram muito raras e limitadas a dados anteriores a 2011. Os dados faltantes não são relevantes para essa dica porque as regras de negociação de ações foram comparadas apenas para estratégias de negociação na janela de 25 meses. Julho de 2014 até julho de 2016.
Além disso, aos filtros de pré-processamento para o intervalo de datas, outro pré-processamento foi implementado.
Os dados foram consolidados a partir de seis tabelas separadas sem um indicador de símbolo em uma tabela com um indicador de símbolo distinto para cada estoque. Esta etapa facilita a avaliação de estratégias de negociação em todas as seis ações. Além disso, as médias móveis de 10 dias e 30 dias foram calculadas a partir dos dados de preços de ações de base. As médias móveis são uma ferramenta de análise técnica comum para analisar tendências de estoque. A média móvel de 10 dias reflete tendências a curto prazo e a média móvel de 30 dias reflete tendências a mais longo prazo.
O seguinte script T-SQL mostra o código para selecionar dados da tabela crus, adicionando uma coluna de símbolos e calculando médias móveis de 10 dias e 30 dias. Este link compara 6 métodos diferentes para calcular uma soma em uma janela rolante, como 10 dias ou 30 dias. O método com o melhor desempenho usou uma versão personalizada da função SUM que dependia das palavras-chave PRECEDING e CURRENT ROW. O código a seguir ilustra uma adaptação do melhor método para calcular médias móveis em vez de somas em uma janela rotativa.
A captura de tela a seguir exibe um excerto do conjunto de resultados para o script anterior. A coluna mav_10 mostra valores de média móvel de 10 dias e a coluna mav_30 revela valores médios móveis de 30 dias. Observe que os valores para essas colunas não começam até a décima e trigésima linha, respectivamente. Isso ocorre porque uma média móvel de 10 dias requer pelo menos 10 dias anteriores de valores e uma média móvel de 30 dias requer pelo menos 30 dias de valores anteriores. Rolling windows determina quais datas contribuem para os valores da média móvel em cada linha.
O passo chamado criar stocks_ohlcv_with_mav_10_30 tabela com histórico de estoque consolidado e adicionar mav_10 e mav_30 no diagrama de fluxo de controle exibido na segunda captura de tela dentro desta dica inclui o script completo para filtragem de data, consolidação, somando símbolos e computação de médias móveis. O passo armazena seu resultado na tabela stocks_ohlcv_with_mav_10_30.
Existem 525 dias de negociação de ações de julho de 2014 a julho de 2016. Para os seis estoques examinados dentro desta dica, isso significa que existem 3150 linhas na tabela stocks_ohlcv_with_mav_10_30. A seguinte captura de tela mostra as primeiras 31 linhas na tabela. Como os dados são organizados por data dentro do símbolo, essas linhas são para os 31 dias de negociação mais antigos para o símbolo crus. Como as médias móveis são calculadas em valores que se remontam até 2008, não há valores NULL para as médias móveis de 10 dias ou 30 dias.
Três regras de negociação.
Antes de passar para a etapa de pré-processamento final para os dados sobre os preços das ações, será útil rever as três estratégias de negociação avaliadas nesta dica. Lembre-se que o objetivo é avaliar regras de negociação simples porque queremos que as regras sejam facilmente compreendidas pelos clientes do serviço de assessoria de ações. Além disso, buscamos regras que são seguras para negociar - de modo que os preços das ações subam se os preços das ações subirem durante um período de avaliação (vamos colocar alguns exemplos onde um negócio pode perder dinheiro mesmo quando o preço das ações está subindo período prolongado). Esta dica avalia estratégias de negociação para o período de 25 meses de julho de 2014 a julho de 2016. Além disso, precisamos de regras que possam ser facilmente comparadas entre si. As regras examinadas nesta dica são mais como benchmarks para contrastar estilos de negociação que recomendações precisas sobre como negociar ações.
As três regras de negociação avaliadas por esta dica são as seguintes.
A regra geral de compra e retenção compra ações para uma ação no preço aberto do primeiro dia de negociação em julho de 2014 e vende essas ações no preço de encerramento no último dia de negociação em julho de 2016. A regra mensal de compra e retenção compra ações para uma ação no preço aberto por cada mês de julho de 2014 a julho de 2016. No último dia de negociação de cada mês, a regra vende as ações compradas no início do mês. A estratégia condicional de compra e retenção compra ações para um estoque somente quando a tendência de curto prazo dos preços no início do mês, conforme indicado pela média móvel de 10 dias, for maior do que a tendência de longo prazo, conforme indicado pela média móvel de 30 dias. Caso contrário, nenhuma compra é feita para estoque durante o mês. Para manter o código simples para esta comparação de regras de negociação, assumimos que você conhece os valores da média móvel de 10 dias e 30 dias para o primeiro dia de negociação do mês no início do primeiro dia do mês.
Os planos de negociação são comparados com uma variação do preço da ação, bem como uma grande base de variação de preço.
A variação do preço da ação é calculada com base na diferença entre o preço aberto na primeira negociação por um período versus o preço Fechar no último dia de um período. Se o preço Close for maior do que o preço Open, então a regra gera um ganho. Caso contrário, a regra se rompe ou perde dinheiro. Os dias de início e final mudam de uma regra para a próxima. Para a regra de compra e retenção, há apenas uma data de início e uma data de término. A data de início é o primeiro dia de negociação no início de julho de 2014. A data de término é o último dia de negociação de julho de 2016. Para a regra mensal de compra e retenção, há data de início e data de término para cada um dos 25 meses de De julho de 2014 a julho de 2016. Dentro de cada mês, a data de início é sempre o primeiro dia de negociação do mês e a data final é sempre o último dia de negociação do mês. Para a regra condicional de compra e retenção, há uma variável Número de meses em que as ações podem ser compradas e vendidas. As ações só são compradas nos meses em que a média móvel de 10 dias é maior do que a média móvel de 30 dias no início do mês. Se houver uma compra de ações no início de um mês com esta regra, então o preço de fechamento é para o último dia de negociação no mês. Recorde que o termo lote refere-se à cobrança de ações compradas durante uma negociação. O tamanho do lote do termo indica o número de ações compradas ao mesmo tempo. Para avaliação no contexto desta dica, o tamanho do lote para a regra de compra e manutenção mensal é o número de ações compradas (arredondado para as 10 ações mais próximas), então o preço médio mensal é de US $ 4.000 ou um pouco mais. O tamanho do lote varia de um estoque para o outro dentro de um mês. Os tamanhos de lote calculados para a regra de compra e retenção mensal também são usados ​​para a regra de compra e retenção condicional. A regra geral de compra e retenção usa o tamanho de lote de compra e retenção mensal de julho de 2014 para sua primeira compra . Porque no final de 25 meses você vende as ações adquiridas na compra inicial com a regra geral de compra e retenção, o tamanho do lote vendido em julho de 2016 é o mesmo que as ações compradas em julho de 2014. A compra e retenção condicional A regra usa os tamanhos de lote de compra e retenção mensais. A única diferença é que durante meses em que a média móvel inicial de 10 dias é menor ou igual à média móvel inicial de 30 dias, não há compras e vendas de estoque.
A tabela para avaliar as regras de negociação.
Esta dica usa a tabela data_for_trading_rules para armazenar dados em um formato que simplifica a computação de ganhos e perdas mensalmente. A próxima captura de tela mostra as primeiras 25 linhas da tabela data_for_trading_rules. Observe que todas as 25 linhas são para o símbolo crus.
As primeiras três colunas indicam o símbolo eo período de tempo para o resto dos dados em uma linha. As colunas de primeiro dia e último dia não são estritamente necessárias, mas eles fornecem uma maneira de confirmar visualmente que essas datas estão dentro do ano e mês para a linha O Aberto coluna indica o preço aberto no primeiro dia de negociação do mês para a linha As colunas mav_10_first_day e mav_30_day exibem a média móvel de 10 dias e 30 dias no primeiro dia de negociação do mês. A coluna Fechar revela o preço de fechamento na última dia de negociação do mês.
Todos os dados que você precisa para avaliar as regras de negociação mensal e condicional de compra e suspensão estão em uma linha da tabela data_for_trading_rules. Por exemplo, o valor da coluna Fechar, menos o valor da coluna Abrir indica o ganho ou perda por ação para o mês com a regra de compra e retenção mensal. A regra de comprar e manter condicional usa apenas a diferença entre os valores da coluna Fechar e Abrir para meses nos quais a média móvel de 10 dias é maior que a média móvel de 30 dias. Ao somar o ganho ou a perda por cada mês em que houve um comércio, você pode obter o ganho ou a perda em todos os 25 meses para os quais os preços das ações são rastreados.
Para a regra geral de compra e retenção, você precisa de duas linhas da tabela data_for_trading_rules para avaliar o ganho ou perda para a regra de negociação. A diferença entre o preço Fechar de julho de 2016, menos o preço aberto para julho de 2014, retorna o ganho ou perda de estoque. Assim como com as regras mensais, você calcula esse valor separadamente para cada ação.
O script a seguir mostra o script T-SQL para calcular a tabela data_for_trading_rules. O script contém duas consultas de tabela derivadas.
A consulta da tabela derivada first_day_data retorna o preço Open juntamente com as médias móveis de 10 dias e 30 dias para o primeiro dia de negociação de cada mês. A consulta da tabela derivada last_day_data retorna o preço Close para o último dia de negociação de cada mês. Uma sub-consulta Dentro das consultas de tabela derivadas first_day_data e last_day_data permite que as consultas retornem os dados apenas no primeiro ou último dia em um mês a partir da tabela stocks_ohlcv_with_mav_10_30. As duas consultas de tabela derivada são incorporadas internamente com base em SÍMBOLO, ANO e MÊS para colocar preços de abertura e fechamento na mesma linha da tabela data_for_trading_rules A cláusula INTO imediatamente antes da cláusula FROM na consulta externa principal preenche a tabela data_for_trading_rules.
Avaliando as regras de negociação.
Três relatórios do SSRS são fornecidos como um modelo para avaliar as regras de negociação com as seis ações examinadas nesta dica. Os resultados resumidos não incluem custos de negociação porque as comissões por negociação podem variar (ou até mesmo ser zero em alguns casos), dependendo do corretor e da segurança na qual você investe. No entanto, se você planeja usar um corretor particular com uma taxa padrão por troca, você pode querer considerar uma comissão de corretor.
O primeiro relatório é um relatório de linha superior que compara as três estratégias de negociação para o ganho versus perda em uma base por ação e uma base de muito tamanho. Como mostra a tela abaixo, as três estratégias de negociação geraram ganhos ao longo do período de avaliação de 25 meses para cada uma das ações e, em geral. A estratégia de compra e retenção eliminou a regra de compra e venda mensalmente (ganho global de US $ 22.964 para compra e retenção contra US $ 22.950 para comprar e vender todos os meses). A estratégia de negociação baseada na média móvel de 10 dias em relação à média móvel de 30 dias gerou os maiores ganhos por uma margem substancial. Mostramos por que esse resultado é obtido nos próximos dois relatórios.
Como você pode ver, existem 8 colunas no corpo do relatório de topo. A consulta para o relatório começa com uma instrução SELECT que faz referência a duas principais consultas de tabela derivada - cada uma das quais possui suas próprias sub-consultas. A listagem abaixo mostra apenas a consulta mais externa e as referências às principais consultas de tabela derivadas, de modo que você não está distraído por detalhes de obter uma imagem geral sobre como o relatório compila dados. Se desejar, você pode examinar a consulta completa para a comparação da linha superior do relatório de estratégias de negociação no projeto SSRS disponível para download com esta dica.
Uma consulta derivada principal gera dados resumidos para a estratégia de compra e retenção; seu nome é buy_and_hold_summary A outra consulta de tabela derivada principal gera resultados resumidos para a regra de compra e retenção mensal em relação à regra condicional de compra e retenção com base nas médias móveis.
A próxima captura de tela apresenta outro relatório com resultados detalhados para a regra de negociação buy-and-hold mensal. Você pode usar esse relatório para examinar os resultados de qualquer um dos seis estoques no conjunto de dados para essa dica. A captura de tela abaixo mostra os resultados para o estoque com o símbolo crus.
Este segundo relatório exibe resultados mensais de perda de ganho de negociação em uma base por ação e uma base de muito tamanho para o símbolo inserido na caixa de seleção SÍMBOLO. Os meses com perda mostram o resultado em vermelho; Caso contrário, o resultado por ação e por tamanho de lote mostra em verde.
Embora o relatório anterior mostre que o ganho para o estoque de crus foi de cerca de US $ 3.780, o seguinte relatório mostra uma perda em 10 dos 25 meses para os quais os dados de preços foram analisados. Além disso, o estoque perde valor em 4 dos primeiros 5 meses e um período adicional de três meses consecutivos (junho de 2015 a agosto de 2015) que foram analisados. Se um cliente investisse no estoque de crus exclusivamente durante um desses períodos, eles poderiam facilmente concluir que uma recomendação para crus foi ruim, apesar do fato de que o estoque ganhou mais de 100% durante o período de avaliação de 25 meses!
A consulta a seguir mostra o código para relatar resultados comerciais de compra e retenção mensais. A declaração SELECT mais externa faz referência a duas consultas de tabela derivadas que estão internas. O SELECT mais externo calcula um resultado (G / L para o tamanho do lote) e renomeia outras colunas de sua fonte subjacente. Além disso, o parâmetro SYMBOL na última linha do código permite ao usuário do relatório especificar um símbolo de estoque para o qual mostrar resultados.
A consulta de tabela derivada mensal_G / L_per_share retorna para cada mês a diferença entre o preço final de fechamento e o preço de abertura inicial; Este é o ganho ou a perda por ação por um mês. A consulta de tabela derivada de partes_to_buy_sell calcula o tamanho do lote para um estoque, o qual, por sua vez, é usado pela consulta mais externa para ajudar a gerar o ganho ou a perda por lote por um mês.
A próxima captura de tela para esta dica mostra os resultados comerciais quando a média móvel de 10 dias é maior do que a média móvel de 30 dias no início do mês. O resultado da regra é que os negócios não são feitos em 10 meses para os quais a regra de cada mês faz um comércio. Tanto este relatório quanto o anterior são para o estoque com um símbolo crus.
Há 10 meses em que a regra de negociação com base em médias móveis ignora um comércio por um mês em relação à regra de negociação de todos os meses. A regra de negociação com base em médias móveis ignorou 5 perdas e 1 resultado sem alteração. Esses bons resultados da regra da média móvel são contrabalançados, em parte, por ganhos perdidos em 4 meses. O relatório top-line acima mostra que a média móvel retornou mais de $ 700 menos ganhos do que a regra de todos os meses para o estoque crus. O encolhimento nos ganhos foi ainda maior para os restantes 5 estoques.
Minha retirada desses resultados é que a regra da média móvel não é suficientemente precisa para descobrir quando um mês provavelmente resultará em uma perda versus um ganho. Por exemplo, se a regra da média móvel fosse 100% precisa, a negociação só ocorreria por meses em que houve um ganho. Mais pesquisas para descobrir melhores regras de negociação para evitar perdas sem perder ganhos podem resultar em estratégias de negociação seletivas melhores do que comprar e manter ou comprar e vender todo mês.
O script a seguir mostra a consulta do relatório na regra de negociação média móvel. Este script difere do script para a regra de todos os meses na medida em que mostra as médias móveis de 10 dias e 30 dias e que apenas apresenta resultados comerciais nos meses em que a média móvel inicial de 10 dias é maior que a média inicial de 30 dias média móvel.
Próximos passos.
Esta dica apresenta três modelos comerciais simples implementados através do código T-SQL para uma seleção de 6 ações ao longo de um período de avaliação de 25 meses. Três relatórios do SSRS também são apresentados para contrastar e analisar os modelos de negociação. Os relatórios mostram que é possível ter ações que ganham valor significativo ao longo da avaliação de 25 meses, mesmo quando investir seletivamente nos estoques por apenas alguns meses pode realmente gerar uma perda. Ao compartilhar esses resultados com seus clientes, a empresa de consultoria de ações pode ajudar os clientes a evitar a perda de dinheiro em negociações de ações precocemente mensuradas para estoques recomendados. Como todas as etapas, desde o download dos preços das ações históricas até a preparação dos relatórios, são descritas, a empresa de consultoria de ações pode usar qualquer outro conjunto de ações, além daquelas cobertas nesta dica, para um relatório para seus clientes. Além disso, qualquer período de avaliação para o qual o site Google Finance tem preços de ações pode ser usado para relatar os resultados das regras de negociação. Finalmente, a extração de dados adicionais de dados de preços de ações pode levar a melhores regras para extrair mais ganhos da negociação de ações. A pasta de arquivos de recursos para esta dica inclui os arquivos de projeto para os projetos SSIS e SSRS mencionados na dica, juntamente com outros scripts que você pode achar úteis. Certifique-se e analise o arquivo readme. txt na pasta da solução de recursos antes de tentar reproduzir quaisquer resultados na dica com base nos arquivos na pasta de arquivos de recursos. Finalmente, encerro indicando que esta dica não está recomendando ações específicas, incluindo as seis analisadas. Essas ações foram escolhidas porque eu as estava acompanhando como parte de minha devida diligência de investimento. No momento em que enviei essa dica para MSSQLTips, segurei posições em três ações entre as seis da dica. Baixe recursos para esta dica.
Sobre o autor.
Obrigado. Eu gostei de escrever a dica.
Muito legal. Obrigado por publicar.
Aprendendo.
Pesquisa.
Mais informações.
Copyright (c) 2006-2018 Edgewood Solutions, LLC Todos os direitos reservados.
Alguns nomes e produtos listados são marcas registradas de seus respectivos proprietários.

Estratégias de mineração de dados do SQL Server para ações Comprar e vender recomendações.
Por: Rick Dobson | Leia comentários (1) | Dicas relacionadas: Mais> T-SQL.
Nosso serviço de consultoria de estoque de start-up recomenda com sucesso as ações vencedoras de longo prazo. Alguns de nossos clientes também querem conselhos específicos sobre quando comprar e vender ações recomendadas. Forneça um exemplo de solução SQL Server T-SQL para gerar conselhos sobre quando comprar e vender nossas ações recomendadas.
As ferramentas de mineração de dados podem ser usadas para avaliar uma estratégia de linha de base simples para gerar estratégias de compra e venda de ações. Além disso, você pode usar ferramentas de mineração de dados para avaliar se os aprimoramentos de uma estratégia de linha de base melhoram os resultados comerciais para obter recomendações de compra e venda. Esta dica desenha no SQL Server T-SQL código e técnicas de mineração de dados para gerar comprar e vender conselhos de estoque e avaliar se o conselho cresce capital.
O código é apresentado em um estilo modular para que outros possam substituir partes da abordagem com suas próprias idéias ou mesmo apenas testar a dica com diferentes estoques. Esperemos que a estrutura inspire outros a implementar melhor compra e venda de modelos de estoque temporário usando o código T-SQL.
Uma dica anterior da MSSQLTips ilustrou estratégias básicas de desenvolvimento de ações comerciais. A dica anterior demonstrou que uma estratégia de compra e retenção para um conjunto seleto de ações é uma maneira confiável de aumentar o capital. No entanto, alguns investidores em ações se sentem incomodados ao manter seus fundos por um longo período de tempo, como 2 anos ou mais. Outros, acham preocupante manter posições de estoque quando vêem perdas acumuladas, se apenas por algumas semanas ou meses. Fácil de entender e implementar conselhos sobre quando comprar e vender ações recomendadas provavelmente serão bem-vindas por esses indivíduos.
Baixando os dados do site Google Finance.
As with the earlier tip on trading strategies, this tip also uses the Google Finance site as a data source for stock price histories. There is no significant change to how data were retrieved for this tip versus the prior one. Basically, the approach is as simple as inserting a URL into an Internet browser, such as IE or Chrome. The URL specifies the ticker symbol for a security along with a start date, end date, and data format for the data returned from the site.
Returned data starts with the start date or the first trading date for which Google Finance has data. The returned data ends with the last trading date for which Google Finance has data. Historical prices include the current day sometime after the close of trading for a day. The following URL specifies the download of data for Ulta Salon, Cosmetics & Fragrance, Inc., which has a ticker symbol of ulta.
Data for ten securities in four categories were downloaded from Google Finance for this tip. For easy reference, we refer in this tip to all securities as stocks although some are other investment instruments.
A core set of stocks includes six selected because I was watching them based on "due diligence." The symbols for these stocks are: bzun, crus, meet, nvda, tsn, and ulta One additional stock was selected because it is for a company that many readers of this tip are familiar -- Microsoft Corporation (msft) Two more symbols represent inverse ETF securities. The INVESTOPEDIA site defines an inverse etf as: an exchange-traded fund (ETF) constructed by using various derivatives for the purpose of profiting from a decline in the value of an underlying benchmark The benchmark for one etf (sco) is crude oil prices The benchmark for the other etf (sds) is for the S & P 500 index The final symbol is for a regular etf (spy) that tracks the S & P 500 index. Instead of moving inversely to its benchmark, this etf seeks performance that correlates with its benchmark. As with all etf securities, the spy does not perfectly match its benchmark because of various considerations, such as management fees, stock trading commissions, composition of the underlying securities, pace of changes to the benchmark versus changes to the etf, etc.
The following screen shot from Notepad++ shows the first 12 rows downloaded for the ulta stock symbol.
The first row indicates the column names for the data rows that follow The columns for data rows start with a date for the rest of the columns on that row The Open, High, Low, and Close columns display information about the price for the stock symbol over the course of the day denoted by the first column The last column for data rows indicates the number of shares traded during the day.
The download was initiated for ulta and the other nine ticker symbols used in this tip on September 7, 2016 at around 2 PM Eastern Time. Therefore, the first data row is September 6, 2016 - one day before the download date.
All the data in the screen shot above, are valid and correctly formatted. However, Google Finance very infrequently returns data rows that contain invalid data. For commercial applications that require perfectly accurate data, you should consider implementing some verification and cleaning steps that reflect the requirements of your application for the downloaded data. These steps were not taken for this tip so as not to detract from the main focus on developing buy and sell recommendations.
Import downloaded data to SQL Server.
Because Google Finance downloads one file per stock and this tip uses 10 ticker symbols, there are 10 downloaded csv files. When the files are downloaded, their name is symbol. csv. For example, the file with data for the ulta symbol has the name ulta. csv. After the csv files are downloaded, you can copy them to whatever directory is convenient for processing. This tip uses the \stock_price_histories_and_trades folder on the C: drive as a repository for downloaded data.
Notice from the screen shot above, that there is no symbol column in the individual ticker symbol files. However, when processing data for more than one symbol in a single table, it is necessary to have a symbol column in the SQL Server table along with the open, high, low, close, volume data.
This tip demonstrates a two-step approach to importing data from downloaded stock price and volume files to SQL Server tables.
Initially, the data for each file is successively inserted into a staging table Then, the data are transferred from the staging table to another table and a column is added for the investment's ticker symbol.
The overall import process relies on four tables within a database.
The imported_stock_prices table is the staging table that successively holds the csv data for each ticker symbol The stocks_symbol_ohlcv table serves as the repository for data from all ten ticker symbols A third table (WHILE_LOOP_FIELDS) contains three columns to facilitate looping through the files and copying the data with each of the ten symbols to the stocks_symbol_ohlcv table One column for each row contains a ticker symbol Another column contains a numeric field (from 1 through the number of files) for each symbol A third column for each row contains the path and file name downloaded from Google Finance A fourth temporary table (T#) is used to track which of the ten ticker symbols is currently being processed.
As the WHILE_LOOP_FIELDS table name implies, a WHILE loop is used for successively importing data from each of the downloaded csv files. Within the WHILE loop, Dynamic T-SQL code relies on a BULK INSERT statement to import all data rows from each csv file to the imported_stock_prices table. Then, an INSERT statement transfers the imported data along with a stock symbol value to the stocks_symbol_ohlcv table.
Here's the script from a sql file named import_downloaded_data_into_SQL_Server. sql that implements the steps described above. Notice the code starts with a reference to the stock_price_histories_trades database. The tip uses this database to store data for implementing and evaluating the trading rules. The resource files folder for this tip contains T-SQL code for creating a fresh, empty version of the stock_price_histories_trades database.
Review of trading rules for assigning buy and sell dates for stocks.
Two trading rules for assigning buy and sell dates to a stock are examined in this tip.
One rule is to buy stocks with rising prices that were previously not rising, and then to sell those stocks when they stop rising. This rule is named the stock-rising rule. A second buy-low rule rides on top of the first rule so that a buy is only executed when its buy price is less than the buy price for the immediately preceding trade. This rule helps to avoid buying a stock when it already has a relatively high price from which there is little upside potential. Sell recommendations are issued with the buy-low rule in the same exact way as the stock-rising rule.
This tip uses 10-day and 30-day moving averages as well as the closing price for a trading day to verify if a stock is rising. Moving average computational techniques for stock prices are examined in a prior tip. Here are two specific criteria for assessing when stocks are rising.
The close price for a stock is greater than the 10-day moving average. This indicates the most recent price for a stock is greater than its average price over the prior 10 days. The 10-day moving average is greater than the 30-day moving average. This confirms the price trend over the past 10 days is greater than the price trend over the past 30 days.
The buy recommendation for the rising-stock rule depends on the following conditions over a 5-day period.
The stock must not be rising for two successive days Followed by two more successive days in which the stock is rising The buy price is the open price on the fifth day in the sequence.
The sell recommendation for the rising-stock rule depends on the following conditions over a 2-day period.
The stock price must no longer be rising. More specifically, a day must occur in which neither the close price is above the 10-day moving average nor the 10-day moving average is above the 30-day moving average. The sell price is the open price on the next trading day.
This tip examines the two trading rules successively. First, the rising-stock price rule is implemented and examined. Second, the buy-low rule for not executing buys when the buy price is above the preceding buy price is implemented and compared to the initial rising-stock trade outcomes.
Creating and populating a table with inputs for the rising-stock rule.
To issue rising-stock buy and sell recommendations according to the rising-stock rule, an application needs to have available data for the current day, the next day, and each of three preceding days. This tip collects all these inputs into rows for the current day within the stocks_symbol_trade_inputs table. Each row of this table has the information needed to determine if the next day is a recommended buy day or sell day. It also has the date and open price for the next day, which will be useful when evaluating the trading results for the rising-stock rule.
In addition to the values downloaded from Google Finance, the code to implement the rising-stock rule needs 10-day and 30-day moving averages. These moving averages are based on the close price for 10 or 30 trading days preceding and through the current trading day. The 10-day and 30-day moving averages are compared to each other and the 10-day moving average is compared to the close price of the current day. The comparison outcomes need to be available for the current day as well as the prior three days.
This tip examines the two trading rules successively. First the rising-stock price rule is implemented and examined. Second, the buy-low rule for not executing buys when the buy price is above the preceding buy price is implemented and compared to the initial rising-stock trade outcomes.
As with the code to import downloaded values, the computations for current, lagging, and leading day values are performed inside a WHILE loop successively for each stock symbol. Before the WHILE loop starts, a CREATE TABLE statement creates the stocks_symbol_trade_inputs table. Within the WHILE loop, there is a nested sub-query for computing 10-day and 30-day moving averages. Then, and outer query computes comparisons for the current day and three prior days. The outer query derives the open price and date for the next trading day. The open price and date for the next day are candidate values for buy or sell recommended date and price.
Here's the script from a sql file named compute_trade_inputs. sql that implements the steps described above.
Creating a table with buy and sell recommendations for the rising-stock trading strategy.
The stocks_symbol_trade_inputs table serves as input to the code for yet another table (stocks_symbol_buy_sell_recs) in the assignment of recommended buy and sell dates and prices. The code for going from the stocks_symbol_trade_inputs table to the stocks_symbol_buy_sell_recs table implements the rising-stock trading strategy.
An easy way to understand the role of the stocks_symbol_buy_sell_recs table is to view selected rows from it. The following screen shot shows the last set of matching buy and sell recommendations for the ulta and crus ticker symbols in 2016 (through the final trading date of September 6, 2016 for the data used by this tip).
In the first pair of rows for ulta, there was a reversal of the rising price trend on the day (2016-02-02) for which a buy recommendation was issued. As a result, a sell recommendation was set for the next day (2016-02-03). The price for ulta on 2016-02-03 dropped from the open to the close so the close price was below the 10-day moving average; the 10-day moving average was already below the 30-day moving average. It is the close price on 2016-02-02 that caused the trade to end on 2016-02-03. In the case of the second set of buy and sell recommendations for ulta in 2016, there was a several month gap between the buy recommendation and the sell recommendation. You can verify this gap is appropriate by checking appropriate rows from the stocks_symbol_trade_inputs table.
The four rows for the crus symbol show the starting date and price versus the ending date and price for crus. For crus, several months separated the initial buy and sell recommendation, but only a few days separated the second buy and sell recommendations. As with the buy and sell recommendations for ulta, you can verify these crus outcomes for yourself by examining appropriate rows from the stocks_symbol_trade_inputs table.
This tip examines more deeply the gains and losses associated with trades in a subsequent section.
As with the scripts for other tables in the application, the code for creating and populating the stocks_symbol_buy_sell_recs table commences with a CREATE TABLE statement followed by a WHILE loop. Within the WHILE loop, the buy and sell recommendations for each symbol are added to the stocks_symbol_buy_sell_recs table.
A temporary table named #to_clean_recs serves as a staging table to accept the buy and sell recommendations for a stock symbol. This table is, in turn, created by an outer query based on a union of two sub-queries.
The first sub-query extracts selected rows from the stocks_symbol_trade_inputs table for the current symbol being processed that match the buy recommendation criteria The second sub-query performs the same function for the stocks_symbol_trade_inputs table rows that match sell recommendation criteria.
An outer query does some minor processing to facilitate ordering the buy and sell rows by date. Then, a second query does some minor cleaning to remove some sell rows that have no matching buy rows and pumps the cleansed result set for a symbol into the stocks_symbol_buy_sell_recs table.
The script (compute_buy_and_sell_recommendations. sql) that implements these steps appears below.
Compute Gain_Loss outcomes for rising-stock and buy-low trade strategies.
As you can see from the preceding screen shot, it is a relatively simple matter to compute the gain or loss associated with each trade by subtracting the buy price from the sell price. However, the structure of the stocks_symbol_buy_sell_recs table does not readily facilitate this computation because the buy and sell prices for each trade are on different rows. In addition, for some stock symbols there can be buy recommendations with no matching sell recommendation at the end of the trades for a stock. This is simply because the buy signal was issued, but the sell criteria to conclude the trade did not occur within the data downloaded for this tip (it occurred or will occur at a later date, namely after September 6, 2016).
There is one other matter that bears on gain and loss computations. So far, this tip reviewed only the detailed implementation steps for the stock-rising trading strategy. However, we need to include a second trading strategy that builds on the stock-rising strategy. This second trading rule builds on the stock-rising strategy by only including gains and losses when the buy price for a trade is less than the buy price for the immediately preceding trade. Because this buy-low trading strategy builds on the stock-rising strategy, its implementation was purposely deferred until this section.
The gains and losses per share for each trade are saved in one of two tables depending on the trading rule.
The gains and losses for the stock-rising strategy are saved in the all_trades_gain_loss table The gains and losses for the buy-low strategy are saved in the buy_low_trades_gain_loss table.
The following screen shot shows the gain and loss outcomes for the buy and sell recommendations in the preceding screen shot. Recall that these are for completed trades for ulta and crus during 2016. These data are from the all_trades_gain_loss table. You can readily confirm for yourself from the rows in the following screen shot that the gain or loss is simply the sell price less the buy price.
Also note that the per share gain is nearly $52 for ulta in the trade ending on May 24, 2016! This oversized gain is associated with a trade having a buy price that is well below the buy price of the preceding trade. In an inversely corresponding way, the crus trade ending on May 5, 2016 ends in a loss of $1.85. This trade has a buy price that is greater than the preceding trade. The buy-low trade strategy would keep the trade having a $52 per share gain and exclude the trade ending in a loss of $1.85. The buy-low trading rule can selectively include and exclude trades without actually performing the trade because it is based on a comparison of the current prospective trade buy price to the previous trade buy price. If the buy price for current prospective trade is greater than the buy price for the previous trade, the trade is not selected for execution by the buy-low trading strategy.
As discussed, the gain and loss computations depend on corresponding buy and sell prices for the buy date and sell date in a trade. The data source for these computations is the all_trades_gain_loss table for the stock-rising trade strategy. The data source for gains and losses for the buy-low trading strategy is the buy_low_trades_gain_loss table.
The following listing (create_and_populate_gain_loss_tables. sql) shows the code for creating and populating the gains and losses for each of the two trading strategies. It follows the discussion within this section as well as the general coding conventions of preceding sections about computing results for each symbol in turn.
Comparison of gain_loss performance for trading rules.
The reports in this section are from an SSRS project based on queries for the all_trades_gain_loss and buy_low_trades_gain_loss tables in the stock_price_histories_trades database. In order not to distract from focusing on the findings, the T-SQL code for the report queries do not appear in the tip. A resource folder available for download with this tip contains the SSRS project, which, in turn, has the T-SQL code for each report's query (see the Dataset Properties window of the dataset for each report within the SSRS project).
The following screen shot shows an SSRS report confirming that both the rising-stock and buy_low trading rules can return gains for selected stock categories. Results in the table are across all trades made for a stock category with a trading rule. Buy and sell prices as well as gain_loss values are in dollars on a per share basis. Broker commissions for trades are not included because these can vary depending on the broker that executes the trades.
The due diligence stocks (bzun, crus, meet, nvda, tsn, and ulta) returned a 2.56 percent gain on shares per trade with the rising-stock strategy With the buy_low trading strategy for due diligence stocks, the percentage gain per trade rises to 5.18 percent; this gain is driven substantially by a huge drop in the buy price for trades selected by the buy_low trading rule (sum of buy prices per trade was $6,119.90 with the rising-stock rule, but it was only $2,593.44 for the buy_low rule) The spy etf, which has the S & P 500 index as its benchmark, returned the same kind of trend, but not to the same extent, as the due diligence stocks Microsoft's stock did not generate gains with either rule Instead, it returned slight losses per trade basis with the rising stock rule However, the buy_low rule did cut the percentage for the size of the loss about in half The two inverse etf securities (sds and sco) did not return positive results, and the trade outcomes were about the same on a percentage basis with either rule for inverse etf securities.
There are at least three reasons why the buy_low strategy is a winner with the due diligence stocks. The following chart documents these for you.
The gain per share is nearly 70% greater for buy_low trades than rising-stock trades ($1.08 per share versus $0.64) The percentage of winning trades is marginally better with the buy_low strategy than with the rising-stock rule (by a ratio of about 32% to 30%) The number of trades with the buy_low rule is about half as many as for the rising-stock rule. The reduced number of trades makes more capital available for gains with other trades for other stocks (normally, a stock advisory firm will recommend many more than the 6 due diligence stocks covered in this tip)
Before closing, it is worthwhile taking a look at the percent gain_loss from the two trading rules with individual due diligence stocks. The buy price, sell price, and gain_loss values are the sums across all trades for a stock with a trading model. The gain loss percent is the summed gain_loss value divided by the summed buy price value represented as a percentage.
Overall, the magnitude of the gains were up 7 to 8 percent for the best performing stocks and trading strategies With the exception of one stock, the buy_low strategy improves gains or changes a loss into a gain relative to the rising-stock strategy For the one stock (nvda) that did not improve its performance with the buy_low strategy, the percentage gain was nearly identical between the two strategies The variations in outcomes by stock and trading strategy point to the value of historically testing the performance for a stock with a trading strategy before endorsing its use for trading a stock.
Próximos passos.
This tip demonstrates how to implement a baseline trading model (rising-stock) and optionally augment it with a supplemental approach (buy-low). The concepts are easy to understand, and their implementation is also relatively simple to follow. The two trading strategies can work together to preserve and grow capital.
The tip describes and demonstrates the logic behind a suite of four T-SQL scripts used for importing data, pre-processing data for implementing the trading models, and running the trading models. One goal of the tip is to encourage you to replace its trading models with ones that you prefer instead. At the very least, you are urged to replace the stocks used in this tip with those of specific interest to you.
Here are a few questions for you to consider in deciding your next steps after reading this tip.
Would you like to try this approach to see how it works with your stocks? What are some better ways of operationalizing the concepts described in the trading models examined within this tip? Will moving averages over different periods than 10 and 30 days improve the trade outcomes? Can you enhance the model for sell recommendations to retain more of the gain achieved while a stock is rising? Can you enhance the model for buy recommendations to reduce the percentage of trades that end before a stock ever starts rising? Can you design, implement, and test vastly superior trading models based on other data mining tools besides moving averages and if-then-else rules?
The resource files folder for this tip includes the four main T-SQL scripts for importing, pre-processing, and implementing the trading rules as well as selected other scripts for data displayed in screen shots that support the explanation of the trading rules. Additionally, the resource files include the SSRS project files for the reports in the Comparison of gain_loss performance for trading rules section. Please be sure and review the readme. txt file in the resource solution folder before trying to reproduce any results in this tip based on the files in the resource files folder.
Finally, I close by indicating that this tip is not recommending any particular stocks, including the ten analyzed ones. These stocks were chosen because I had been watching them as part of my normal investing due diligence. At the time that I submitted this tip to MSSQLTips, I or other immediate family members held positions in seven stocks among the ten in the tip.
Sobre o autor.
Nice article using SQL Server to predict the trend. :)
Aprendendo.
Pesquisa.
Mais informações.
Copyright (c) 2006-2018 Edgewood Solutions, LLC All rights reserved.
Some names and products listed are the registered trademarks of their respective owners.

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

Комментариев нет:

Отправить комментарий