Aprendizado de máquinas para negociação.
Inteligência Artificial (AI) e Aprendizado de Máquinas (ML) estão revolucionando quimicamente quase todas as áreas de nossas vidas. Você sabia que os algoritmos de negociação mais recentes estão usando essas tecnologias extensivamente?
Você pode se surpreender ao saber que os fundos de hedge da Machine Learning já superaram significativamente os fundos de hedge generalizados, bem como os fundos de quantia tradicionais, de acordo com um relatório da ValueWalk. Os sistemas ML e AI podem ser ferramentas incrivelmente úteis para os seres humanos navegando no processo de tomada de decisão envolvendo investimentos e avaliação de risco.
O impacto das emoções humanas nas decisões de negociação é muitas vezes o maior obstáculo para o desempenho superior. Algoritmos e computadores tomam decisões e executam trades mais rapidamente do que qualquer ser humano, e libertam-se da influência das emoções.
Existem vários tipos diferentes de negociação algorítmica. Alguns exemplos são os seguintes:
Algoritmos de execução comercial, que dividem os negócios em ordens menores para minimizar o impacto no preço das ações. Um exemplo disto é uma estratégia de preço médio ponderado por volume (VWAP) Estratégia de algoritmos de implementação que fazem negócios com base em sinais de dados de mercado em tempo real. Exemplos disso são estratégias baseadas em tendências que envolvem médias móveis, fuga de canais, movimentos de níveis de preços e outros indicadores técnicos. Algoritmos de discrição / jogo que são orientados para detectar e aproveitar os movimentos de preços causados por grandes negócios e / ou outras estratégias de algoritmos. Oportunidades de arbitragem. Um exemplo seria onde uma ação pode negociar em dois mercados separados por dois preços diferentes e a diferença de preço pode ser capturada vendendo ações com preços mais altos e comprando ações com preço mais baixo.
Quando as estratégias de negociação algorítmica foram introduzidas pela primeira vez, elas foram lucrativamente lucrativas e ganharam rapidamente participação de mercado. Em maio de 2017, a empresa de pesquisa de mercado Tabb Group disse que a negociação de alta freqüência (HFT) representou 52% do volume médio diário de negociação. Mas, à medida que a concorrência aumentou, os lucros diminuíram. Neste ambiente cada vez mais difícil, os comerciantes precisam de uma nova ferramenta para dar-lhes uma vantagem competitiva e aumentar os lucros. A boa notícia é que a ferramenta está aqui agora: Aprendizado de Máquinas.
A aprendizagem de máquinas envolve a alimentação de um algoritmo de amostras de dados, geralmente derivados de preços históricos. As amostras de dados consistem em variáveis chamadas preditores, bem como uma variável alvo, que é o resultado esperado. O algoritmo aprende a usar as variáveis preditoras para prever a variável alvo.
A aprendizagem de máquinas oferece o número de vantagens importantes em relação aos programas algorítmicos tradicionais. O processo pode acelerar a busca de estratégias de negociação algorítmicas efetivas, automatizando o que muitas vezes é um processo manual tedioso. Também aumenta o número de mercados que um indivíduo pode monitorar e responder. Mais importante ainda, eles oferecem a capacidade de passar de encontrar associações baseadas em dados históricos para identificar e se adaptar às tendências à medida que elas se desenvolvem. Se você pode automatizar um processo, outros estão executando manualmente; Você tem uma vantagem competitiva. Se você pode aumentar a quantidade de mercados em que você está, você terá mais oportunidades. E no mundo de negociação de soma zero, se você pode se adaptar a mudanças em tempo real, enquanto outros estão parados, sua vantagem se traduzirá em lucros.
Existem múltiplas estratégias que utilizam o aprendizado da máquina para otimizar os algoritmos, incluindo: regressões lineares, redes neurais, aprendizado profundo, máquinas de vetor de suporte e Bayes ingênuos, para citar alguns. E fundos bem conhecidos como Citadel, Renaissance Technologies, Bridgewater Associates e Two Sigma Investments estão buscando estratégias de aprendizado de máquina como parte de sua abordagem de investimento. Na Sigmoidal, temos a experiência e o know-how para ajudar os comerciantes a incorporar ML nas suas próprias estratégias de negociação.
Nosso estudo de caso.
Em um de nossos projetos, nós criamos um sistema inteligente de alocação de ativos que utilizou Deep Learning e Modern Portfolio Theory. A tarefa era implementar uma estratégia de investimento que pudesse se adaptar a mudanças rápidas no ambiente de mercado.
O modelo base AI foi responsável pela previsão de retorno de ativos com base em dados históricos. Isso foi realizado através da implementação de Unidades de Memória de Longo Prazo Longas, que são uma generalização sofisticada de uma Rede Neural Recorrente. Esta arquitetura particular pode armazenar informações para vários timestaps, o que é possível por uma célula de memória. Esta propriedade permite ao modelo aprender padrões temporais longos e complicados em dados. Como resultado, conseguimos prever os retornos futuros do ativo, bem como a incerteza de nossas estimativas utilizando uma técnica inovadora denominada Dropway Variacional.
Para fortalecer nossas previsões, usamos uma riqueza de dados de mercado, como moedas, índices, etc. em nosso modelo, além dos retornos históricos dos ativos relevantes. Isso resultou em mais de 400 recursos que usamos para fazer previsões finais. Claro, muitas dessas características foram correlacionadas. Esse problema foi atenuado pela Análise de Componentes Principais (PCA), o que reduz a dimensionalidade do problema e decorra os recursos.
Usamos as previsões de retorno e risco (incerteza) para todos os ativos como entradas para um algoritmo de Otimização de Variância Média, que usa um solucionador quadrático para minimizar o risco de um determinado retorno. Este método determina a alocação de ativos, que é diversificada e garante o menor nível de risco possível, atendendo às previsões dos retornos.
A combinação desses modelos criou uma estratégia de investimento que gerou um retorno anualizado de 8%, que foi 23% maior do que qualquer outra estratégia de benchmark testada ao longo de um período de dois anos. Contacte-nos para saber mais.
As estratégias de IA superam a performance.
É difícil encontrar dados de desempenho para as estratégias de AI, dado a sua natureza proprietária, mas a empresa de pesquisa de hedge funds Eurekahedge publicou alguns dados informativos. O gráfico abaixo mostra o desempenho do índice Eurekahedge AI / Machine Learning Hedge Fund vs. vs. Quantos fundos tradicionais de 2018 a 2018. O índice rastreia 23 fundos no total, dos quais 12 continuam a viver.
Eurekahedge observa que:
"Os fundos de hedge de AI / máquina de aprendizagem superaram os quantis tradicionais e o hedge fund médio desde 2018, apresentando rendimentos anualizados de 8,44% ao longo desse período, em comparação com 2,62%, 1,62% e 4,27% para os seguidores de tendências da CTA, e o hedge global médio fundo, respectivamente. "
Eurekahedge também fornece a seguinte tabela com as principais opções:
Tabela 1: Desempenho em números - AI / Machine Learning Hedge Fund Index vs. quants e hedge funds tradicionais.
Os fundos de hedge de aprendizado de AI / máquina superaram o fundo de hedge global médio para todos os anos, excluindo 2018.
Salvo em 2018 e em 2018, os retornos para os fundos de hedge de aprendizado de AI / máquina superaram os padrões tradicionais de estratégias de futuros administrados pelo CTA, e apresentaram uma tendência sistemática de tendência sistemática inferior ao ano de 2018, quando estes realizaram ganhos fortes de futuros de energia curta.
Durante o período anualizado de cinco, três e dois anos, os fundos de hedge de aprendizagem de AI / máquina superaram as quantas tradicionais e o fundo de hedge global médio, apresentando ganhos anualizados de 7,35%, 9,57% e 10,56%, respectivamente, ao longo desses períodos.
Os fundos de hedge de aprendizado de AI / máquina também apresentaram melhores retornos ajustados ao risco nos últimos dois anos e três períodos anualizados em comparação com todos os pares descritos na tabela abaixo, com índices de Sharpe de 1,51 e 1,53 em ambos os períodos, respectivamente.
Embora os retornos tenham sido mais voláteis em comparação com o fundo de hedge médio (compare com o índice Eurekahedge Hedge Fund), os fundos de aprendizagem de AI / máquina apresentaram volatilidades anualizadas consideravelmente menores em comparação com estratégias de tendências sistemáticas.
Eurekahedge também observa que os hedge funds AI / machine learning estão "correlacionados negativamente com o fundo de hedge médio (-0,267)" e têm "correlação zero-a-marginalmente positiva para os futuros de CTA / futuros gerenciados e as estratégias seguindo a tendência", que apontam para potenciais benefícios de diversificação de uma estratégia de AI.
Os dados acima ilustram o potencial na utilização de AI e Aprendizado de Máquinas em estratégias de negociação. Felizmente, os comerciantes ainda estão nos estágios iniciais de incorporar essa ferramenta poderosa em suas estratégias de negociação, o que significa que a oportunidade permanece relativamente inexplorada e o potencial significativo.
Aqui está um exemplo de uma aplicação de AI na prática.
Sistema de texto financeiro do Arizona (AZFinText)
Imagine um sistema que possa monitorar os preços das ações em tempo real e prever os movimentos dos preços das ações com base no fluxo de notícias. É exatamente isso que o AZFinText faz. Este artigo descreve uma experiência que usou o Support Vector Machine (SVM) para trocar S & amp; P-500 e produziu excelentes resultados. Abaixo está a tabela que mostra como foi realizada em relação aos 10 principais fundos de investimento quantitativos do mundo:
Estratégia usando o Google Trends.
Outra estratégia de comércio experimental usou o Google Trends como uma variável. Há uma infinidade de artigos sobre o uso do Google Trends como um indicador de sentimento de um mercado.
O experimento neste artigo acompanhou as mudanças no volume de pesquisa de um conjunto de 98 termos de busca (alguns deles relacionados ao mercado de ações). O termo "dívida" acabou por ser o indicador mais forte e confiável quando se prevê movimentos de preços no DJIA.
Abaixo está um gráfico de desempenho cumulativo. A linha vermelha descreve um "comprar e segurar" estratégia. A estratégia Google Trends (linha azul) superou massivamente com um retorno de 326%.
Posso aprender ML mesmo?
Aplicando máquina Aprender a negociar é um topis vasto e complicado que leva o tempo para dominar. Mas se você estiver interessado, como ponto de partida, recomendamos:
Uma vez que você está familiarizado com esses materiais, há um curso de Udacity popular em hot para aplicar a base da Aprendizagem de Máquinas para negociação no mercado.
Se você quiser acelerar o processo de aprendizagem, você pode contratar um consultor. Certifique-se de fazer perguntas difíceis antes de iniciar um projeto.
Ou, você pode agendar uma pequena chamada conosco para explorar o que pode ser feito.
Preciso de exemplos mais específicos aplicáveis na minha indústria.
Ao incorporar a Aprendizagem de Máquinas em suas estratégias comerciais, seu portfólio pode capturar mais alfa. Mas implementar uma estratégia bem sucedida de investimento ML é difícil, você precisará de pessoas extraordinárias e talentosas com experiência em comércio e ciência dos dados para chegar lá. Deixe-nos ajudá-lo a começar.
Procurando por consultoria em Aprendizado de máquinas?
Compartilhe esta publicação.
Obtenha novas informações sobre como conseguir que os dados funcionem!
Assine as atualizações da Sigmoidal.
Minha experiência com Docker Swarm - Como saber quando você pode precisar disso.
Nesta publicação, vou analisar o papel do Docker em cada etapa do ciclo de vida do aplicativo e do & hellip;
Aprendizagem profunda para visão computacional - indo além da classificação e regressão da imagem.
Desde 2018, quando AlexNet apareceu e quebrou quase todos os registros em concursos de classificação de imagens, a paisagem de um & hellip;
Jesse Spaulding.
Como fiz $ 500k com aprendizado de máquina e HFT (negociação de alta freqüência)
Esta publicação detalhará o que fiz para fazer aprox. 500k de negociação de alta freqüência de 2009 a 2018. Desde que eu estava negociando completamente de forma independente e não estou mais executando meu programa, eu estou feliz em contar tudo. Minha negociação foi principalmente em contratos de futuros Russel 2000 e DAX.
A chave para o meu sucesso, eu acredito, não estava em uma equação financeira sofisticada, mas sim no projeto de algoritmo geral que uniu muitos componentes simples e a aprendizagem de máquinas usadas para otimizar a máxima rentabilidade. Você ganhou não precisa conhecer qualquer terminologia sofisticada aqui porque, quando eu configurei meu programa, tudo foi baseado na intuição. (O curso de aprendizado de máquina incrível da Andrew Ng não estava ainda disponível - por favor, se você clicar nesse link, você será levado ao meu projeto atual: CourseTalk, um site de revisão para MOOCs)
Primeiro, eu só quero demonstrar que o meu sucesso não foi simplesmente o resultado da sorte. Meu programa fez 1000-4000 negociações por dia (meio e meio, curto) e nunca entrou em posições de mais de alguns contratos por vez. Isso significava que a sorte aleatória de qualquer comércio em particular era muito rápida. O resultado foi que nunca perdi mais de US $ 2000 em um dia e nunca tive um mês perdedor:
(EDITAR: estes números são depois de pagar comissões)
E aqui é um gráfico para dar uma sensação de variação diária. Observe que isso exclui os últimos 7 meses porque - à medida que os números pararam de subir - eu perdi minha motivação para inseri-los.
Antes de configurar meu programa de negociação automatizado I & rsquo; d tinha 2 anos de experiência como um & ldquo; manual & rdquo; comerciante do dia. Isso foi de volta em 2001 - foram os primeiros dias do comércio eletrônico e houve oportunidades para & ldquo; scalpers & rdquo; para ganhar dinheiro. Eu só posso descrever o que eu estava fazendo como semelhante a jogar um jogo de vídeo / jogo com uma suposta vantagem. Ser bem-sucedido significou ser rápido, ser disciplinado e possuir boas habilidades de reconhecimento de padrões intuitivas. Eu consegui fazer cerca de US $ 250 mil, pagar meus empréstimos estudantis e ter dinheiro restante. Ganhar!
Nos próximos cinco anos, eu lançaria duas startups, pegando algumas habilidades de programação ao longo do caminho. Não seria até o final de 2008 que eu voltaria a negociar. Com o dinheiro escorrendo da venda da minha primeira inicialização, a negociação ofereceu esperanças de algum dinheiro rápido enquanto eu descobri minha próxima jogada.
Em 2008 eu estava & ldquo; manualmente & rdquo; dia comercializando futuros usando o software chamado T4. Eu estava desejando algumas teclas de atalho de entrada de pedidos personalizadas, então, depois de descobrir que a T4 tinha uma API, assumi o desafio de aprender C # (a linguagem de programação necessária para usar a API) e segui adiante e me criei algumas teclas rápidas.
Depois de ficar com os pés molhados com a API, logo tive aspirações maiores: queria ensinar o computador a trocar por mim. A API forneceu um fluxo de dados de mercado e uma maneira fácil de enviar ordens para a troca - tudo o que eu tinha que fazer era criar a lógica no meio.
Abaixo está uma captura de tela de uma janela de negociação T4. O que foi legal é que, quando trabalhei, consegui assistir o comércio de computadores nesta mesma interface. Ver as ordens reais que aparecem dentro e fora (por si com meu dinheiro real) foram emocionantes e assustadoras.
O design do meu algoritmo.
Desde o início, meu objetivo era configurar um sistema de forma que eu pudesse estar razoavelmente confiante. Eu ganharei dinheiro antes de fazer qualquer transação ao vivo. Para realizar isso, eu precisava construir uma estrutura de simulação de negociação que, com a maior precisão possível, simulasse a negociação ao vivo.
Embora a negociação no modo ao vivo exigisse o processamento de atualizações de mercado transmitidas através da API, o modo de simulação exigia a leitura de atualizações de mercado a partir de um arquivo de dados. Para coletar esses dados, configurei a primeira versão do meu programa para simplesmente conectar-se à API e registrar as atualizações do mercado com timestamps. Acabei usando 4 semanas de dados de mercado recentes para treinar e testar meu sistema.
Com um quadro básico no local, eu ainda tinha a tarefa de descobrir como criar um sistema comercial lucrativo. Como se verifica, meu algoritmo seria dividido em dois componentes distintos, que eu explorarei por sua vez:
Previsão de movimentos de preços; e fazer negócios lucrativos.
Previsão de movimentos de preços.
Talvez um componente óbvio de qualquer sistema comercial seja capaz de prever onde os preços se moverão. E o meu não foi exceção. Eu definei o preço atual como a média da oferta interna e oferta interna e eu estabeleci o objetivo de prever onde o preço seria nos próximos 10 segundos. Meu algoritmo precisaria apresentar esta previsão momento a momento ao longo do dia de negociação.
Criando & amp; indicadores de otimização.
Eu criei um punhado de indicadores que provaram ter uma habilidade significativa para prever movimentos de preços de curto prazo. Cada indicador produziu um número que era positivo ou negativo. Um indicador era útil se, com maior frequência, um número positivo correspondesse com o mercado subindo e um número negativo correspondia ao mercado descer.
Meu sistema me permitiu determinar rapidamente a capacidade preditiva de qualquer indicador, então eu consegui experimentar muitos indicadores diferentes para ver o que funcionou. Muitos dos indicadores tinham variáveis nas fórmulas que os produziam e consegui encontrar os valores ótimos para essas variáveis, fazendo comparações lado a lado dos resultados obtidos com valores variáveis.
Os indicadores que foram mais úteis foram todos relativamente simples e foram baseados em eventos recentes no mercado que negociei, bem como os mercados de títulos correlacionados.
Fazendo previsões de movimento de preço exato.
Ter indicadores que simplesmente previam um movimento de preços para cima ou para baixo não era suficiente. Eu precisava saber exatamente quanto o movimento do preço era previsto por cada valor possível de cada indicador. Eu precisava de uma fórmula que convertesse um valor indicador para uma previsão de preços.
Para realizar isso, rastreei os movimentos de preços previstos em 50 baldes que dependiam do alcance em que o valor do indicador caiu. Isso produziu previsões únicas para cada balde que eu então consegui representar no Excel. Como você pode ver, a variação esperada do preço aumenta à medida que o valor do indicador aumenta.
Com base em um gráfico como esse, consegui fazer uma fórmula para ajustar a curva. No começo eu fiz isso & ldquo; curve fitting & rdquo; manualmente, mas logo escrevi algum código para automatizar esse processo.
Observe que nem todas as curvas indicadoras tiveram a mesma forma. Observe também que os baldes foram distribuídos logaritticamente de modo a espalhar os dados de forma uniforme. Finalmente, note que os valores de indicadores negativos (e as respectivas previsões de preços descendentes correspondentes) foram invertidos e combinados com os valores positivos. (Meu algoritmo tratado de forma ascendente e exata exatamente o mesmo.)
Combinando indicadores para uma única previsão.
Uma coisa importante a considerar era que cada indicador não era totalmente independente. Eu não poderia simplesmente resumir todas as previsões que cada indicador faz individualmente. A chave era descobrir o valor preditivo adicional que cada indicador tinha além do que já estava previsto. Isso não era muito difícil de implementar, mas isso significava que se eu fosse & ldquo; curve fitting & rdquo; vários indicadores ao mesmo tempo eu tive que ter cuidado; mudar um afetaria as previsões de outro.
A fim de & ldquo; curve fit & rdquo; Todos os indicadores ao mesmo tempo eu configurei o otimizador para passar apenas 30% do caminho para as novas curvas de previsão com cada passagem. Com este salto de 30%, descobri que as curvas de previsão se estabilizariam dentro de algumas passagens.
Com cada indicador agora nos dando a previsão de preço adicional de ñsquo; eu poderia simplesmente adicioná-los para produzir uma previsão única de onde o mercado seria em 10 segundos.
Por que a previsão de preços não é suficiente.
Você pode pensar que com essa vantagem no mercado eu estava dourado. Mas você precisa ter em mente que o mercado é composto por lances e ofertas - não é apenas um preço de mercado. O sucesso na negociação de alta freqüência se resume a obter bons preços e não é tão fácil.
Os seguintes fatores tornam difícil a criação de um sistema lucrativo:
Com cada troca eu tinha que pagar comissões para o meu corretor e a troca. O spread (diferença entre oferta mais alta e oferta mais baixa) significava que, se eu fosse simplesmente comprar e vender aleatoriamente, eu estaria perdendo uma tonelada de dinheiro. A maior parte do volume do mercado eram outros bots que só executariam um comércio comigo se achassem que tinham alguma vantagem estatística. Ver uma oferta não garantiu que eu pudesse comprá-la. No momento em que minha ordem de compra chegou ao intercâmbio, era muito possível que essa oferta tivesse sido cancelada. Como um pequeno jogador do mercado, não havia nenhuma maneira de eu competir sozinho na velocidade.
Construindo uma simulação de negociação completa.
Então eu tive uma estrutura que me permitiu backtest e otimizar indicadores. Mas eu tinha que ir além disso - eu precisava de uma estrutura que me permitisse fazer backtest e otimizar um sistema comercial completo; um onde eu estava mandando ordens e entrando em posições. Neste caso, I & rsquo; d seja otimizado para P & amp; L total e, em certa medida, P & amp; L médio por comércio.
Isso seria mais complicado e, de certa forma, impossível modelar exatamente, mas eu fiz o melhor que pude. Aqui estão algumas das questões que eu tive que lidar com:
Quando um pedido foi enviado ao mercado em simulação, tive que modelar o tempo de atraso. O fato de meu sistema ter visto uma oferta não significava que pudesse comprá-lo imediatamente. O sistema enviaria o pedido, espere aproximadamente 20 milissegundos e, em seguida, apenas se a oferta ainda fosse considerada como um comércio executado. Isso foi inexato porque o tempo de atraso real foi inconsistente e não relatado. Quando eu coloquei lances ou ofertas, tive que olhar para o fluxo de execução comercial (fornecido pela API) e usá-los para avaliar quando minha ordem teria sido executada contra. Para fazer isso, tive que rastrear a posição do meu pedido na fila. (É um sistema de primeira saída em primeiro lugar). Mais uma vez, não consegui fazer isso perfeitamente, mas fiz uma melhor aproximação.
Para refinar a simulação de execução do meu pedido, fiz os meus arquivos de log da negociação ao vivo através da API e comparei-os aos arquivos de log produzidos por negociação simulada do mesmo período. Eu consegui minha simulação até o ponto de ser bastante preciso e, para as partes que eram impossíveis de modelar exatamente, me assegurei pelo menos de produzir resultados estatisticamente similares (nas métricas que achava importantes).
Faz negócios lucrativos.
Com um modelo de simulação de ordem no local, agora eu poderia enviar ordens no modo de simulação e ver uma P & amp; L simulada. Mas como saberia o meu sistema quando e onde comprar e vender?
As previsões de movimento de preços foram um ponto de partida, mas não toda a história. O que eu fiz foi criar um sistema de pontuação para cada um dos 5 níveis de preço na oferta e oferta. Estes incluíram um nível acima da oferta interna (para um pedido de compra) e um nível abaixo da oferta interna (para uma ordem de venda).
Se a pontuação em qualquer nível de preço fosse superior a um certo limite que significaria que meu sistema deveria ter uma oferta / oferta ativa - abaixo do limite, então todas as ordens ativas deveriam ser canceladas. Com base nisso, não era incomum que meu sistema iria mostrar uma oferta no mercado e, em seguida, cancelá-lo imediatamente. (Embora eu tentei minimizar isso, como é irritante, como diabos para quem olha a tela com olhos humanos - inclusive eu.)
Os escores do nível de preços foram calculados com base nos seguintes fatores:
A previsão do movimento do preço (que discutimos anteriormente). O nível de preços em questão. (Os níveis internos significaram que foram necessárias maiores previsões de movimento de preços). O número de contratos na frente do meu pedido na fila. (Menos foi melhor.) O número de contratos por trás do meu pedido na fila. (Mais foi melhor.)
Essencialmente, esses fatores serviram para identificar & ldquo; safe & rdquo; lugares para oferecer / oferecer. A previsão de movimento de preço por si só não era adequada porque não explicava o fato de que ao colocar uma oferta eu não estava preenchido automaticamente - eu só cheguei se alguém me vendesse lá. A realidade era que o simples fato de alguém me vender a um certo preço alterou as probabilidades estatísticas do comércio.
As variáveis utilizadas nesta etapa estavam todas sujeitas a otimização. Isso foi feito exatamente da mesma maneira que otimizei variáveis nos indicadores de movimento de preços, exceto neste caso eu estava otimizando a linha de fundo P & amp; L.
Ao negociar como seres humanos, muitas vezes temos poderosas emoções e desvios que podem levar a decisões menos do que ótimas. Claramente, não queria codificar esses preconceitos. Aqui estão alguns fatores que meu sistema ignorou:
O preço que uma posição foi inserida - Em um escritório de negociação, é muito comum ouvir a conversa sobre o preço no qual alguém é longo ou curto, como se isso pudesse afetar a futura tomada de decisões. Embora isso tenha alguma validade como parte de uma estratégia de redução de risco, ele realmente não tem influência no futuro dos eventos no mercado. Portanto, meu programa ignorou completamente essa informação. É o mesmo conceito que ignorar custos irrecuperáveis. Ir a curto vs. sair de uma posição longa - Normalmente, um comerciante teria critérios diferentes que determinam onde vender uma posição longa versus onde ficar curto. No entanto, da minha perspectiva de algoritmos não havia motivo para fazer uma distinção. Se o meu algoritmo esperava que uma venda de movimento descendente fosse uma boa idéia, independentemente de ser atualmente longa, curta ou plana. A & ldquo; dobrando para cima & rdquo; estratégia - Esta é uma estratégia comum em que os comerciantes comprarão mais ações no caso de o comércio original ir contra elas. Isso resulta em um preço de compra médio menor e significa que quando (ou se) o estoque se virar, você estará configurado para fazer o seu dinheiro de volta em nenhum momento. Na minha opinião, esta é realmente uma estratégia horrível, a menos que você seja o Warren Buffet. Você está enganado para pensar que você está indo bem porque a maioria de seus negócios serão vencedores. O problema é quando você perde você perder grande. O outro efeito é que dificilmente julgar se você realmente tem uma vantagem no mercado ou está apenas tendo sorte. Ser capaz de monitorar e confirmar que o meu programa de fato teve uma vantagem foi um objetivo importante.
Uma vez que meu algoritmo tomou decisões do mesmo modo, independentemente de onde ele entrou em um comércio ou se fosse atualmente longo ou curto, ocasionalmente sentava-se (e aceitou) alguns grandes negócios perdidos (além de alguns grandes negócios vencedores). Mas, você não deveria pensar que não havia nenhum gerenciamento de riscos.
Para gerenciar o risco, apliquei um tamanho máximo de posição de 2 contratos por vez, ocasionalmente acumulado em dias de alto volume. Eu também tive um limite máximo de perda diária para proteger contra quaisquer condições de mercado inesperadas ou um erro no meu software. Esses limites foram aplicados no meu código, mas também no backend através do meu corretor. Como aconteceu, nunca encontrei problemas significativos.
Desde o momento em que comecei a trabalhar no meu programa, demorei cerca de 6 meses antes de chegar ao ponto de rentabilidade e começar a executá-lo ao vivo. Embora seja justo, uma quantidade significativa de tempo foi aprender uma nova linguagem de programação. Enquanto trabalhava para melhorar o programa, vi maiores lucros para cada um dos próximos quatro meses.
Todas as semanas, eu treinaria o sistema com base nas 4 semanas anteriores de dados. Eu achei que isso atingiu o equilíbrio certo entre a captura de tendências comportamentais recentes do mercado e garantir que meu algoritmo tivesse dados suficientes para estabelecer padrões significativos. À medida que o treinamento começou a tomar mais e mais tempo, eu o separei para que ele possa ser executado por 8 máquinas virtuais usando o Amazon EC2. Os resultados foram então agrupados na minha máquina local.
O ponto alto da minha negociação foi em outubro de 2009, quando eu fiz quase 100k. Depois disso, continuei a gastar os próximos quatro meses tentando melhorar meu programa, apesar da diminuição do lucro a cada mês. Infelizmente, neste ponto, acho que eu implementei todas as minhas melhores idéias, porque nada que tentei pareceu ajudar muito.
Com a frustração de não poder fazer melhorias e não ter um senso de crescimento, comecei a pensar em uma nova direção. Eu enviei 6 empresas de comércio de alta freqüência diferentes para ver se eles estavam interessados em comprar meu software e me contratar para trabalhar para eles. Ninguém respondeu. Eu tive algumas idéias de inicialização novas que queria trabalhar, então eu nunca segui.
UPDATE - Posteci isso no Hacker News e tem tido muita atenção. Eu só quero dizer que não defendo ninguém tentando fazer algo assim agora. Você precisaria de uma equipe de pessoas realmente inteligentes com uma variedade de experiências para ter alguma esperança de competir. Mesmo quando eu estava fazendo isso, eu acreditava que era muito raro que os indivíduos conseguissem sucesso (embora eu tivesse ouvido falar de outros).
Há um comentário no topo da página que menciona "estatísticas manipuladas" e se refere a mim como um investidor de varejo & ldquo; rdquo; que os quants gostariam de escolher com entusiasmo & rdquo ;. Este é um comentário bastante infeliz que simplesmente não é baseado na realidade. Configurando isso de lado há alguns comentários interessantes: news. ycombinator / item? Id = 4748624.
UPDATE # 2 - I & rsquo; postou um FAQ de seguimento que responde algumas perguntas comuns que eu recebi dos comerciantes sobre esta publicação.
Delhideviant gostou disto.
Oi, sou Jesse, fundador da Thinklab. Eu vivo e toco em São Francisco. Você encontrou minha casa na web ... Bem-vindo!
Melhores estratégias 4: Aprendizado de máquinas.
Deep Blue foi o primeiro computador que ganhou um campeonato mundial de xadrez. Isso foi em 1996 e levou 20 anos até que outro programa, o AlphaGo, pudesse derrotar o melhor jogador Go humano. Deep Blue era um sistema baseado em modelo com regras de xadrez hardwired. O AlphaGo é um sistema de mineração de dados, uma rede neural profunda treinada com milhares de jogos Go. Hardware não melhorado, mas um avanço no software foi essencial para o passo de vencer os melhores jogadores de xadrez para vencer os melhores jogadores Go.
Nesta 4ª parte da mini-série, analisaremos a abordagem de mineração de dados para o desenvolvimento de estratégias comerciais. Este método não se preocupa com os mecanismos de mercado. Ele apenas verifica curvas de preços ou outras fontes de dados para padrões preditivos. Aprendizagem de máquina ou "Inteligência Artificial" e # 8221; nem sempre está envolvido em estratégias de mineração de dados. Na verdade, o mais popular & # 8211; e surpreendentemente lucrativo & # 8211; O método de mineração de dados funciona sem redes neurais sofisticadas ou máquinas de vetor de suporte.
Princípios de aprendizado da máquina.
Um algoritmo de aprendizagem é alimentado com amostras de dados, normalmente derivadas de algum modo de preços históricos. Cada amostra consiste em n variáveis x 1 .. x n, comumente designadas preditores, recursos, sinais ou simplesmente entrada. Esses preditores podem ser os retornos de preços das últimas barras n, ou uma coleção de indicadores clássicos, ou qualquer outra função imaginável da curva de preços (I & # 8217; até mesmo visto os pixels de uma imagem de gráfico de preços usada como preditor para uma neural rede!). Cada amostra também inclui normalmente uma variável alvo y, como o retorno do próximo comércio depois de tirar a amostra, ou o próximo movimento de preços. Na literatura, você pode encontrar também o nome do rótulo ou objetivo. Em um processo de treinamento, o algoritmo aprende a prever o alvo y a partir dos preditores x 1 .. x n. A memória aprendida & # 8216; & # 8217; é armazenado em uma estrutura de dados chamada modelo que é específico para o algoritmo (não deve ser confundido com um modelo financeiro para estratégias baseadas em modelos!). Um modelo de aprendizagem de máquina pode ser uma função com regras de predição no código C, gerado pelo processo de treinamento. Ou pode ser um conjunto de pesos de conexão de uma rede neural.
Os preditores, características, ou o que quer que você os chama, devem conter informações suficientes para prever o alvo e com alguma precisão. Eles também cumprem com freqüência dois requisitos formais. Primeiro, todos os valores de preditores devem estar no mesmo intervalo, como -1 ... +1 (para a maioria dos algoritmos R) ou -100 ... +100 (para algoritmos Zorro ou TSSB). Então você precisa normalizá-los de alguma forma antes de enviá-los para a máquina. Em segundo lugar, as amostras devem ser equilibradas, ou seja, distribuídas igualmente em todos os valores da variável alvo. Então, deve haver quase tantos como ganhar amostras. Se você não observar estes dois requisitos, você se perguntará por que você está obtendo resultados ruins do algoritmo de aprendizado da máquina.
Os algoritmos de regressão prevêem um valor numérico, como a magnitude e o sinal do próximo movimento de preços. Os algoritmos de classificação prevêem uma classe de amostra qualitativa, por exemplo, se ela está precedendo uma vitória ou uma perda. Alguns algoritmos, como redes neurais, árvores de decisão ou máquinas de vetor de suporte, podem ser executados em ambos os modos.
Alguns algoritmos aprendem a dividir amostras em classes sem necessidade de qualquer alvo y. A aprendizagem sem supervisão desse tipo, em oposição à aprendizagem supervisionada usando um alvo. Somewhere inbetween é o aprendizado de reforço, onde o sistema se treina executando simulações com os recursos fornecidos e usando o resultado como alvo de treinamento. AlphaZero, o sucessor do AlphaGo, usou a aprendizagem de reforço ao jogar milhões de jogos Go contra si. Em finanças, há poucas aplicações para aprendizagem sem supervisão ou reforço. 99% das estratégias de aprendizagem de máquinas usam a aprendizagem supervisionada.
Independentemente dos sinais que usamos para preditores em finanças, eles provavelmente contêm muito ruído e pouca informação, e não serão estacionários além disso. Portanto, a previsão financeira é uma das tarefas mais difíceis na aprendizagem por máquinas. Algoritmos mais complexos não conseguem necessariamente melhores resultados. A seleção dos preditores é fundamental para o sucesso. It is no good idea to use lots of predictors, since this simply causes overfitting and failure in out of sample operation. Therefore data mining strategies often apply a preselection algorithm that determines a small number of predictors out of a pool of many. The preselection can be based on correlation between predictors, on significance, on information content, or simply on prediction success with a test set. Practical experiments with feature selection can be found in a recent article on the Robot Wealth blog.
Here’s a list of the most popular data mining methods used in finance.
1. Indicator soup.
Most trading systems we’re programming for clients are not based on a financial model. The client just wanted trade signals from certain technical indicators, filtered with other technical indicators in combination with more technical indicators. When asked how this hodgepodge of indicators could be a profitable strategy, he normally answered: “Trust me. I’m trading it manually, and it works.”
It did indeed. At least sometimes. Although most of those systems did not pass a WFA test (and some not even a simple backtest), a surprisingly large number did. And those were also often profitable in real trading. The client had systematically experimented with technical indicators until he found a combination that worked in live trading with certain assets. This way of trial-and-error technical analysis is a classical data mining approach, just executed by a human and not by a machine. I can not really recommend this method – and a lot of luck, not to speak of money, is probably involved – but I can testify that it sometimes leads to profitable systems.
2. Candle patterns.
Not to be confused with those Japanese Candle Patterns that had their best-before date long, long ago. The modern equivalent is price action trading . You’re still looking at the open, high, low, and close of candles. You’re still hoping to find a pattern that predicts a price direction. But you’re now data mining contemporary price curves for collecting those patterns. There are software packages for that purpose. They search for patterns that are profitable by some user-defined criterion, and use them to build a specific pattern detection function. It could look like this one (from Zorro’s pattern analyzer):
This C function returns 1 when the signals match one of the patterns, otherwise 0. You can see from the lengthy code that this is not the fastest way to detect patterns. A better method, used by Zorro when the detection function needs not be exported, is sorting the signals by their magnitude and checking the sort order. An example of such a system can be found here.
Can price action trading really work? Just like the indicator soup, it’s not based on any rational financial model. One can at best imagine that sequences of price movements cause market participants to react in a certain way, this way establishing a temporary predictive pattern. However the number of patterns is quite limited when you only look at sequences of a few adjacent candles. The next step is comparing candles that are not adjacent, but arbitrarily selected within a longer time period. This way you’re getting an almost unlimited number of patterns – but at the cost of finally leaving the realm of the rational. It is hard to imagine how a price move can be predicted by some candle patterns from weeks ago.
Still, a lot effort is going into that. A fellow blogger, Daniel Fernandez, runs a subscription website (Asirikuy) specialized on data mining candle patterns. He refined pattern trading down to the smallest details, and if anyone would ever achieve any profit this way, it would be him. But to his subscribers’ disappointment, trading his patterns live (QuriQuant) produced very different results than his wonderful backtests. If profitable price action systems really exist, apparently no one has found them yet.
3. Linear regression.
The simple basis of many complex machine learning algorithms: Predict the target variable y by a linear combination of the predictors x 1 .. x n .
The coefficients a n are the model. They are calculated for minimizing the sum of squared differences between the true y values from the training samples and their predicted y from the above formula:
For normal distributed samples, the minimizing is possible with some matrix arithmetic, so no iterations are required. In the case n = 1 – with only one predictor variable x – the regression formula is reduced to.
which is simple linear regression , as opposed to multivariate linear regression where n > 1. Simple linear regression is available in most trading platforms, f. i. with the LinReg indicator in the TA-Lib. With y = price and x = time it’s often used as an alternative to a moving average. Multivariate linear regression is available in the R platform through the lm(..) function that comes with the standard installation. A variant is polynomial regression . Like simple regression it uses only one predictor variable x , but also its square and higher degrees, so that x n == x n :
With n = 2 or n = 3 , polynomial regression is often used to predict the next average price from the smoothed prices of the last bars. The polyfit function of MatLab, R, Zorro, and many other platforms can be used for polynomial regression.
4. Perceptron.
Often referred to as a neural network with only one neuron. In fact a perceptron is a regression function like above, but with a binary result, thus called logistic regression . It’s not regression though, it’s a classification algorithm. Zorro’s advise(PERCEPTRON, …) function generates C code that returns either 100 or -100, dependent on whether the predicted result is above a threshold or not:
You can see that the sig array is equivalent to the features x n in the regression formula, and the numeric factors are the coefficients a n .
5. N eural networks.
Linear or logistic regression can only solve linear problems. Many do not fall into this category – a famous example is predicting the output of a simple XOR function. And most likely also predicting prices or trade returns. An artificial neural network (ANN) can tackle nonlinear problems. It’s a bunch of perceptrons that are connected together in an array of layers . Any perceptron is a neuron of the net. Its output goes to the inputs of all neurons of the next layer, like this:
Like the perceptron, a neural network also learns by determining the coefficients that minimize the error between sample prediction and sample target. But this requires now an approximation process, normally with backpropagating the error from the output to the inputs, optimizing the weights on its way. This process imposes two restrictions. First, the neuron outputs must now be continuously differentiable functions instead of the simple perceptron threshold. Second, the network must not be too deep – it must not have too many ‘hidden layers’ of neurons between inputs and output. This second restriction limits the complexity of problems that a standard neural network can solve.
When using a neural network for predicting trades, you have a lot of parameters with which you can play around and, if you’re not careful, produce a lot of selection bias :
Number of hidden layers Number of neurons per hidden layer Number of backpropagation cycles, named epochs Learning rate, the step width of an epoch Momentum, an inertia factor for the weights adaption Activation function.
The activation function emulates the perceptron threshold. For the backpropagation you need a continuously differentiable function that generates a ‘soft’ step at a certain x value. Normally a sigmoid , tanh , or softmax function is used. Sometimes it’s also a linear function that just returns the weighted sum of all inputs. In this case the network can be used for regression, for predicting a numeric value instead of a binary outcome.
Neural networks are available in the standard R installation ( nnet , a single hidden layer network) and in many packages, for instance RSNNS and FCNN4R .
6. Deep learning.
Deep learning methods use neural networks with many hidden layers and thousands of neurons, which could not be effectively trained anymore by conventional backpropagation. Several methods became popular in the last years for training such huge networks. They usually pre-train the hidden neuron layers for achieving a more effective learning process. A Restricted Boltzmann Machine ( RBM ) is an unsupervised classification algorithm with a special network structure that has no connections between the hidden neurons. A Sparse Autoencoder ( SAE ) uses a conventional network structure, but pre-trains the hidden layers in a clever way by reproducing the input signals on the layer outputs with as few active connections as possible. Those methods allow very complex networks for tackling very complex learning tasks. Such as beating the world’s best human Go player.
Deep learning networks are available in the deepnet and darch R packages. Deepnet provides an autoencoder, Darch a restricted Boltzmann machine. I have not yet experimented with Darch, but here’s an example R script using the Deepnet autoencoder with 3 hidden layers for trade signals through Zorro’s neural() function:
7. Support vector machines.
Like a neural network, a support vector machine (SVM) is another extension of linear regression. When we look at the regression formula again,
we can interpret the features x n as coordinates of a n - dimensional feature space . Setting the target variable y to a fixed value determines a plane in that space, called a hyperplane since it has more than two (in fact, n-1 ) dimensions. The hyperplane separates the samples with y > o from the samples with y < 0. The a n coefficients can be calculated in a way that the distances of the plane to the nearest samples – which are called the ‘support vectors’ of the plane, hence the algorithm name – is maximum. This way we have a binary classifier with optimal separation of winning and losing samples.
The problem: normally those samples are not linearly separable – they are scattered around irregularly in the feature space. No flat plane can be squeezed between winners and losers. If it could, we had simpler methods to calculate that plane, f. i. linear discriminant analysis . But for the common case we need the SVM trick: Adding more dimensions to the feature space. For this the SVM algorithm produces more features with a kernel function that combines any two existing predictors to a new feature. This is analogous to the step above from the simple regression to polynomial regression, where also more features are added by taking the sole predictor to the n-th power. The more dimensions you add, the easier it is to separate the samples with a flat hyperplane. This plane is then transformed back to the original n-dimensional space, getting wrinkled and crumpled on the way. By clever selecting the kernel function, the process can be performed without actually computing the transformation.
Like neural networks, SVMs can be used not only for classification, but also for regression. They also offer some parameters for optimizing and possibly overfitting the prediction process:
Kernel function. You normally use a RBF kernel (radial basis function, a symmetric kernel), but you also have the choice of other kernels, such as sigmoid, polynomial, and linear. Gamma, the width of the RBF kernel Cost parameter C, the ‘penalty’ for wrong classifications in the training samples.
An often used SVM is the libsvm library. It’s also available in R in the e1071 package. In the next and final part of this series I plan to describe a trading strategy using this SVM.
8. K-Nearest neighbor.
Compared with the heavy ANN and SVM stuff, that’s a nice simple algorithm with a unique property: It needs no training. So the samples are the model. You could use this algorithm for a trading system that learns permanently by simply adding more and more samples. The nearest neighbor algorithm computes the distances in feature space from the current feature values to the k nearest samples. A distance in n-dimensional space between two feature sets (x 1 .. x n ) and (y 1 .. y n ) is calculated just as in 2 dimensions:
The algorithm simply predicts the target from the average of the k target variables of the nearest samples, weighted by their inverse distances. It can be used for classification as well as for regression. Software tricks borrowed from computer graphics, such as an adaptive binary tree (ABT), can make the nearest neighbor search pretty fast. In my past life as computer game programmer, we used such methods in games for tasks like self-learning enemy intelligence. You can call the knn function in R for nearest neighbor prediction – or write a simple function in C for that purpose.
This is an approximation algorithm for unsupervised classification. It has some similarity, not only its name, to k-nearest neighbor. For classifying the samples, the algorithm first places k random points in the feature space. Then it assigns to any of those points all the samples with the smallest distances to it. The point is then moved to the mean of these nearest samples. This will generate a new samples assignment, since some samples are now closer to another point. The process is repeated until the assignment does not change anymore by moving the points, i. e. each point lies exactly at the mean of its nearest samples. We now have k classes of samples, each in the neighborhood of one of the k points.
This simple algorithm can produce surprisingly good results. In R, the kmeans function does the trick. An example of the k-means algorithm for classifying candle patterns can be found here: Unsupervised candlestick classification for fun and profit.
10. Naive Bayes.
This algorithm uses Bayes’ Theorem for classifying samples of non-numeric features (i. e. events ), such as the above mentioned candle patterns . Suppose that an event X (for instance, that the Open of the previous bar is below the Open of the current bar) appears in 80% of all winning samples. What is then the probability that a sample is winning when it contains event X ? It’s not 0.8 as you might think. The probability can be calculated with Bayes’ Theorem:
P(Y|X) is the probability that event Y (f. i. winning) occurs in all samples containing event X (in our example, Open(1) < Open(0) ). According to the formula, it is equal to the probability of X occurring in all winning samples (here, 0.8), multiplied by the probability of Y in all samples (around 0.5 when you were following my above advice of balanced samples) and divided by the probability of X in all samples.
If we are naive and assume that all events X are independent of each other, we can calculate the overall probability that a sample is winning by simply multiplying the probabilities P (X|winning) for every event X . This way we end up with this formula:
with a scaling factor s . For the formula to work, the features should be selected in a way that they are as independent as possible, which imposes an obstacle for using Naive Bayes in trading. For instance, the two events Close(1) < Close(0) and Open(1) < Open(0) are most likely not independent of each other. Numerical predictors can be converted to events by dividing the number into separate ranges.
The Naive Bayes algorithm is available in the ubiquitous e1071 R package.
11. Decision and regression trees.
Those trees predict an outcome or a numeric value based on a series of yes/no decisions, in a structure like the branches of a tree. Any decision is either the presence of an event or not (in case of non-numerical features) or a comparison of a feature value with a fixed threshold. A typical tree function, generated by Zorro’s tree builder, looks like this:
How is such a tree produced from a set of samples? There are several methods; Zorro uses the Shannon i nformation entropy , which already had an appearance on this blog in the Scalping article. At first it checks one of the features, let’s say x 1 . It places a hyperplane with the plane formula x 1 = t into the feature space. This hyperplane separates the samples with x 1 > t from the samples with x 1 < t . The dividing threshold t is selected so that the information gain – the difference of information entropy of the whole space, to the sum of information entropies of the two divided sub-spaces – is maximum. This is the case when the samples in the subspaces are more similar to each other than the samples in the whole space.
This process is then repeated with the next feature x 2 and two hyperplanes splitting the two subspaces. Each split is equivalent to a comparison of a feature with a threshold. By repeated splitting, we soon get a huge tree with thousands of threshold comparisons. Then the process is run backwards by pruning the tree and removing all decisions that do not lead to substantial information gain. Finally we end up with a relatively small tree as in the code above.
Decision trees have a wide range of applications. They can produce excellent predictions superior to those of neural networks or support vector machines. But they are not a one-fits-all solution, since their splitting planes are always parallel to the axes of the feature space. This somewhat limits their predictions. They can be used not only for classification, but also for regression, for instance by returning the percentage of samples contributing to a certain branch of the tree. Zorro’s tree is a regression tree. The best known classification tree algorithm is C5.0 , available in the C50 package for R.
For improving the prediction even further or overcoming the parallel-axis-limitation, an ensemble of trees can be used, called a random forest . The prediction is then generated by averaging or voting the predictions from the single trees. Random forests are available in R packages randomForest , ranger and Rborist .
Conclusão.
There are many different data mining and machine learning methods at your disposal. The critical question: what is better, a model-based or a machine learning strategy? There is no doubt that machine learning has a lot of advantages. You don’t need to care about market microstructure, economy, trader psychology, or similar soft stuff. You can concentrate on pure mathematics. Machine learning is a much more elegant, more attractive way to generate trade systems. It has all advantages on its side but one. Despite all the enthusiastic threads on trader forums, it tends to mysteriously fail in live trading.
Every second week a new paper about trading with machine learning methods is published (a few can be found below). Please take all those publications with a grain of salt. According to some papers, phantastic win rates in the range of 70%, 80%, or even 85% have been achieved. Although win rate is not the only relevant criterion – you can lose even with a high win rate – 85% accuracy in predicting trades is normally equivalent to a profit factor above 5. With such a system the involved scientists should be billionaires meanwhile. Unfortunately I never managed to reproduce those win rates with the described method, and didn’t even come close. So maybe a lot of selection bias went into the results. Or maybe I’m just too stupid.
Compared with model based strategies, I’ve seen not many successful machine learning systems so far. And from what one hears about the algorithmic methods by successful hedge funds, machine learning seems still rarely to be used. But maybe this will change in the future with the availability of more processing power and the upcoming of new algorithms for deep learning.
Classification using deep neural networks: Dixon. et. al.2018 Predicting price direction using ANN & SVM: Kara. et. al.2018 Empirical comparison of learning algorithms: Caruana. et. al.2006 Mining stock market tendency using GA & SVM: Yu. Wang. Lai.2005.
The next part of this series will deal with the practical development of a machine learning strategy.
30 thoughts on “Better Strategies 4: Machine Learning”
Bela postagem. There is a lot of potential in these approach towards the market.
Btw are you using the code editor which comes with zorro? how is it possible to get such a colour configuration?
The colorful script is produced by WordPress. You can’t change the colors in the Zorro editor, but you can replace it with other editors that support individual colors, for instance Notepad++.
Is it then possible that notepad detects the zorro variables in the scripts? I mean that BarPeriod is remarked as it is with the zorro editor?
Theoretically yes, but for this you had to configure the syntax highlighting of Notepad++, and enter all variables in the list. As far as I know Notepad++ can also not be configured to display the function description in a window, as the Zorro editor does. There’s no perfect tool…
Concur with the final paragraph. I have tried many machine learning techniques after reading various ‘peer reviewed’ papers. But reproducing their results remains elusive. When I live test with ML I can’t seem to outperform random entry.
ML fails in live? Maybe the training of the ML has to be done with price data that include as well historical spread, roll, tick and so on?
I think reason #1 for live failure is data mining bias, caused by biased selection of inputs and parameters to the algo.
Thanks to the author for the great series of articles.
However, it should be noted that we don’t need to narrow our view with predicting only the next price move. It may happen that the next move goes against our trade in 70% of cases but it still worth making a trade. This happens when the price finally does go to the right direction but before that it may make some steps against us. If we delay the trade by one price step we will not enter the mentioned 30% of trades but for that we will increase the result of the remained 70% by one price step. So the criteria is which value is higher: N*average_result or 0.7*N*(avergae_result + price_step).
Bela postagem. If you just want to play around with some machine learning, I implemented a very simple ML tool in python and added a GUI. It’s implemented to predict time series.
Thanks JCL I found very interesting your article. I would like to ask you, from your expertise in trading, where can we download reliable historical forex data? I consider it very important due to the fact that Forex market is decentralized.
Desde já, obrigado!
There is no really reliable Forex data, since every Forex broker creates their own data. They all differ slightly dependent on which liquidity providers they use. FXCM has relatively good M1 and tick data with few gaps. You can download it with Zorro.
Thanks for writing such a great article series JCL… a thoroughly enjoyable read!
I have to say though that I don’t view model-based and machine learning strategies as being mutually exclusive; I have had some OOS success by using a combination of the elements you describe.
To be more exact, I begin the system generation process by developing a ‘traditional’ mathematical model, but then use a set of online machine learning algorithms to predict the next terms of the various different time series (not the price itself) that are used within the model. The actual trading rules are then derived from the interactions between these time series. So in essence I am not just blindly throwing recent market data into an ML model in an effort to predict price action direction, but instead develop a framework based upon sound investment principles in order to point the models in the right direction. I then data mine the parameters and measure the level of data-mining bias as you’ve described also.
It’s worth mentioning however that I’ve never had much success with Forex.
Anyway, best of luck with your trading and keep up the great articles!
Obrigado por publicar esta ótima série mini JCL.
I recently studied a few latest papers about ML trading, deep learning especially. Yet I found that most of them valuated the results without risk-adjusted index, i. e., they usually used ROC curve, PNL to support their experiment instead of Sharpe Ratio, for example.
Also, they seldom mentioned about the trading frequency in their experiment results, making it hard to valuate the potential profitability of those methods. Por que é que? Do you have any good suggestions to deal with those issues?
ML papers normally aim for high accuracy. Equity curve variance is of no interest. This is sort of justified because the ML prediction quality determines accuracy, not variance.
Of course, if you want to really trade such a system, variance and drawdown are important factors. A system with lower accuracy and worse prediction can in fact be preferable when it’s less dependent on market condictions.
“In fact the most popular – and surprisingly profitable – data mining method works without any fancy neural networks or support vector machines.”
Would you please name those most popular & surprisingly profitable ones. So I could directly use them.
I was referring to the Indicator Soup strategies. For obvious reasons I can’t disclose details of such a strategy, and have never developed such systems myself. We’re merely coding them. But I can tell that coming up with a profitable Indicator Soup requires a lot of work and time.
Well, i am just starting a project which use simple EMAs to predict price, it just select the correct EMAs based on past performance and algorithm selection that make some rustic degree of intelligence.
Jonathan. orrego@gmail offers services as MT4 EA programmer.
Thanks for the good writeup. It in reality used to be a leisure account it.
Look complicated to more delivered agreeable from you!
By the way, how could we be in contact?
There are following issues with ML and with trading systems in general which are based on historical data analysis:
1) Historical data doesn’t encode information about future price movements.
Future price movement is independent and not related to the price history. There is absolutely no reliable pattern which can be used to systematically extract profits from the market. Applying ML methods in this domain is simply pointless and doomed to failure and is not going to work if you search for a profitable system. Of course you can curve fit any past period and come up with a profitable system for it.
The only thing which determines price movement is demand and supply and these are often the result of external factors which cannot be predicted. For example: a war breaks out somewhere or other major disaster strikes or someone just needs to buy a large amount of a foreign currency for some business/investment purpose. These sort of events will cause significant shifts in the demand supply structure of the FX market . As a consequence, prices begin to move but nobody really cares about price history just about the execution of the incoming orders. An automated trading system can only be profitable if it monitors a significant portion of the market and takes the supply and demand into account for making a trading decision. But this is not the case with any of the systems being discussed here.
2) Race to the bottom.
Even if (1) wouldn’t be true and there would be valuable information encoded in historical price data, you would still face following problem: there are thousands of gold diggers out there, all of them using similar methods and even the same tools to search for profitable systems and analyze the same historical price data. As a result, many of them will discover the same or very similar “profitable” trading systems and when they begin actually trading those systems, they will become less and less profitable due to the nature of the market.
The only sure winners in this scenario will be the technology and tool vendors.
I will be still keeping an eye on your posts as I like your approach and the scientific vigor you apply. Your blog is the best of its kind – keep the good work!
One hint: there are profitable automated systems, but they are not based on historical price data but on proprietary knowledge about the market structure and operations of the major institutions which control these markets. Let’s say there are many inefficiencies in the current system but you absolutely have no chance to find the information about those by analyzing historical price data. Instead you have to know when and how the institutions will execute market moving orders and front run them.
Thanks for the extensive comment. I often hear these arguments and they sound indeed intuitive, only problem is that they are easily proven wrong. The scientific way is experiment, not intuition. Simple tests show that past and future prices are often correlated – otherwise every second experiment on this blog had a very different outcome. Many successful funds, for instance Jim Simon’s Renaissance fund, are mainly based on algorithmic prediction.
One more thing: in my comment I have been implicitly referring to the buy side (hedge funds, traders etc) not to the sell side (market makers, banks). The second one has always the edge because they sell at the ask and buy at the bid, pocketing the spread as an additional profit to any strategy they might be running. Regarding Jim Simon’s Renaissance: I am not so sure if they have not transitioned over the time to the sell side in order to stay profitable. There is absolutely no information available about the nature of their business besides the vague statement that they are using solely quantitative algorithmic trading models…
Thanks for the informative post!
Regarding the use of some of these algorithms, a common complaint which is cited is that financial data is non-stationary…Do you find this to be a problem? Couldn’t one just use returns data instead which is (I think) stationary?
Yes, this is a problem for sure. If financial data were stationary, we’d all be rich. I’m afraid we have to live with what it is. Returns are not any more stationary than other financial data.
Hello sir, I developed some set of rules for my trading which identifies supply demand zones than volume and all other criteria. Can you help me to make it into automated system ?? If i am gonna do that myself then it can take too much time. Please contact me at svadukia@gmail if you are interested.
Sure, please contact my employer at info@opgroup. de. They’ll help.
I have noticed you don’t monetize your page, don’t waste your traffic,
you can earn extra bucks every month because you’ve got high quality content.
If you want to know how to make extra $$$, search for: Mrdalekjd methods for $$$
Technical analysis has always been rejected and looked down upon by quants, academics, or anyone who has been trained by traditional finance theories. I have worked for proprietary trading desk of a first tier bank for a good part of my career, and surrounded by those ivy-league elites with background in finance, math, or financial engineering. I must admit none of those guys knew how to trade directions. They were good at market making, product structures, index arb, but almost none can making money trading directions. Por quê? Because none of these guys believed in technical analysis. Then again, if you are already making your millions why bother taking the risk of trading direction with your own money. For me luckily my years of training in technical analysis allowed me to really retire after laying off from the great recession. I look only at EMA, slow stochastics, and MACD; and I have made money every year since started in 2009. Technical analysis works, you just have to know how to use it!!
Sistemas de negociação de aprendizado de máquina.
The SPDR S&P 500 ETF (SPY) is one of the widely traded ETF products on the market, with around $200Bn in assets and average turnover of just under 200M shares daily. So the likelihood of being able to develop a money-making trading system using publicly available information might appear to be slim-to-none. So, to give ourselves a fighting chance, we will focus on an attempt to predict the overnight movement in SPY, using data from the prior day’s session.
In addition to the open/high/low and close prices of the preceding day session, we have selected a number of other plausible variables to build out the feature vector we are going to use in our machine learning model:
The daily volume The previous day’s closing price The 200-day, 50-day and 10-day moving averages of the closing price The 252-day high and low prices of the SPY series.
We will attempt to build a model that forecasts the overnight return in the ETF, i. e. [O(t+1)-C(t)] / C(t)
In this exercise we use daily data from the beginning of the SPY series up until the end of 2018 to build the model, which we will then test on out-of-sample data running from Jan 2018-Aug 2018. In a high frequency context a considerable amount of time would be spent evaluating, cleaning and normalizing the data. Here we face far fewer problems of that kind. Typically one would standardized the input data to equalize the influence of variables that may be measured on scales of very different orders of magnitude. But in this example all of the input variables, with the exception of volume, are measured on the same scale and so standardization is arguably unnecessary.
First, the in-sample data is loaded and used to create a training set of rules that map the feature vector to the variable of interest, the overnight return:
In Mathematica 10 Wolfram introduced a suite of machine learning algorithms that include regression, nearest neighbor, neural networks and random forests, together with functionality to evaluate and select the best performing machine learning technique. These facilities make it very straightfoward to create a classifier or prediction model using machine learning algorithms, such as this handwriting recognition example:
We create a predictive model on the SPY trainingset, allowing Mathematica to pick the best machine learning algorithm:
There are a number of options for the Predict function that can be used to control the feature selection, algorithm type, performance type and goal, rather than simply accepting the defaults, as we have done here:
Having built our machine learning model, we load the out-of-sample data from Jan 2018 to Aug 2018, and create a test set:
We next create a PredictionMeasurement object, using the Nearest Neighbor model , that can be used for further analysis:
There isn’t much dispersion in the model forecasts, which all have positive value. A common technique in such cases is to subtract the mean from each of the forecasts (and we may also standardize them by dividing by the standard deviation).
The scatterplot of actual vs. forecast overnight returns in SPY now looks like this:
There’s still an obvious lack of dispersion in the forecast values, compared to the actual overnight returns, which we could rectify by standardization. In any event, there appears to be a small, nonlinear relationship between forecast and actual values, which holds out some hope that the model may yet prove useful.
From Forecasting to Trading.
There are various methods of deploying a forecasting model in the context of creating a trading system. The simplest route, which we will take here, is to apply a threshold gate and convert the filtered forecasts directly into a trading signal. But other approaches are possible, for example:
Combining the forecasts from multiple models to create a prediction ensemble Using the forecasts as inputs to a genetic programming model Feeding the forecasts into the input layer of a neural network model designed specifically to generate trading signals, rather than forecasts.
In this example we will create a trading model by applying a simple filter to the forecasts, picking out only those values that exceed a specified threshold. This is a standard trick used to isolate the signal in the model from the background noise. We will accept only the positive signals that exceed the threshold level, creating a long-only trading system. i. e. we ignore forecasts that fall below the threshold level. We buy SPY at the close when the forecast exceeds the threshold and exit any long position at the next day’s open. This strategy produces the following pro-forma results:
Conclusão.
The system has some quite attractive features, including a win rate of over 66% and a CAGR of over 10% for the out-of-sample period.
Obviously, this is a very basic illustration: we would want to factor in trading commissions, and the slippage incurred entering and exiting positions in the post - and pre-market periods, which will negatively impact performance, of course. On the other hand, we have barely begun to scratch the surface in terms of the variables that could be considered for inclusion in the feature vector, and which may increase the explanatory power of the model.
In other words, in reality, this is only the beginning of a lengthy and arduous research process. Nonetheless, this simple example should be enough to give the reader a taste of what’s involved in building a predictive trading model using machine learning algorithms.
Artigos relacionados.
Protected: The Systematic Strategies Quantitative Equity Strategy.
Futures WealthBuilder.
Can Machine Learning Techniques Be Used To Predict Market Direction? The 1,000,000 Model Test.
1 comentário. Deixe o novo.
[…] Machine Learning Trading Systems [Jonathan Kinlay] The SPDR S&P 500 ETF (SPY) is one of the widely traded ETF products on the market, with around $200Bn in assets and average turnover of just under 200M shares daily. So the likelihood of being able to develop a money-making trading system using publicly available information might appear to be slim-to-none. So, to give ourselves a fighting chance, we will focus on an attempt to predict the […]
Application of Machine Learning Techniques to Trading.
Auquan recently concluded another version of QuantQuest, and this time, we had a lot of people attempt Machine Learning with our problems. It was good learning for both us and them (hopefully!). This post is inspired by our observations of some common caveats and pitfalls during the competition when trying to apply ML techniques to trading problems.
Creating a Trade Strategy.
The final output of a trading strategy should answer the following questions:
DIRECTION: identify if an asset is cheap/expensive/fair value ENTRY TRADE: if an asset is cheap/expensive, should you buy/sell it EXIT TRADE: if an asset is fair priced and if we hold a position in that asset(bought or sold it earlier), should you exit that position PRICE RANGE: which price (or range) to make this trade at QUANTITY: Amount of capital to trade(example shares of a stock)
Machine Learning can be used to answer each of these questions, but for the rest of this post, we will focus on answering the first, Direction of trade.
Strategy Approach.
There can be two types of approaches to building strategies, model based or data mining. These are essentially opposite approaches. In model-based strategy building , we start with a model of a market inefficiency, construct a mathematical representation(eg price, returns) and test it’s validity in the long term. This model is usually a simplified representation of the true complex model and it’s long term significance and stability need to verified. Common trend-following, mean reversion, arbitrage strategies fall in this category.
On the other hand, we first look for price patterns and attempt to fit an algorithm to it in data mining approach . What causes these patterns is not important, only that patterns identified will continue to repeat in the future. This is a blind approach and we need rigorous checks to identify real patterns from random patterns. Trial-and-error TA, candle patterns, regression on a large number of features fall in this category.
Clearly, Machine Learning lends itself easily to data mining approach. Let’s look into how we can use ML to create a trade signal by data mining.
You can follow along the steps in this model using this IPython notebook . The code samples use Auquan’s python based free and open source toolbox. You can install it via pip: ` pip install - U auquan_toolbox` . We use scikit learn for ML models. Install it using `pip install - U scikit-learn`.
Using ML to create a Trading Strategy Signal — Data Mining.
Before we begin, a sample ML problem setup looks like below.
We create features which could have some predictive power (X), a target variable that we’d like to predict(Y) and use historical data to train a ML model that can predict Y as close as possible to the actual value. Finally, we use this model to make predictions on new data where Y is unknown. This leads to our first step:
Step 1 — Setup your problem.
In our framework above, what is Y?
Are you predicting Price at a future time, future Return/Pnl, Buy/Sell Signal, Optimizing Portfolio Allocation, try Efficient Execution etc?
Let’s say we’re trying to predict price at the next time stamp. In that case, Y(t) = Price(t+1). Now we can complete our framework with historical data.
Note Y(t) will only be known during a backtest, but when using our model live, we won’t know Price(t+1) at time t. We make a prediction Y(Predicted, t) using our model and compare it with actual value only at time t+1. This means you cannot use Y as a feature in your predictive model.
Once we know our target, Y, we can also decide how to evaluate our predictions. This is important to distinguish between different models we will try on our data. Choose a metric that is a good indicator of our model efficiency based on the problem we are solving. For example, if we are predicting price, we can use the Root Mean Square Error as a metric. Some common metrics(RMSE, logloss, variance score etc) are pre-coded in Auquan’s toolbox and available under features.
F or demonstration, we’re going to use a problem from QuantQuest(Problem 1). We are going to create a prediction model that predicts future expected value of basis, where:
basis = Price of Stock — Price of Future basis(t)=S(t)−F(t) Y(t) = future expected value of basis = Average(basis(t+1),basis(t+2),basis(t+3),basis(t+4),basis(t+5))
Since this is a regression problem, we will evaluate the model on RMSE. We’ll also use Total Pnl as an evaluation criterion.
Our Objective: Create a model so that predicted value is as close as possible to Y.
Step 2: Collect Reliable Data.
You need to think about what data will have predictive power for the target variable Y? If we were predicting Price, you could use Stock Price Data, Stock Trade Volume Data, Fundamental Data, Price and Volume Data of Correlated stocks, an Overall Market indicator like Stock Index Level, Price of other correlated assets etc.
You will need to setup data access for this data, and make sure your data is accurate, free of errors and solve for missing data(quite common). Also ensure your data is unbiased and adequately represents all market conditions (example equal number of winning and losing scenarios) to avoid bias in your model. You may also need to clean your data for dividends, stock splits, rolls etc.
If you’re using Auquan’s Toolbox, we provide access to free data from Google, Yahoo, NSE and Quandl. We also pre-clean the data for dividends, stock splits and rolls and load it in a format that rest of the toolbox understands.
F or our demo problem, we are using the following data for a dummy stock ‘MQK’ at minute intervals for trading days over one month(
8000 data points): Stock Bid Price, Ask Price, Bid Volume, Ask Volume Future Bid Price, Ask Price, Bid Volume, Ask Volume, StockVWAP, Future VWAP. This data is already cleaned for Dividends, Splits, Rolls.
Auquan’s Toolbox has downloaded and loaded the data into a dictionary of dataframes for you. We now need to prepare the data in a format we like. The function ds. getBookDataByFeature() returns a dictionary of dataframes, one dataframe per feature. We create a new data dataframe for the stock with all the features.
Step 3: Split Data.
This is an extremely important step! Before we proceed any further, we should split our data into training data to train your model and test data to evaluate model performance. Recommended split: 60–70% training and 30–40% test.
Since training data is used to evaluate model parameters, your model will likely be overfit to training data and training data metrics will be misleading about model performance. If you do not keep any separate test data and use all your data to train, you will not know how well or badly your model performs on new unseen data. This is one of the major reasons why well trained ML models fail on live data — people train on all available data and get excited by training data metrics, but the model fails to make any meaningful predictions on live data that it wasn’t trained on.
There is a problem with this method. If we repeatedly train on training data, evaluate performance on test data and optimise our model till we are happy with performance we have implicitly made test data a part of training data. Eventually our model may perform well for this set of training and test data, but there is no guarantee that it will predict well on new data.
To solve for this we can create a separate validation data set. Now you can train on training data, evaluate performance on validation data, optimise till you are happy with performance, and finally test on test data. This way the test data stays untainted and we don’t use any information from test data to improve our model.
Remember once you do check performance on test data don’t go back and try to optimise your model further. If you find that your model does not give good results discard that model altogether and start fresh. Recommended split could be 60% training data, 20% validation data and 20% test data.
F or our problem we have three datasets available, we will use one as training set, second as validation set and the third as our test set.
To each of these, we add the target variable Y, defined as average of next five values of basis.
Etapa 4: engenharia de recursos.
Now comes the real engineering. The golden rule of feature selection is that the predictive power should come from primarily from the features and not from the model. You will find that the choice of features has a far greater impact on performance than the choice of model. Some pointers for feature selection:
Don’t randomly choose a very large set of features without exploring relationship with target variable Little or no relationship with target variable will likely lead to overfitting Your features might be highly correlated with each other, in that case a fewer number of features will explain the target just as well I generally create a few features that make intuitive sense, look at correlation of target variable with those features, as well as their inter correlation to decide what to use You could also try ranking candidate features according to Maximal Information Coefficient (MIC), performing Principal Component Analysis(PCA) and other methods.
Feature Transformation/Normalization:
ML models tend to perform well with normalization. However, normalization is tricky when working with time series data because future range of data is unknown. Your data could fall out of bounds of your normalization leading to model errors. Still you could try to enforce some degree of stationarity:
Scaling: divide features by standard deviation or interquartile range Centering: subtract historical mean from current value Normalization: both of the above (x — mean)/stdev over lookback period Regular normalization: standardize data to the range -1 to +1 over lookback period (x-min)/(max-min) and re-center.
Note since we are using historical rolling mean, standard deviation, max or min over lookback period, the same normalized value of feature will mean different actual value at different times. For example, if the current value of feature is 5 with a rolling 30-period mean of 4.5, this will transform to 0.5 after centering. Later if the rolling 30-period mean changes to 3, a value of 3.5 will transform to 0.5. This may be a cause of errors in your model; hence normalization is tricky and you have to figure what actually improves performance of your model(if at all).
If you are using our toolbox, it already comes with a set of pre coded features for you to explore.
F or this first iteration in our problem, we create a large number of features, using a mix of parameters. Later we will try to see if can reduce the number of features.
Passo 5: Seleção do modelo.
The choice of model will depend on the way the problem is framed. Are you solving a supervised (every point X in feature matrix maps to a target variable Y ) or unsupervised learning problem(there is no given mapping, model tries to learn unknown patterns)? Are you solving a regression (predict the actual price at a future time) or a classification problem (predict only the direction of price(increase/decrease) at a future time).
Some common supervised learning algorithms to get you started are:
I recommend starting with a simple model, for example linear or logistic regression and building up to more sophisticated models from there if needed. Also recommend reading the Math behind the model instead of blindly using it as a black box.
Step 6: Train, Validate and Optimize (Repeat steps 4–6)
Now you’re ready to finally build your model. At this stage, you really just iterate over models and model parameters. Train your model on training data, measure it’s performance on validation data, and go back, optimize, re-train and evaluate again. If you’re unhappy with a model’s performance, try using a different model. You loop over this stage multiple times till you finally have a model that you’re happy with.
Only when you have a model who’s performance you like, proceed to the next step.
For our demo problem, let’s start with a simple linear regression.
Look at the model coeffecients. We can’t really compare them or tell which ones are important since they all belong to different scale. Let’s try normalization to conform them to same scale and also enforce some stationarity.
The model doesn’t improve on the previous model, but it’s not much worse either. And now we can actually compare coefficients to see which ones are actually important.
Let’s look at the coefficients.
We can clearly see that some features have a much higher coeffecient compared to others, and probably have more predictive power.
Let’s also look at correlation between different features.
The areas of dark red indicate highly correlated variables. Let’s create/modify some features again and try to improve our model.
For example, I can easily discard features like emabasisdi7 that are just a linear combination of other features.
See, our model performance does not change, and we only need a few features to explain our target variable. I recommend playing with more features above, trying new combinations etc to see what can improve our model.
We can also try more sophisticated models to see if change of model may improve performance.
K Nearest Neighbours.
Decision Trees.
Passo 7: Backtest em dados de teste.
This is the moment of truth. We run our final, optimized model from last step on that Test Data that we had kept aside at the start and did not touch yet.
This provides you with realistic expectation of how your model is expected to perform on new and unseen data when you start trading live. Hence, it is necessary to ensure you have a clean dataset that you haven’t used to train or validate your model.
If you don’t like the results of your backtest on test data, discard the model and start again. DO NOT go back and re-optimize your model, this will lead to over fitting! (Also recommend to create a new test data set, since this one is now tainted; in discarding a model, we implicitly know something about the dataset).
F or backtesting, we use Auquan’s Toolbox.
Step 8: Other ways to improve model.
Besides collecting more data, creating better features or trying more models, there’s a few things you can try to train your model better.
1. Rolling Validation.
Market conditions rarely stay same. Let’s say you have data for a year and you use Jan-August to train and Sep-Dec to test your model, you might end up training over a very specific set of market conditions. Maybe there was no market volatility for first half of the year and some extreme news caused markets to move a lot in September, your model will not learn this pattern and give you junk results.
It might be better to try a walk forward rolling validation — train over Jan-Feb, validate over March, re-train over Apr-May, validate over June and so on.
2. Ensemble Learning.
Some models may work well in prediction certain scenarios and other in prediction other scenarios. Or a model may be extremely overfitting in a certain scenario. One way of reducing error and overfitting both is to use an ensemble of different model. Your prediction is the average of predictions made by many model, with errors from different models likely getting cancelled out or reduced. Some common ensemble methods are Bagging and Boosting.
To keep this post short, I will skip these methods, but you can read more about them here.
Let’s try an ensemble method for our problem.
Variance score: 0.95.
All the code for the above steps is available in this IPython notebook. You can read more below:
That was quite a lot of information. Let’s do a quick Recap:
Frame your problem Collect reliable Data and clean Data Split Data into Training, Validation and Test sets Create Features and Analyze Behavior Choose an appropriate training model based on Behavior Use Training Data to train your model to make predictions Check performance on validation set and re-optimize Verify final performance on Test Set.
Phew! But that’s not it. You only have a solid prediction model now. Remember what we actually wanted from our strategy? You still have to:
Develop Signal to identify trade direction based on prediction model Develop Strategy to identify Entry/Exit Points Execution System to identify Sizing and Price.
And then you can finally send this order to your broker, and make your automated trade!
Important Note on Transaction Costs : Why are the next steps important? Your model tells you when your chosen asset is a buy or sell. It however doesn’t take into account fees/transaction costs/available trading volumes/stops etc. Transaction costs very often turn profitable trades into losers. For example, an asset with an expected $0.05 increase in price is a buy, but if you have to pay $0.10 to make this trade, you will end up with a net loss of -$0.05. Our own great looking profit chart above actually looks like this after you account for broker commissions, exchange fees and spreads:
Transaction fees and spreads take up more than 90% of our Pnl! We will discuss these in detail in a follow-up post.
Finally, let’s look at some common pitfalls.
DO’s and DONT’s.
AVOID OVERFITTING AT ALL COSTS! Don’t retrain after every datapoint: This was a common mistake people made in QuantQuest. If your model needs re-training after every datapoint, it’s probably not a very good model. That said, it will need to be retrained periodically, just at a reasonable frequency (example retraining at the end of every week if making intraday predictions) Avoid biases, especially lookahead bias: This is another reason why models don’t work — Make sure you are not using any information from the future. Mostly this means, don’t use the target variable, Y as a feature in your model. This is available to you during a backtest but won’t be available when you run your model live, making your model useless. Be wary of data mining bias: Since we are trying a bunch of models on our data to see if anything fits, without an inherent reason behind it fits, make sure you run rigorous tests to separate random patterns from real patterns which are likely to occur in the future. For example what might seem like an upward trending pattern explained well by a linear regression may turn out to be a small part of a larger random walk!
Evite a superposição.
This is so important, I feel the need to mention it again.
Overfitting is the most dangerous pitfall of a trading strategy A complex algorithm may perform wonderfully on a backtest but fails miserably on new unseen data — this algorithm has not really uncovered any trend in data and no real predictive power. It is just fit very well to the data it has seen Keep your systems as simple as possible. If you find yourself needing a large number of complex features to explain your data, you are likely over fitting Divide your available data into training and test data and always validate performance on Real Out of Sample data before using your model to trade live.
Webinar Video : If you prefer listening to reading and would like to see a video version of this post, you can watch this webinar link instead.
Ao bater palmas mais ou menos, você pode nos indicar quais são as histórias que realmente se destacam.
Equipe Auquan.
A Auquan pretende envolver pessoas de diversas origens para aplicar as habilidades de seus respectivos campos para desenvolver estratégias de negociação de alta qualidade. Acreditamos que pessoas extremamente talentosas equipadas com conhecimento e atitude adequados podem projetar algoritmos de negociação bem-sucedidos.
No comments:
Post a Comment