Tuesday, 3 April 2018

Aprendizado de máquina em estratégias de negociação


Aprendizado de Máquina para Negociação & # 8211; Visão geral.


Inteligência Artificial (IA) e Aprendizado de Máquina (ML) estão silenciosamente revolucionando quase todas as áreas de nossas vidas. Você sabia que o Machine Learning para negociação está ficando cada vez mais importante?


Você pode se surpreender ao saber que os fundos de hedge Learning Machine já superam significativamente os fundos de hedge generalizados, bem como os fundos quant tradicionais, de acordo com um relatório da ValueWalk. Os sistemas ML e AI podem ser ferramentas incrivelmente úteis para os seres humanos que navegam no processo de tomada de decisão envolvido em investimentos e avaliação de risco.


O impacto das emoções humanas nas decisões de negociação é frequentemente o maior obstáculo ao desempenho superior. Algoritmos e computadores tomam decisões e executam negócios com mais rapidez do que qualquer humano, e o fazem livres 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 de negócios, que dividem as negociações em ordens menores para minimizar o impacto no preço das ações. Um exemplo disso é uma estratégia de Preço Médio Ponderado por Volume (VWAP). Algoritmos de implementação de estratégia que fazem negócios com base em sinais de dados de mercado em tempo real. Exemplos disso são as estratégias baseadas em tendências que envolvem médias móveis, interrupções de canais, movimentos de níveis de preços e outros indicadores técnicos. Algoritmos furtivos / de jogos que são voltados para detectar e aproveitar os movimentos de preços causados ​​por grandes negociações e / ou outras estratégias de algoritmo. Oportunidades de arbitragem. Um exemplo seria onde uma ação pode ser negociada em dois mercados separados por dois preços diferentes e a diferença no preço pode ser capturada pela venda de ações com preço mais alto e pela compra de ações com preços mais baixos.


Quando as estratégias de negociação algorítmica foram introduzidas pela primeira vez, elas foram altamente lucrativas e rapidamente ganharam participação de mercado. Em maio de 2017, a Tabb Group, empresa de pesquisa de mercado de capitais, disse que as transações de alta frequência (HFT) representaram 52% do volume médio diário negociado. Mas como a concorrência aumentou, os lucros diminuíram. Neste ambiente cada vez mais difícil, os comerciantes precisam de uma nova ferramenta para lhes dar uma vantagem competitiva e aumentar os lucros. A boa notícia é que a ferramenta está aqui agora: Machine Learning.


O Aprendizado de Máquina envolve a alimentação de amostras de dados de algoritmos, geralmente derivados de preços históricos. As amostras de dados consistem em variáveis ​​chamadas preditores, bem como uma variável de destino, que é o resultado esperado. O algoritmo aprende a usar as variáveis ​​preditoras para prever a variável de destino.


O Aprendizado de Máquina oferece o número de vantagens importantes sobre os programas algorítmicos tradicionais. O processo pode acelerar a busca por estratégias efetivas de negociação algorítmica, automatizando o que geralmente é um processo tedioso e manual. 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 adaptar-se às tendências à medida que se desenvolvem. Se você puder automatizar um processo que outras pessoas estão executando manualmente; você tem uma vantagem competitiva. Se você puder aumentar o número de mercados em que você está, terá mais oportunidades. E no mundo da negociação de soma zero, se você puder se adaptar às mudanças em tempo real enquanto os outros estão parados, sua vantagem se traduzirá em lucros.


Existem várias estratégias que usam o Machine Learning para otimizar algoritmos, incluindo regressões lineares, redes neurais, aprendizado profundo, máquinas de vetores 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 traders a incorporar o ML em suas próprias estratégias de negociação.


Nosso estudo de caso.


Em um de nossos projetos, criamos um sistema inteligente de alocação de ativos que utilizou a teoria do Deep Learning e do Modern Portfolio. A tarefa era implementar uma estratégia de investimento que pudesse se adaptar a mudanças rápidas no ambiente de mercado.


O modelo básico de IA foi responsável por prever retornos de ativos com base em dados históricos. Isso foi conseguido com a implementação de Unidades de Memória de Longo Prazo de Longo Prazo, que são uma sofisticada generalização de uma Rede Neural Recorrente. Essa arquitetura específica pode armazenar informações para vários timesteps, o que é possível por uma célula de memória. Essa propriedade permite que o modelo aprenda padrões temporais longos e complicados em dados. Como resultado, pudemos prever os retornos futuros do ativo, bem como a incerteza de nossas estimativas usando uma nova técnica denominada Dropout Variacional.


A fim de fortalecer nossas previsões, usamos uma riqueza de dados de mercado, como moedas, índices, etc. em nosso modelo, além dos retornos históricos de ativos relevantes. Isso resultou em mais de 400 recursos que usamos para fazer previsões finais. Naturalmente, muitos desses recursos foram correlacionados. Esse problema foi mitigado pela Análise de Componentes Principais (PCA), que reduz a dimensionalidade do problema e correlaciona os recursos.


Em seguida, usamos as previsões de retorno e risco (incerteza) para todos os ativos como entradas para um algoritmo de otimização de média-variância, que usa um solucionador quadrático para minimizar o risco de um dado retorno. Este método determina a alocação de ativos, que é diversa e garante o menor nível possível de risco, dados os retornos & # 8217; previsões.


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 em um período de dois anos. Contacte-nos para saber mais.


Estratégias AI superam.


É difícil encontrar dados de desempenho para estratégias de IA, dada a sua natureza proprietária, mas a empresa de pesquisa de fundos de hedge Eurekahedge publicou alguns dados informativos. O gráfico abaixo mostra o desempenho do Eurekahedge AI / Machine Learning Hedge Fund Index vs. quant e hedge funds tradicionais de 2010 a 2016. O Índice registra 23 fundos no total, dos quais 12 continuam ativos.


Eurekahedge observa que:


“Os hedge funds AI / Machine Learning têm superado os tradicionais e os hedge funds desde 2010, obtendo retornos anualizados de 8,44% neste período, comparados com 2,62%, 1,62% e 4,27% para os seguidores de tendência do CTA e o hedge médio global. fundos, respectivamente. ”


Eurekahedge também fornece a tabela a seguir com as principais conclusões:


Tabela 1: Desempenho em números - AI / Machine Learning Hedge Fund Index vs. quants e hedge funds tradicionais.


Os fundos hedge de IA / Aprendizagem Automática superaram o fundo de hedge global médio para todos os anos, exceto 2012. Com exceção de 2011 e 2014, os retornos de fundos de hedge de AI / Machine Learning ultrapassaram os tradicionais para estratégias de futuros geridos pelo CTA, enquanto obtiveram desempenho abaixo do esperado. o ano de 2014, quando este último realizou fortes ganhos de futuros de energia curta. Durante os cinco, três e dois anos do período anualizado, os fundos hedge de IA / Machine Learning superaram os quants tradicionais e os hedge funds globais médios, obtendo ganhos anualizados de 7,35%, 9,57% e 10,56%, respectivamente, durante esses períodos. Os fundos hedge de IA / Aprendizagem Automática também apresentaram melhores retornos ajustados ao risco nos últimos períodos de dois e três anos, comparados com todos os pares descritos na tabela abaixo, com as taxas de Sharpe de 1,51 e 1,53 nos dois períodos, respectivamente. Embora os retornos tenham sido mais voláteis em comparação com o fundo de hedge médio (compare com o Eurekahedge Hedge Fund Index), os fundos de AI / Machine Learning registraram volatilidades anualizadas consideravelmente mais baixas em comparação com as estratégias de acompanhamento de tendências sistemáticas.


Eurekahedge também observa que os fundos de hedge de Aprendizado de Máquina / Aprendizado estão “negativamente correlacionados ao fundo de hedge médio (-0.267)” e têm “correlação zero-a-marginalmente positiva com futuros geridos pelo CTA e estratégias de seguimento de tendência”, que apontam para o benefícios potenciais de diversificação de uma estratégia de IA.


Os dados acima ilustram o potencial em utilizar AI e Machine Learning em estratégias de negociação. Felizmente, os traders ainda estão nos estágios iniciais de incorporação dessa poderosa ferramenta 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 IA na prática:


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 relata um experimento que usou o Support Vector Machine (SVM) para negociar o S & # 038; P-500 e produziu excelentes resultados. Abaixo está a tabela que mostra como é realizada em relação aos 10 principais fundos mútuos quantitativos do mundo:


Estratégia usando o Google Trends.


Outra estratégia de negociação 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 deste artigo rastreou mudanças no volume de busca de um conjunto de 98 termos de pesquisa (alguns deles relacionados ao mercado de ações). O termo & # 8220; dívida & # 8221; acabou por ser o indicador mais forte e mais confiável ao prever os movimentos de preços no DJIA.


Abaixo está um gráfico de desempenho acumulado. A linha vermelha representa um & # 8220; Compre e segure & # 8221; estratégia. A estratégia do Google Trends (linha azul) superou maciçamente com um retorno de 326%.


Posso aprender ML pessoalmente?


Aplicando Machine Learning para negociação é 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ê esteja familiarizado com esses materiais, há também um curso popular da Udacity sobre como aplicar a base do Machine Learning ao mercado de negociação.


Se você quer 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 ligação conosco para explorar o que pode ser feito.


Preciso de exemplos mais específicos aplicáveis ​​no meu setor.


Ao incorporar o Aprendizado de Máquina em suas estratégias de negociação, seu portfólio pode capturar mais alfa. Mas implementar uma estratégia de investimento de sucesso é difícil - você precisará de pessoas extraordinárias e talentosas com experiência em comércio e ciência de dados para chegar lá. Deixe-nos ajudar você a começar.


0 comentários.


Deixe uma resposta Cancelar.


Você precisa estar logado para postar um comentário.


Histórias mais recentes


733 3rd Avenue, 15º andar.


Nova Iorque, NY, 10017.


Tão feliz em ver você ficar por perto!


Quer ser o primeiro a receber as novidades?


Digite seu endereço de e-mail abaixo e enviaremos as novidades diretamente para sua caixa de entrada.


Jesse Spaulding.


Como ganhei $ 500k com aprendizado de máquina e HFT (negociação de alta frequência)


Este post irá detalhar o que eu fiz para fazer aprox. 500k de negociação de alta frequência de 2009 a 2010. Desde que eu estava negociando de forma totalmente independente e não estou mais executando o meu programa, estou feliz em dizer tudo. Minha negociação foi principalmente em contratos de futuros Russel 2000 e DAX.


A chave do meu sucesso, acredito, não estava em uma equação financeira sofisticada, mas sim no design geral do algoritmo, que unia muitos componentes simples e usava o aprendizado de máquina para otimizar a máxima rentabilidade. Você não precisa conhecer nenhuma terminologia sofisticada aqui, porque quando eu configurei meu programa, tudo foi baseado na intuição. (O surpreendente curso de aprendizado de máquina de Andrew Ng ainda não estava disponível - se você clicar nesse link, você será levado ao meu projeto atual: CourseTalk, um site de revisão para MOOCs)


Primeiro, quero apenas demonstrar que meu sucesso não foi simplesmente o resultado da sorte. Meu programa fazia de 1000 a 4000 negociações por dia (meio longo, meio curto) e nunca ocupava posições de mais do que alguns contratos por vez. Isso significava que a sorte aleatória de qualquer negociação em particular era muito rápida. O resultado foi que eu nunca perdi mais de US $ 2000 em um dia e nunca tive um mês perdido:


(EDIT: Estes números são depois de pagar comissões)


E aqui está um gráfico para lhe dar uma noção da variação diária. Note que isso exclui os últimos 7 meses porque - à medida que os números pararam de subir - perdi minha motivação para entrar neles.


Antes de configurar o meu programa de negociação automatizado, eu tinha 2 anos de experiência como "manual" e "& rdquo; comerciante do dia. Isso foi em 2001 - eram os primeiros dias do comércio eletrônico e havia oportunidades para os "cambistas". fazer um bom dinheiro. Eu só posso descrever o que eu estava fazendo como se fosse jogar videogames / jogos de azar com uma suposta vantagem. Ser bem-sucedido significa ser rápido, ser disciplinado e ter uma boa capacidade intuitiva de reconhecimento de padrões. Consegui ganhar cerca de US $ 250 mil, pagar meus empréstimos estudantis e ter dinheiro sobrando. Ganhar!


Nos próximos cinco anos, eu lançaria duas startups, adquirindo 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 acabando com a venda da minha primeira startup, a negociação oferecia esperanças de algum dinheiro rápido enquanto eu descobria o meu próximo movimento.


Em 2008, eu era "manualmente" e "rdquo; dia negociando futuros usando software chamado T4. Eu estava querendo algumas teclas de atalho de entrada de pedidos personalizadas, então depois de descobrir que o T4 tinha uma API, aceitei o desafio de aprender C # (a linguagem de programação necessária para usar a API) e fui em frente e desenvolvi algumas teclas de atalho.


Depois de molhar os pés 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 pedidos para a troca - tudo o que eu tinha que fazer era criar a lógica no meio.


Abaixo está uma imagem de uma janela de negociação T4. O que foi legal é que quando eu comecei meu programa trabalhando eu pude assistir o comércio de computador exatamente nesta mesma interface. Assistir ordens reais entrando e saindo (por conta própria com meu dinheiro real) era ao mesmo tempo emocionante e assustador.


O design do meu algoritmo.


Desde o início, meu objetivo era configurar um sistema de modo que eu pudesse estar razoavelmente confiante de que ganharia dinheiro antes de fazer qualquer negociação ao vivo. Para conseguir isso, eu precisava construir uma estrutura de simulação de negociação que simulasse a negociação ao vivo, com a maior precisão possível.


Enquanto a negociação no modo ao vivo exigia atualizações do mercado de processamento transmitidas pela API, o modo de simulação exigia a leitura das atualizações do mercado a partir de um arquivo de dados. Para coletar esses dados, configurei a primeira versão do meu programa para simplesmente conectar-me à API e registrar as atualizações do mercado com registros de data e hora. Acabei usando 4 semanas de dados de mercado recentes para treinar e testar meu sistema.


Com uma estrutura básica em vigor, ainda tinha a tarefa de descobrir como criar um sistema comercial lucrativo. Como se vê, meu algoritmo se dividiria em dois componentes distintos, que eu exploraria por sua vez:


Previsão de movimentos de preços; e Fazendo negócios lucrativos.


Previsão de movimentos de preços.


Talvez um componente óbvio de qualquer sistema de negociação seja a capacidade de prever onde os preços irão se mover. E o meu não foi exceção. Eu defini o preço atual como a média do lance interno e da oferta interna e estabeleci a meta de prever onde o preço estaria nos próximos 10 segundos. Meu algoritmo precisaria apresentar essa previsão momento a momento ao longo do dia de negociação.


Criando & amp; otimização de indicadores.


Eu criei um punhado de indicadores que provaram ter uma capacidade significativa de prever movimentos de preços de curto prazo. Cada indicador produziu um número que foi positivo ou negativo. Um indicador era útil se, na maior parte dos casos, um número positivo correspondesse ao aumento do mercado e um número negativo correspondesse à queda do mercado.


Meu sistema me permitiu determinar rapidamente a capacidade preditiva de qualquer indicador, por isso pude experimentar muitos indicadores diferentes para ver o que funcionava. Muitos dos indicadores tinham variáveis ​​nas fórmulas que os produziam e eu 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 em que eu estava negociando, bem como nos mercados de títulos correlacionados.


Fazendo previsões precisas de movimentação de preços.


Ter indicadores que simplesmente previam uma alta ou baixa no preço não era suficiente. Eu precisava saber exatamente quanto movimento de preço era previsto por cada valor possível de cada indicador. Eu precisava de uma fórmula que convertesse um valor de indicador em uma previsão de preço.


Para conseguir isso, acompanhei as movimentações de preço previstas em 50 buckets que dependiam do intervalo em que o valor do indicador caiu. Isso gerou previsões exclusivas para cada bucket que eu era capaz de representar graficamente no Excel. Como você pode ver, a mudança de preço esperada 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 "ajuste de curva". manualmente, mas logo escrevi algum código para automatizar esse processo.


Note que nem todas as curvas do indicador tinham a mesma forma. Observe também que os buckets foram distribuídos logaritmicamente para distribuir os dados de maneira uniforme. Por fim, observe que os valores dos indicadores negativos (e suas previsões de preços descendentes correspondentes) foram invertidos e combinados com os valores positivos. (Meu algoritmo tratado para cima e para baixo 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 somar todas as previsões que cada indicador fez individualmente. A chave era descobrir o valor preditivo adicional que cada indicador tinha além do que já estava previsto. Isso não era difícil de implementar, mas significava que se eu estivesse "ajustando a curva", vários indicadores ao mesmo tempo, tive que ser cuidadoso; a mudança de um efetuaria as previsões de outro.


Para ajustar a curva & rdquo; Todos os indicadores ao mesmo tempo eu configurei o otimizador para pisar apenas 30% do caminho para as novas curvas de previsão com cada passagem. Com esse salto de 30%, descobri que as curvas de previsão se estabilizariam em poucas passagens.


Com cada indicador nos dando agora a previsão adicional de preço, eu poderia simplesmente adicioná-los para produzir uma única previsão de onde o mercado estaria em 10 segundos.


Por que prever preços não é suficiente.


Você pode pensar que com essa vantagem no mercado eu era de ouro. Mas você precisa ter em mente que o mercado é composto de ofertas e ofertas - não é apenas um preço de mercado. Sucesso na negociação de alta freqüência se resume a obter bons preços e não é assim tão fácil.


Os fatores a seguir dificultam a criação de um sistema lucrativo:


Com cada negócio eu tive que pagar comissões ao meu corretor e à bolsa. O spread (diferença entre oferta mais alta e oferta mais baixa) significava que se eu simplesmente comprasse e vendesse aleatoriamente, estaria perdendo uma tonelada de dinheiro. A maior parte do volume do mercado era de outros bots que só fariam uma troca comigo se achassem que tinham alguma vantagem estatística. Vendo uma oferta não garante que eu poderia comprá-lo. No momento em que minha ordem de compra chegou à bolsa, era muito possível que essa oferta tivesse sido cancelada. Como um pequeno participante do mercado, não havia como competir sozinho com a velocidade.


Construindo uma simulação de negociação completa.


Então eu tive uma estrutura que me permitiu backtest e otimizar os indicadores. Mas eu tive que ir além disso - eu precisava de um framework que me permitisse fazer backtest e otimizar um sistema de negociação completo; aquele em que eu estava mandando pedidos e ficando em posições. Neste caso, eu estaria otimizando para P & amp; L total e, em certa medida, P & amp; L médio por negociação.


Isso seria mais complicado e, de certa forma, impossível modelar exatamente, mas eu fiz o melhor que pude. Aqui estão alguns dos problemas que eu tive que lidar:


Quando um pedido foi enviado ao mercado na simulação, tive que modelar o tempo de atraso. O fato de meu sistema ter visto uma oferta não significa que ela poderia comprá-la imediatamente. O sistema enviaria o pedido, aguardaria aproximadamente 20 milissegundos e somente se a oferta ainda estivesse lá era considerado como um negócio executado. Isso era inexato porque o tempo real de atraso era inconsistente e não relatado. Quando eu fiz lances ou ofertas, tive que olhar para o fluxo de execução de negociação (fornecido pela API) e usá-los para avaliar quando meu pedido seria executado. Para fazer isso direito eu tive que rastrear a posição do meu pedido na fila. (É um sistema first-in first-out). Novamente, eu não pude fazer isso perfeitamente, mas fiz uma melhor aproximação.


Para refinar minha simulação de execução de pedidos, o que fiz foi extrair meus arquivos de log da negociação ao vivo pela API e compará-los aos arquivos de log produzidos pela negociação simulada no mesmo período de tempo. Consegui obter minha simulação ao ponto de ser bastante precisa e, para as partes que eram impossíveis de modelar exatamente, certifiquei-me de, pelo menos, produzir resultados que fossem estatisticamente semelhantes (nas métricas que julguei importantes).


Fazendo negócios lucrativos.


Com um modelo de simulação de pedidos, agora eu poderia enviar pedidos no modo de simulação e ver um P & amp; Mas como meu sistema saberia quando e onde comprar e vender?


As previsões do 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 uma ordem de compra) e um nível abaixo da oferta interna (para uma ordem de venda).


Se a pontuação de um determinado nível de preço estiver acima de um determinado limite, isso significa que o meu sistema deve ter um lance / oferta ativa - abaixo do limite, então qualquer pedido ativo deve ser cancelado. Com base nisso, não era incomum que meu sistema exibisse um lance no mercado e o cancelasse imediatamente. (Embora eu tentei minimizar isso, é irritante para quem olha para a tela com olhos humanos - inclusive eu.)


As pontuações do nível de preços foram calculadas com base nos seguintes fatores:


A previsão do movimento de preços (que discutimos anteriormente). O nível de preços em questão. (Níveis internos significavam que grandes previsões de movimentação de preço eram necessárias.) 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 "seguro". lugares para licitar / oferecer. A previsão do movimento de preços, por si só, não era adequada porque não levava em conta o fato de que, ao fazer uma oferta, eu não era preenchido automaticamente - só fui preenchido se alguém me vendesse lá. A realidade era que o simples fato de alguém me vender a um certo preço mudava as probabilidades estatísticas do negócio.


As variáveis ​​usadas nesta etapa foram todas sujeitas a otimização. Isso foi feito exatamente da mesma maneira que eu otimizei as variáveis ​​nos indicadores de preço, exceto neste caso eu estava otimizando para a linha de fundo P & amp; L.


Quando negociamos como seres humanos, muitas vezes temos emoções e vieses poderosos que podem levar a decisões menos que ótimas. Obviamente, não queria codificar esses vieses. Aqui estão alguns fatores que meu sistema ignorou:


O preço em que uma posição foi inserida - Em um escritório comercial, é bastante comum ouvir conversas sobre o preço em que alguém é comprido ou baixo, como se isso pudesse afetar sua futura tomada de decisão. Embora isso tenha alguma validade como parte de uma estratégia de redução de riscos, ela realmente não tem relação com o curso futuro dos eventos no mercado. Portanto, meu programa ignorou completamente essa informação. É o mesmo conceito que ignorar os custos irrecuperáveis. Indo curto vs. saindo de uma posição longa - Tipicamente um trader teria critérios diferentes que determinam onde vender uma posição comprada versus onde ir short. No entanto, da minha perspectiva de algoritmos, não havia razão para fazer uma distinção. Se meu algoritmo esperava um movimento descendente, a venda era uma boa ideia, independentemente de ser atualmente longa, curta ou plana. A & ldquo; dobrando & rdquo; estratégia - Esta é uma estratégia comum, onde os comerciantes vão comprar mais ações no caso de que o comércio original vai contra eles. Isso faz com que o preço médio de compra seja menor e isso significa que quando (ou se) a ação girar, você estará pronto para recuperar seu dinheiro rapidamente. Na minha opinião, esta é realmente uma estratégia horrível, a menos que você esteja Warren Buffet. Você é levado a pensar que está indo bem porque a maioria de seus negócios será vencedora. O problema é quando você perde você perde grande. O outro efeito é que torna difícil julgar se você realmente tem uma vantagem no mercado ou está apenas tendo sorte. Ser capaz de monitorar e confirmar que meu programa realmente tinha uma vantagem era um objetivo importante.


Como meu algoritmo tomava decisões da mesma forma, independentemente de onde ele entrasse em uma negociação ou se era atualmente longo ou curto, ocasionalmente ele fazia parte (e tomava) de algumas grandes negociações perdedoras (além de algumas grandes negociações vitoriosas). Mas, você não deve pensar que não houve nenhum gerenciamento de risco.


Para gerenciar o risco, impus um tamanho máximo de posição de dois contratos por vez, ocasionalmente aumentado em dias de alto volume. Eu também tinha um limite máximo de perda diária para proteger contra condições inesperadas de mercado ou um bug no meu software. Esses limites foram aplicados no meu código, mas também no backend por meio do meu corretor. Aconteceu que nunca encontrei problemas significativos.


A partir do momento em que comecei a trabalhar no meu programa, demorei cerca de 6 meses até atingir o ponto de rentabilidade e comecei a executá-lo ao vivo. Embora, para ser justo, uma quantidade significativa de tempo foi aprender uma nova linguagem de programação. Enquanto trabalhei para melhorar o programa, vi um aumento nos lucros para cada um dos próximos quatro meses.


Toda semana eu reciclaria meu sistema com base nas 4 semanas anteriores de dados. Descobri que isso estabelecia o equilíbrio certo entre captar tendências comportamentais recentes do mercado e garantir que meu algoritmo tivesse dados suficientes para estabelecer padrões significativos. Como o treinamento começou a tomar mais e mais tempo, eu o dividi para que pudesse ser executado por 8 máquinas virtuais usando o amazon EC2. Os resultados foram então reunidos na minha máquina local.


O ponto alto da minha negociação foi em outubro de 2009, quando fiz quase 100k. Depois disso, continuei a passar os próximos quatro meses tentando melhorar meu programa, apesar do lucro reduzido a cada mês. Infelizmente, a essa altura, acho que implementei todas as minhas melhores ideias, porque nada do que tentei parecia ajudar muito.


Com a frustração de não poder fazer melhorias e não ter senso de crescimento, comecei a pensar em uma nova direção. Eu enviei um e-mail para 6 diferentes empresas de negociação de alta frequência para ver se eles estariam interessados ​​em comprar meu software e me contratar para trabalhar para eles. Ninguém respondeu. Eu tive algumas novas idéias de inicialização que eu queria trabalhar, então eu nunca dei continuidade.


ATUALIZAÇÃO - Eu postei isso no Hacker News e tem recebido muita atenção. Eu só quero dizer que eu 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 qualquer esperança de competir. Mesmo quando eu estava fazendo isso, acredito que era muito raro para as pessoas alcançarem o sucesso (embora eu já tivesse ouvido falar de outras pessoas).


Há um comentário no topo da página que menciona "estatísticas manipuladas" e se refere a mim como um investidor de varejo & rdquo; que quants iria "alegremente escolher". Este é um comentário bastante infeliz que simplesmente não se baseia na realidade. Deixando isso de lado, há alguns comentários interessantes: news. ycombinator / item? Id = 4748624.


ATUALIZAÇÃO # 2 - Fiz uma FAQ de acompanhamento que responde a algumas perguntas comuns que recebi de traders sobre essa postagem.


carlosspicyweiner111 gostou disto.


Oi, eu sou Jesse, fundador do Thinklab. Eu moro e toco em São Francisco. Você encontrou minha casa na web .. Bem-vindo!


Aprendizado de Máquina para o Curso de Negociação.


Visão geral.


Este curso apresenta aos alunos os desafios do mundo real de implementar estratégias de negociação baseadas em aprendizado de máquina, incluindo as etapas algorítmicas desde a coleta de informações até as ordens do mercado. O foco está em como aplicar abordagens de aprendizado de máquina probabilísticas às decisões de negociação. Consideramos abordagens estatísticas como regressão linear, Q-Learning, KNN e árvores de regressão e como aplicá-las às situações reais de negociação de ações.


Este curso é composto por três mini-cursos:


Um conjunto de notas do curso e código de exemplo pode ser encontrado aqui: [[1]]


Conteúdo de Vídeo.


O conteúdo de vídeo deste curso está disponível gratuitamente em [Udacity].


Nota importante.


Este curso aumenta as dificuldades no final. Os projetos no final 1/3 do curso são desafiadores. Esteja preparado.


Informação do instrutor.


Professor de Computação Interativa na Georgia Tech.


Designer de Cursos CS 7646.


Instrutor CS 7646: Primavera 2016, Outono 2016, Primavera 2017, Verão 2017 (online), Outono 2017, Primavera 2018.


Pesquisador, Centro de Tecnologia de Mídia Interativa da Georgia Tech.


CS 7646 Instructor: Summer 2016, Summer 2017 (no campus), Primavera de 2018.


CS 7646 Head TA: Primavera de 2016, outono de 2016, outono de 2017.


Programas e cronograma para semestres específicos.


Livros didáticos, Software & amp; Outros recursos.


Nós usaremos os seguintes livros didáticos:


Para Mini-curso 1: Python for Finance por Yves Hilpisch amazon (opcional) Para Mini-curso 2: What Hedge Funds Really Do por Romero e Balch amazon (obrigatório) Para Mini-curso 3: Machine Learning por Tom Mitchell (opcional) Comprar por US $ 218,00 em: amazon Compre uma versão em brochura por US $ 61,78. AVISOS IMPORTANTES: 1) Eles só enviam para os EUA 2) Demora 3 semanas para imprimir o livro. Se você fizer pedidos de fora dos EUA, eles aceitarão o seu dinheiro tranquilamente, mas nunca enviarão o livro: versão mais barata no mcgraw hill Compre uma versão internacional em brochura por US $ 19,10. Não tenho certeza sobre a confiabilidade desta empresa: internacional.


Notas do curso desenvolvidas por Octavian Blaga [docs. google] Documentação do Pandas: [pandas. pydata] Os slides de David Byrd sobre como vetorizar os métodos de análise técnica: media: CDB_vectorize_me. pptx.


Pré-requisitos / Co-requisitos


Todos os tipos de estudantes são bem vindos! Os tópicos de Aprendizado de Máquina podem ser "revisão" para estudantes de Ciências da Computação, enquanto partes de finanças serão revisadas para estudantes de finanças. No entanto, mesmo que você tenha experiência nesses tópicos, descobrirá que os consideramos de uma maneira diferente da que você poderia ter visto antes, em particular com um olho na implementação para negociação.


Se você responder "não" às seguintes perguntas, pode ser benéfico atualizar seu conhecimento do material de pré-requisito antes de tomar CS 7646:


Você tem um conhecimento prático de estatísticas básicas, incluindo distribuições de probabilidade (como normal e uniforme), cálculo e diferenças entre média, mediana e modo Você entende a diferença entre média geométrica e média aritmética? Você tem fortes habilidades de programação? Faça este teste compinvesti-prog-quiz se você quiser ajudar a determinar a força de suas habilidades de programação. Você é competente na linha de comando do Unix?


Para quem é este curso: O curso destina-se a pessoas com forte experiência em programação de software e conhecimento de nível introdutório sobre práticas de investimento. Um pré-requisito primário é um interesse e entusiasmo sobre o mercado de ações.


Software que usaremos: Para concluir as tarefas de programação, você precisará de um ambiente de desenvolvimento com o qual esteja familiarizado. Usamos o Unix, mas você também pode trabalhar com ambientes Windows e Mac OS. Você deve baixar e instalar um conjunto de módulos Python em seu computador (incluindo NumPy, SciPy e Pandas).


OMSCS: Usaremos o Udacity para vídeos de palestras. Entre aqui usando sua conta GT: GT-Udacity Login (video de instrução)


Nota: NÃO faça o login usando sua conta Udacity pessoal, caso você tenha uma. Vá para o curso de Udacity (ou navegue pelos Meus Cursos): udacity / course / viewer #! / C-ud501 Se você tiver problemas para acessar o conteúdo Udacity, por favor, compartilhe seu problema via e-mail com gtech-support @ udacity Usaremos T - Quadrado para TODAS as submissões: T-Square (escolha o local do curso apropriado) Usaremos o Piazza ou o Reddit para interação e discussão. Consulte a página do semestre atual para um link.


A: 90,0% e acima B: 80,0% e acima C: 70,0% e acima D: 60,0% e acima F: abaixo de 60,0%


Os alunos que fazem o curso Passe / Reprovado devem ganhar pelo menos 75% para passar.


Nós não encorajamos os alunos de "auditoria". Se você está no curso sobre o status de auditoria, você deve ganhar pelo menos um "B" no meio do período.


Veja o programa semestral para pesos de atribuição.


Requisitos técnicos mínimos


Navegador e velocidade de conexão: uma versão atualizada do Chrome ou do Firefox é altamente recomendável. Também suportamos o Internet Explorer 9 e as versões para desktop do Internet Explorer 10 e superior (não as versões do metrô). 2+ Mbps recomendado; no mínimo velocidade de download de 0,768 Mbps. Hardware: Um computador com pelo menos 4 GB de RAM e velocidade de CPU de pelo menos 2,5 GHz. Para desenvolvimento e teste de código, essas três configurações funcionarão com PC: Windows XP ou superior com as atualizações mais recentes instaladas Mac: OS X 10.6 ou superior com atualizações mais recentes instaladas Linux: Qualquer distribuição recente que tenha os navegadores suportados instalados Para realizar testes on-line (proctortrack) você precisará de um: PC: Windows XP ou superior com as atualizações mais recentes instaladas Mac: OS X 10.6 ou superior com as atualizações mais recentes instaladas O Linux NÃO é suportado.


Horas de expediente.


Estar determinado.


Plágio.


Na maioria dos casos, espero que todo o código enviado seja escrito por você. Apresentarei algumas bibliotecas na classe que você tem permissão para usar (como pandas e numpy). Caso contrário, todo código-fonte, imagens e anotações fornecidas por você devem ter sido criados somente por você.


Melhores estratégias 4: Machine Learning.


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, AlphaGo, pudesse derrotar o melhor jogador de Go humano. O Deep Blue era um sistema baseado em modelos com regras de xadrez hardwired. O AlphaGo é um sistema de mineração de dados, uma rede neural profunda treinada com milhares de jogos Go. Não melhorou hardware, mas um avanço no software foi essencial para a etapa de bater os melhores jogadores de xadrez para bater os melhores jogadores de Go.


Nesta quarta parte da minissérie, analisaremos a abordagem de mineração de dados para o desenvolvimento de estratégias de negociação. 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. Aprendizado de máquina ou & # 8220; Inteligência Artificial & # 8221; nem sempre está envolvido em estratégias de mineração de dados. Na verdade, o mais popular # 8211; e surpreendentemente rentável & # 8211; O método de mineração de dados funciona sem nenhuma rede neural sofisticada ou máquina de vetores de suporte.


Princípios de aprendizado de máquina.


Um algoritmo de aprendizagem é alimentado com amostras de dados, normalmente derivadas de algum modo dos preços históricos. Cada amostra consiste em n variáveis ​​x 1 .. x n, comumente chamadas de preditores, recursos, sinais ou simplesmente input. Esses preditores podem ser os retornos de preço das últimas n barras, ou uma coleção de indicadores clássicos, ou quaisquer outras funções imagináveis ​​da curva de preço (eu mesmo vi os pixels de uma imagem de gráfico de preços usados ​​como preditores de um gráfico neural). rede!). Cada amostra também inclui normalmente uma variável-alvo y, como o retorno da transação seguinte após a amostra, ou o próximo movimento de preço. Na literatura você pode encontrar y também chamado rótulo ou objetivo. Em um processo de treinamento, o algoritmo aprende a predizer o alvo y a partir dos preditores x 1 .. x n. A memória erudita & # 8216; & # 8217; é armazenado em uma estrutura de dados denominada model que é específica para o algoritmo (não confundir com um modelo financeiro para estratégias baseadas em modelos!). Um modelo de aprendizado de máquina pode ser uma função com regras de predição no código C, geradas pelo processo de treinamento. Ou pode ser um conjunto de pesos de conexão de uma rede neural.


Os preditores, recursos ou o que quer que você os chame, devem conter informações suficientes para prever a meta com alguma precisão. Eles também geralmente cumprem dois requisitos formais. Primeiro, todos os valores de previsão 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, isto é, igualmente distribuídas por todos os valores da variável alvo. Portanto, deve haver tantos vencendo quanto perdendo amostras. Se você não observar esses dois requisitos, ficará imaginando por que está obtendo resultados ruins com o algoritmo de aprendizado de máquina.


Os algoritmos de regressão predizem um valor numérico, como a magnitude e o sinal do próximo movimento de preço. Algoritmos de classificação preveem uma classe de amostra qualitativa, por exemplo, se ela precede uma vitória ou uma perda. Alguns algoritmos, como redes neurais, árvores de decisão ou máquinas de vetores de suporte, podem ser executados em ambos os modos.


Alguns algoritmos aprendem a dividir amostras em classes sem precisar de nenhum destino. Isso é aprendizagem não supervisionada, ao contrário da aprendizagem supervisionada usando um alvo. Em algum lugar entre os dois está o aprendizado por reforço, em que o sistema se treina executando simulações com os recursos dados e usando o resultado como alvo de treinamento. AlphaZero, o sucessor do AlphaGo, usou o aprendizado de reforço ao jogar milhões de jogos Go contra si mesmo. Em finanças, há poucas aplicações para aprendizado não supervisionado ou de reforço. 99% das estratégias de aprendizado de máquina usam o aprendizado supervisionado.


Seja qual for o sinal que estamos usando para os preditores em finanças, eles provavelmente conterão muito ruído e pouca informação, e serão não-estacionários em cima dele. Portanto, a previsão financeira é uma das tarefas mais difíceis no aprendizado de máquina. Algoritmos mais complexos não atingem necessariamente melhores resultados. A seleção dos preditores é fundamental para o sucesso. Não é uma boa ideia usar muitos preditores, pois isso simplesmente causa overfitting e falha na operação de amostra. Portanto, as estratégias de mineração de dados geralmente aplicam um algoritmo de pré-seleção que determina um pequeno número de preditores de um conjunto de muitos. A pré-seleção pode se basear na correlação entre preditores, no significado, no conteúdo da informação ou simplesmente no sucesso da previsão com um conjunto de testes. Experimentos práticos com seleção de recursos podem ser encontrados em um artigo recente no blog Robot Wealth.


Aqui está uma lista dos métodos mais populares de mineração de dados usados ​​em finanças.


1. Sopa indicadora.


A maioria dos sistemas de negociação que estamos programando para clientes não é baseada em um modelo financeiro. O cliente queria apenas sinais comerciais de determinados indicadores técnicos, filtrados com outros indicadores técnicos em combinação com indicadores mais técnicos. Quando perguntado como essa miscelânea de indicadores poderia ser uma estratégia lucrativa, ele normalmente respondia: "Confie em mim." Eu estou trocando-o manualmente, e isso funciona. & # 8221;


Isso realmente aconteceu. Pelo menos às vezes. Embora a maioria desses sistemas não tenha passado no teste WFA (e alguns nem mesmo um simples backtest), um número surpreendentemente grande foi o que aconteceu. E esses também eram frequentemente lucrativos em negociações reais. O cliente tinha sistematicamente experimentado indicadores técnicos até encontrar uma combinação que funcionasse na negociação ao vivo com certos ativos. Essa forma de análise técnica de tentativa e erro é uma abordagem clássica de mineração de dados, executada apenas por um ser humano e não por uma máquina. Eu não posso realmente recomendar este método & # 8211; e muita sorte, para não falar de dinheiro, está provavelmente envolvida & # 8211; mas posso testemunhar que às vezes leva a sistemas lucrativos.


2. Padrões de vela.


Não deve ser confundido com aqueles Padrões Japoneses de Vela que tiveram seu melhor encontro antes, há muito tempo. O equivalente moderno é a negociação de ações de preço. Você ainda está olhando para as velas abertas, altas, baixas e fechadas. Você ainda está esperando encontrar um padrão que preveja uma direção de preço. Mas agora você está analisando as curvas de preços contemporâneas para coletar esses padrões. Existem pacotes de software para esse fim. Eles pesquisam padrões que são lucrativos por algum critério definido pelo usuário e os utilizam para criar uma função específica de detecção de padrões. Poderia se parecer com este (do analisador de padrões do Zorro):


Esta função C retorna 1 quando os sinais correspondem a um dos padrões, caso contrário, 0. Você pode ver no longo código que essa não é a maneira mais rápida de detectar padrões. Um método melhor, usado pelo Zorro quando a função de detecção não precisa ser exportada, está classificando os sinais pela sua magnitude e verificando a ordem de classificação. Um exemplo de tal sistema pode ser encontrado aqui.


O preço da negociação de ações realmente funciona? Assim como a sopa indicadora, ela não é baseada em nenhum modelo financeiro racional. Pode-se imaginar, na melhor das hipóteses, que sequências de movimentos de preços fazem com que os participantes do mercado reajam de uma determinada maneira, estabelecendo assim um padrão preditivo temporário. No entanto, o número de padrões é bastante limitado quando você olha apenas sequências de algumas velas adjacentes. O próximo passo é comparar velas que não são adjacentes, mas arbitrariamente selecionadas dentro de um período de tempo mais longo. Dessa forma, você está obtendo um número quase ilimitado de padrões & # 8211; mas ao custo de finalmente deixar o reino do racional. É difícil imaginar como um movimento de preços pode ser previsto por alguns padrões de velas de semanas atrás.


Ainda assim, muito esforço está sendo feito. Um colega blogueiro, Daniel Fernandez, administra um site de assinatura (Asirikuy) especializado em padrões de velas de mineração de dados. Ele refinou o padrão de negociação até os menores detalhes, e se alguém conseguisse algum lucro dessa maneira, seria ele. Mas para seus assinantes & # 8217; decepção, trocando seus padrões ao vivo (QuriQuant) produziu resultados muito diferentes dos seus maravilhosos backtests. Se realmente existem sistemas de ações lucrativas, aparentemente ninguém os encontrou ainda.


3. Regressão linear


A base simples de muitos algoritmos complexos de aprendizado de máquina: Preveja a variável de destino y por uma combinação linear dos preditores x 1 .. x n.


Os coeficientes a n são o modelo. Eles são calculados para minimizar a soma das diferenças quadráticas entre os valores verdadeiros de y das amostras de treinamento e seus y previstos da fórmula acima:


Para amostras distribuídas normais, a minimização é possível com alguma aritmética de matriz, portanto, nenhuma iteração é necessária. No caso n = 1 & # 8211; com apenas uma variável preditora x & # 8211; a fórmula de regressão é reduzida para.


que é a regressão linear simples, em oposição à regressão linear multivariada em que n & gt; 1 Regressão linear simples está disponível na maioria das plataformas de negociação, f. i. com o indicador LinReg no TA-Lib. Com y = preço e x = tempo, ele é frequentemente usado como alternativa a uma média móvel. A regressão linear multivariada está disponível na plataforma R através da função lm (..) que acompanha a instalação padrão. Uma variante é a regressão polinomial. Como a regressão simples, ele usa apenas uma variável preditora x, mas também seu quadrado e graus mais altos, de modo que x n == x n:


Com n = 2 ou n = 3, a regressão polinomial é freqüentemente usada para prever o próximo preço médio dos preços suavizados das últimas barras. A função polyfit do MatLab, R, Zorro e muitas outras plataformas pode ser usada para a regressão polinomial.


4. Perceptron.


Muitas vezes referida como uma rede neural com apenas um neurônio. De fato, um perceptron é uma função de regressão como acima, mas com um resultado binário, chamado de regressão logística. Não é a regressão, é um algoritmo de classificação. A função de aviso do Zorro (PERCEPTRON, & # 8230;) gera o código C que retorna 100 ou -100, dependendo se o resultado previsto está acima de um limite ou não:


Você pode ver que a matriz de caracteres é equivalente aos recursos x n na fórmula de regressão e os fatores numéricos são os coeficientes a n.


5. Redes nacionais.


A regressão linear ou logística só pode resolver problemas lineares. Muitos não se enquadram nesta categoria & # 8211; Um exemplo famoso é prever a saída de uma função XOR simples. E provavelmente também prevê preços ou retornos comerciais. Uma rede neural artificial (RNA) pode lidar com problemas não-lineares. É um monte de perceptrons que estão conectados em uma matriz de camadas. Qualquer perceptron é um neurônio da rede. Sua saída vai para as entradas de todos os neurônios da próxima camada, assim:


Como o perceptron, uma rede neural também aprende determinando os coeficientes que minimizam o erro entre a previsão da amostra e o alvo da amostra. Mas isso requer agora um processo de aproximação, normalmente com retropropagação do erro da saída para as entradas, otimizando os pesos em seu caminho. Este processo impõe duas restrições. Primeiro, as saídas dos neurônios devem agora ser funções continuamente diferenciáveis, em vez do simples limiar do perceptron. Em segundo lugar, a rede não deve ser muito profunda & # 8211; não deve ter muitas & # 8216; camadas ocultas & # 8217; de neurônios entre entradas e saídas. Essa segunda restrição limita a complexidade dos problemas que uma rede neural padrão pode resolver.


Ao usar uma rede neural para prever negociações, você tem muitos parâmetros com os quais você pode brincar e, se você não for cuidadoso, produzirá um grande viés de seleção:


Número de camadas ocultas Número de neurônios por camada oculta Número de ciclos de retropropagação, épocas nomeadas Taxa de aprendizado, a largura do passo de uma época Momentum, um fator de inércia para a adaptação de pesos Função de ativação.


A função de ativação emula o limiar do perceptron. Para a retropropagação você precisa de uma função continuamente diferenciável que gere um & # 8216; soft & # 8217; passo em um determinado valor x. Normalmente, uma função sigmoid, tanh ou softmax é usada. Às vezes, também é uma função linear que apenas retorna a soma ponderada de todas as entradas. Neste caso, a rede pode ser usada para regressão, para prever um valor numérico em vez de um resultado binário.


As redes neurais estão disponíveis na instalação padrão R (nnet, uma única rede de camada oculta) e em muitos pacotes, por exemplo, RSNNS e FCNN4R.


6. Aprendizagem profunda.


Os métodos de aprendizagem profunda usam redes neurais com muitas camadas ocultas e milhares de neurônios, que não poderiam ser efetivamente treinados pela retropropagação convencional. Vários métodos tornaram-se populares nos últimos anos para o treinamento de redes tão grandes. Eles costumam pré-treinar as camadas de neurônios ocultos para alcançar um processo de aprendizado mais efetivo. Uma máquina restrita de Boltzmann (RBM) é um algoritmo de classificação não supervisionado com uma estrutura de rede especial que não tem conexões entre os neurônios ocultos. Um Autoencoder Escasso (SAE) usa uma estrutura de rede convencional, mas pré-treina as camadas ocultas de maneira inteligente, reproduzindo os sinais de entrada nas saídas da camada com o mínimo possível de conexões ativas. Esses métodos permitem redes muito complexas para lidar com tarefas de aprendizagem muito complexas. Tal como bater o melhor jogador humano do mundo.


Redes de aprendizagem profunda estão disponíveis nos pacotes R deep e darch. A Deepnet fornece um autoencoder, Darch uma máquina Boltzmann restrita. Eu ainda não experimentei o Darch, mas aqui está um exemplo do script R usando o autoencoder do Deepnet com 3 camadas ocultas para sinais de negociação através da função neural () do Zorro:


7. Máquinas de vetores de suporte.


Como uma rede neural, uma máquina de vetores de suporte (SVM) é outra extensão da regressão linear. Quando olhamos novamente para a fórmula de regressão,


podemos interpretar os recursos x n como coordenadas de um espaço de recurso n-dimensional. Definir a variável de destino y como um valor fixo determina um plano nesse espaço, chamado de hiperplano, pois possui mais de duas dimensões (na verdade, n-1). O hiperplano separa as amostras com y & gt; o das amostras com y & lt; 0 Os coeficientes an podem ser calculados de forma que as distâncias do plano às amostras mais próximas & # 8211; que são chamados os vetores de suporte & # 8216; & # 8217; do avião, daí o nome do algoritmo & # 8211; é o máximo. Desta forma, temos um classificador binário com separação ideal de amostras vencedoras e perdedoras.


O problema: normalmente essas amostras não são linearmente separáveis ​​& # 8211; eles estão espalhados irregularmente no espaço de recursos. Nenhum plano plano pode ser espremido entre vencedores e perdedores. Se pudesse, nós tínhamos métodos mais simples para calcular esse plano, f. i. análise discriminante linear. Mas, para o caso comum, precisamos do truque do SVM: Adicionar mais dimensões ao espaço do recurso. Para isso, o algoritmo SVM produz mais recursos com uma função kernel que combina quaisquer dois preditores existentes para um novo recurso. Isso é análogo ao passo acima da regressão simples à regressão polinomial, onde também mais características são adicionadas, tomando o único preditor da enésima potência. Quanto mais dimensões você adicionar, mais fácil será separar as amostras com um hiperplano plano. Este plano é então transformado de volta ao espaço n-dimensional original, ficando enrugado e amassado no caminho. Ao selecionar inteligentemente a função kernel, o processo pode ser executado sem realmente computar a transformação.


Como as redes neurais, as SVMs podem ser usadas não apenas para classificação, mas também para regressão. Eles também oferecem alguns parâmetros para otimizar e possivelmente sobrecarregar o processo de previsão:


Função de kernel. Você normalmente usa um kernel RBF (função de base radial, um kernel simétrico), mas você também tem a escolha de outros kernels, como sigmoid, polynomial e linear. Gama, a largura do parâmetro de Custo do kernel RBF C, a penalidade & # 8216; & # 8217; para classificações erradas nas amostras de treinamento.


Um SVM frequentemente usado é a biblioteca libsvm. Também está disponível em R no pacote e1071. Na próxima e última parte desta série pretendo descrever uma estratégia de negociação usando este SVM.


8. K-vizinho mais próximo.


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.2016 Predicting price direction using ANN & SVM: Kara. et. al.2011 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!


Thanks for posting this great mini series 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,


você pode ganhar dinheiro extra todo mês porque tem conteúdo de alta qualidade.


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!!


Aprendizado de Máquina para Negociação.


Oferecido na Georgia Tech como CS 7646.


Programa de Nanodegree.


Learn Unreal VR.


Learn the fundamentals of building vr applications using unreal engine.


Acelere sua carreira com a credencial que leva você rapidamente ao sucesso no trabalho.


Sobre este curso.


Este curso apresenta aos alunos os desafios do mundo real de implementar estratégias de negociação baseadas em aprendizado de máquina, incluindo as etapas algorítmicas desde a coleta de informações até as ordens do mercado. O foco está em como aplicar abordagens de aprendizado de máquina probabilísticas às decisões de negociação. Consideramos abordagens estatísticas como regressão linear, KNN e árvores de regressão e como aplicá-las às situações reais de negociação de ações.


Custo do Curso


Aprox. 4 meses.


Nível de habilidade.


Incluído no curso.


Conteúdo rico de aprendizado.


Ministrado por profissionais da indústria.


Comunidade de Suporte ao Aluno.


Junte-se ao caminho para a grandeza.


This free course is your first step towards a new career with the Learn Unreal VR Nanodegree Program.


Curso Livre.


Aprendizado de Máquina para Negociação.


Melhore seu conjunto de habilidades e impulsione sua contratação por meio de aprendizado inovador e independente.


Programa de Nanodegree.


Learn Unreal VR.


Acelere sua carreira com a credencial que leva você rapidamente ao sucesso no trabalho.


Leads do curso.


Tucker Balch.


Arpan Chakraborty.


O que você aprenderá


Este curso é composto por três mini-cursos:


Mini-curso 1: Manipulando Dados Financeiros em Python Mini-curso 2: Investimento Computacional Mini-curso 3: Algoritmos de Aprendizado de Máquina para Negociação.


Cada mini-curso consiste em cerca de 7 a 10 lições curtas. Atribuições e projetos são intercalados.


Queda 2015 Estudantes da OMS: Haverá dois testes - um de meio de aula após o minicurso 2 e um exame final.


Pré-requisitos e requisitos.


Os estudantes devem ter fortes habilidades de codificação e alguma familiaridade com os mercados de ações. Nenhuma experiência financeira ou de aprendizado de máquina é assumida.


Note que este curso atende estudantes com foco em ciência da computação, assim como alunos de outras áreas, como engenharia de sistemas industriais, gerenciamento ou matemática, que têm experiências diferentes. Todos os tipos de estudantes são bem vindos!


Os tópicos do ML podem ser & quot; revisão & quot; para alunos do CS, enquanto partes de finanças serão revisadas para estudantes de finanças. No entanto, mesmo que você tenha experiência nesses tópicos, descobrirá que os consideramos de uma maneira diferente da que você poderia ter visto antes, em particular com um olho na implementação para negociação.


A programação será principalmente em Python. Vamos fazer uso pesado de bibliotecas de computação numérica como o NumPy e o Pandas.


Por que fazer este curso?


No final deste curso, você deve ser capaz de:


Entenda as estruturas de dados usadas para negociação algorítmica. Saiba como construir software para acessar dados de patrimônio ao vivo, avaliá-lo e tomar decisões comerciais. Compreender 3 algoritmos de aprendizado de máquina populares e como aplicá-los a problemas de negociação. Entenda como avaliar o desempenho de um algoritmo de aprendizado de máquina para dados de séries temporais (dados de preço de ações). Saiba como e por que as técnicas de mineração de dados (aprendizado de máquina) falham. Construa um sistema de software de negociação de ações que usa dados diários atuais.


Algumas limitações / restrições:


Nós usamos dados diários. Este não é um curso de HFT, mas muitos dos conceitos aqui são relevantes. Nós não interagimos (negociamos) diretamente com o mercado, mas vamos gerar alocações de ações que você poderia negociar se quisesse.


O que eu ganho?


Vídeos de instrutor Aprender fazendo exercícios Ensinados por profissionais da indústria.


Cursos relacionados.


Computational Photography.


Sistemas Embarcados.


Cyber-Physical Systems Security.


High Performance Computer Architecture.


Big Data Analytics in Healthcare.


Software Analysis & Testando


Cursos Populares.


Display Advertising.


Learn Swift Programming Syntax.


Featured Programs.


Apenas no Udacity.


Programas.


O negócio.


"Nanodegree" é uma marca registrada da Udacity. &cópia de; 2011 & ndash; 2018 Udacity, Inc.


Udacity não é uma universidade credenciada e não conferimos graus.


Melhores estratégias 5: um sistema de aprendizado de máquina de curto prazo.


É hora da quinta e última parte da série Build Better Strategies. Na parte 3, discutimos o processo de desenvolvimento de um sistema baseado em modelo e, consequentemente, concluiremos a série com o desenvolvimento de um sistema de mineração de dados. Os princípios de mineração de dados e aprendizado de máquina têm sido o tópico da parte 4. Para nosso exemplo de negociação de curto prazo, usaremos um algoritmo de aprendizado profundo, um autoencoder empilhado, mas funcionará da mesma maneira com muitas outras máquinas. algoritmos de aprendizagem. Com as ferramentas de software de hoje, apenas cerca de 20 linhas de código são necessárias para uma estratégia de aprendizado de máquina. Eu tentarei explicar todas as etapas em detalhes.


Our example will be a research project – a machine learning experiment for answering two questions. Does a more complex algorithm – such as, more neurons and deeper learning – produce a better prediction? And are short-term price moves predictable by short-term price history? The last question came up due to my scepticism about price action trading in the previous part of this series. I got several emails asking about the “trading system generators” or similar price action tools that are praised on some websites. There is no hard evidence that such tools ever produced any profit (except for their vendors) – but does this mean that they all are garbage? Nós veremos.


Our experiment is simple: We collect information from the last candles of a price curve, feed it in a deep learning neural net, and use it to predict the next candles. My hypothesis is that a few candles don’t contain any useful predictive information. Of course, a nonpredictive outcome of the experiment won’t mean that I’m right, since I could have used wrong parameters or prepared the data badly. But a predictive outcome would be a hint that I’m wrong and price action trading can indeed be profitable.


Machine learning strategy development.


Step 1: The target variable.


To recap the previous part: a supervised learning algorithm is trained with a set of features in order to predict a target variable . So the first thing to determine is what this target variable shall be. A popular target, used in most papers, is the sign of the price return at the next bar. Better suited for prediction, since less susceptible to randomness, is the price difference to a more distant prediction horizon , like 3 bars from now, or same day next week. Like almost anything in trading systems, the prediction horizon is a compromise between the effects of randomness (less bars are worse) and predictability (less bars are better).


Sometimes you’re not interested in directly predicting price, but in predicting some other parameter – such as the current leg of a Zigzag indicator – that could otherwise only be determined in hindsight. Or you want to know if a certain market inefficiency will be present in the next time, especially when you’re using machine learning not directly for trading, but for filtering trades in a model-based system. Or you want to predict something entirely different, for instance the probability of a market crash tomorrow. All this is often easier to predict than the popular tomorrow’s return.


In our price action experiment we’ll use the return of a short-term price action trade as target variable. Once the target is determined, next step is selecting the features.


Step 2: The features.


A price curve is the worst case for any machine learning algorithm. Not only does it carry little signal and mostly noise , it is also nonstationary and the signal/noise ratio changes all the time. The exact ratio of signal and noise depends on what is meant with “signal”, but it is normally too low for any known machine learning algorithm to produce anything useful. So we must derive features from the price curve that contain more signal and less noise. Signal, in that context, is any information that can be used to predict the target, whatever it is. All the rest is noise.


Thus, selecting the features is critical for success – much more critical than deciding which machine learning algorithm you’re going to use. There are two approaches for selecting features. The first and most common is extracting as much information from the price curve as possible. Since you do not know where the information is hidden, you just generate a wild collection of indicators with a wide range of parameters, and hope that at least a few of them will contain the information that the algorithm needs. This is the approach that you normally find in the literature. The problem of this method: Any machine learning algorithm is easily confused by nonpredictive predictors. So it won’t do to just throw 150 indicators at it. You need some preselection algorithm that determines which of them carry useful information and which can be omitted. Without reducing the features this way to maybe eight or ten, even the deepest learning algorithm won’t produce anything useful.


The other approach, normally for experiments and research, is using only limited information from the price curve. This is the case here: Since we want to examine price action trading, we only use the last few prices as inputs, and must discard all the rest of the curve. This has the advantage that we don’t need any preselection algorithm since the number of features is limited anyway. Here are the two simple predictor functions that we use in our experiment (in C):


The two functions are supposed to carry the necessary information for price action: per-bar movement and volatility. The change function is the difference of the current price to the price of n bars before, divided by the current price. The range function is the total high-low distance of the last n candles, also in divided by the current price. And the scale function centers and compresses the values to the +/-100 range, so we divide them by 100 for getting them normalized to +/-1 . We remember that normalizing is needed for machine learning algorithms.


Step 3: Preselecting/preprocessing predictors.


When you have selected a large number of indicators or other signals as features for your algorithm, you must determine which of them is useful and which not. There are many methods for reducing the number of features, for instance:


Determine the correlations between the signals. Remove those with a strong correlation to other signals, since they do not contribute to the information. Compare the information content of signals directly, with algorithms like information entropy or decision trees. Determine the information content indirectly by comparing the signals with randomized signals; there are some software libraries for this, such as the R Boruta package. Use an algorithm like Principal Components Analysis (PCA) for generating a new signal set with reduced dimensionality. Use genetic optimization for determining the most important signals just by the most profitable results from the prediction process. Great for curve fitting if you want to publish impressive results in a research paper.


For our experiment we do not need to preselect or preprocess the features, but you can find useful information about this in articles (1), (2), and (3) listed at the end of the page.


Step 4: Select the machine learning algorithm.


R offers many different ML packages, and any of them offers many different algorithms with many different parameters. Even if you already decided about the method – here, deep learning – you have still the choice among different approaches and different R packages. Most are quite new, and you can find not many empirical information that helps your decision. You have to try them all and gain experience with different methods. For our experiment we’ve choosen the Deepnet package, which is probably the simplest and easiest to use deep learning library. This keeps our code short. We’re using its Stacked Autoencoder ( SAE ) algorithm for pre-training the network. Deepnet also offers a Restricted Boltzmann Machine ( RBM ) for pre-training, but I could not get good results from it. There are other and more complex deep learning packages for R, so you can spend a lot of time checking out all of them.


How pre-training works is easily explained, but why it works is a different matter. As to my knowledge, no one has yet come up with a solid mathematical proof that it works at all. Anyway, imagine a large neural net with many hidden layers:


Training the net means setting up the connection weights between the neurons. The usual method is error backpropagation. But it turns out that the more hidden layers you have, the worse it works. The backpropagated error terms get smaller and smaller from layer to layer, causing the first layers of the net to learn almost nothing. Which means that the predicted result becomes more and more dependent of the random initial state of the weights. This severely limited the complexity of layer-based neural nets and therefore the tasks that they can solve. At least until 10 years ago.


In 2006 scientists in Toronto first published the idea to pre-train the weights with an unsupervised learning algorithm, a restricted Boltzmann machine. This turned out a revolutionary concept. It boosted the development of artificial intelligence and allowed all sorts of new applications from Go-playing machines to self-driving cars. In the case of a stacked autoencoder, it works this way:


Select the hidden layer to train; begin with the first hidden layer. Connect its outputs to a temporary output layer that has the same structure as the network’s input layer. Feed the network with the training samples, but without the targets. Train it so that the first hidden layer reproduces the input signal – the features – at its outputs as exactly as possible. The rest of the network is ignored. During training, apply a ‘weight penalty term’ so that as few connection weights as possible are used for reproducing the signal. Now feed the outputs of the trained hidden layer to the inputs of the next untrained hidden layer, and repeat the training process so that the input signal is now reproduced at the outputs of the next layer. Repeat this process until all hidden layers are trained. We have now a ‘sparse network’ with very few layer connections that can reproduce the input signals. Now train the network with backpropagation for learning the target variable, using the pre-trained weights of the hidden layers as a starting point.


The hope is that the unsupervised pre-training process produces an internal noise-reduced abstraction of the input signals that can then be used for easier learning the target. And this indeed appears to work. No one really knows why, but several theories – see paper (4) below – try to explain that phenomenon.


Step 5: Generate a test data set.


We first need to produce a data set with features and targets so that we can test our prediction process and try out parameters. The features must be based on the same price data as in live trading, and for the target we must simulate a short-term trade. So it makes sense to generate the data not with R, but with our trading platform, which is anyway a lot faster. Here’s a small Zorro script for this, DeepSignals. c :


We’re generating 2 years of data with features calculated by our above defined change and range functions. Our target is the result of a trade with 3 bars life time. Trading costs are set to zero, so in this case the result is equivalent to the sign of the price difference at 3 bars in the future. The adviseLong function is described in the Zorro manual; it is a mighty function that automatically handles training and predicting and allows to use any R-based machine learning algorithm just as if it were a simple indicator.


In our code, the function uses the next trade return as target, and the price changes and ranges of the last 4 bars as features. The SIGNALS flag tells it not to train the data, but to export it to a. csv file. The BALANCED flag makes sure that we get as many positive as negative returns; this is important for most machine learning algorithms. Run the script in [Train] mode with our usual test asset EUR/USD selected. It generates a spreadsheet file named DeepSignalsEURUSD_L. csv that contains the features in the first 8 columns, and the trade return in the last column.


Step 6: Calibrate the algorithm.


Complex machine learning algorithms have many parameters to adjust. Some of them offer great opportunities to curve-fit the algorithm for publications. Still, we must calibrate parameters since the algorithm rarely works well with its default settings. For this, here’s an R script that reads the previously created data set and processes it with the deep learning algorithm ( DeepSignal. r ):


We’ve defined three functions neural. train , neural. predict , and neural. init for training, predicting, and initializing the neural net. The function names are not arbitrary, but follow the convention used by Zorro’s advise(NEURAL. ) function. It doesn’t matter now, but will matter later when we use the same R script for training and trading the deep learning strategy. A fourth function, TestOOS , is used for out-of-sample testing our setup.


The function neural. init seeds the R random generator with a fixed value (365 is my personal lucky number). Otherwise we would get a slightly different result any time, since the neural net is initialized with random weights. It also creates a global R list named “Models”. Most R variable types don’t need to be created beforehand, some do (don’t ask me why). The ‘<<-‘ operator is for accessing a global variable from within a function.


The function neural. train takes as input a model number and the data set to be trained. The model number identifies the trained model in the “ Models ” Lista. A list is not really needed for this test, but we’ll need it for more complex strategies that train more than one model. The matrix containing the features and target is passed to the function as second parameter. If the XY data is not a proper matrix, which frequently happens in R depending on how you generated it, it is converted to one. Then it is split into the features ( X ) and the target ( Y ), and finally the target is converted to 1 for a positive trade outcome and 0 for a negative outcome.


The network parameters are then set up. Some are obvious, others are free to play around with:


The network structure is given by the hidden vector: c(50,100,50) defines 3 hidden layers, the first with 50, second with 100, and third with 50 neurons. That’s the parameter that we’ll later modify for determining whether deeper is better. The activation function converts the sum of neuron input values to the neuron output; most often used are sigmoid that saturates to 0 or 1, or tanh that saturates to -1 or +1.


We use tanh here since our signals are also in the +/-1 range. The output of the network is a sigmoid function since we want a prediction in the 0..1 range. But the SAE output must be “linear” so that the Stacked Autoencoder can reproduce the analog input signals on the outputs.


The learning rate controls the step size for the gradient descent in training; a lower rate means finer steps and possibly more precise prediction, but longer training time. Momentum adds a fraction of the previous step to the current one. It prevents the gradient descent from getting stuck at a tiny local minimum or saddle point. The learning rate scale is a multiplication factor for changing the learning rate after each iteration (I am not sure for what this is good, but there may be tasks where a lower learning rate on higher epochs improves the training). An epoch is a training iteration over the entire data set. Training will stop once the number of epochs is reached. More epochs mean better prediction, but longer training. The batch size is a number of random samples – a mini batch – taken out of the data set for a single training run. Splitting the data into mini batches speeds up training since the weight gradient is then calculated from fewer samples. The higher the batch size, the better is the training, but the more time it will take. The dropout is a number of randomly selected neurons that are disabled during a mini batch. This way the net learns only with a part of its neurons. This seems a strange idea, but can effectively reduce overfitting.


All these parameters are common for neural networks. Play around with them and check their effect on the result and the training time. Properly calibrating a neural net is not trivial and might be the topic of another article. The parameters are stored in the model together with the matrix of trained connection weights. So they need not to be given again in the prediction function, neural. predict . It takes the model and a vector X of features, runs it through the layers, and returns the network output, the predicted target Y . Compared with training, prediction is pretty fast since it only needs a couple thousand multiplications. If X was a row vector, it is transposed and this way converted to a column vector, otherwise the nn. predict function won’t accept it.


Use RStudio or some similar environment for conveniently working with R. Edit the path to the. csv data in the file above, source it, install the required R packages (deepnet, e1071, and caret), then call the TestOOS function from the command line. If everything works, it should print something like that:


TestOOS reads first our data set from Zorro’s Data folder. It splits the data in 80% for training ( XY. tr ) and 20% for out-of-sample testing ( XY. ts ). The training set is trained and the result stored in the Models list at index 1. The test set is further split in features ( X ) and targets ( Y ). Y is converted to binary 0 or 1 and stored in Y. ob , our vector of observed targets. We then predict the targets from the test set, convert them again to binary 0 or 1 and store them in Y. pr . For comparing the observation with the prediction, we use the confusionMatrix function from the caret package.


A confusion matrix of a binary classifier is simply a 2×2 matrix that tells how many 0’s and how many 1’s had been predicted wrongly and correctly. A lot of metrics are derived from the matrix and printed in the lines above. The most important at the moment is the 62% prediction accuracy . This may hint that I bashed price action trading a little prematurely. But of course the 62% might have been just luck. We’ll see that later when we run a WFO test.


A final advice: R packages are occasionally updated, with the possible consequence that previous R code suddenly might work differently, or not at all. This really happens, so test carefully after any update.


Step 7: The strategy.


Now that we’ve tested our algorithm and got some prediction accuracy above 50% with a test data set, we can finally code our machine learning strategy. In fact we’ve already coded most of it, we just must add a few lines to the above Zorro script that exported the data set. This is the final script for training, testing, and (theoretically) trading the system ( DeepLearn. c ):


We’re using a WFO cycle of one year, split in a 90% training and a 10% out-of-sample test period. You might ask why I have earlier used two year’s data and a different split, 80/20, for calibrating the network in step 5. This is for using differently composed data for calibrating and for walk forward testing. If we used exactly the same data, the calibration might overfit it and compromise the test.


The selected WFO parameters mean that the system is trained with about 225 days data, followed by a 25 days test or trade period. Thus, in live trading the system would retrain every 25 days, using the prices from the previous 225 days. In the literature you’ll sometimes find the recommendation to retrain a machine learning system after any trade, or at least any day. But this does not make much sense to me. When you used almost 1 year’s data for training a system, it can obviously not deteriorate after a single day. Or if it did, and only produced positive test results with daily retraining, I would strongly suspect that the results are artifacts by some coding mistake.


Training a deep network takes really a long time, in our case about 10 minutes for a network with 3 hidden layers and 200 neurons. In live trading this would be done by a second Zorro process that is automatically started by the trading Zorro. In the backtest, the system trains at any WFO cycle. Therefore using multiple cores is recommended for training many cycles in parallel. The NumCores variable at -1 activates all CPU cores but one. Multiple cores are only available in Zorro S, so a complete walk forward test with all WFO cycles can take several hours with the free version.


In the script we now train both long and short trades. For this we have to allow hedging in Training mode, since long and short positions are open at the same time. Entering a position is now dependent on the return value from the advise function, which in turn calls either the neural. train or the neural. predict function from the R script. So we’re here entering positions when the neural net predicts a result above 0.5.


The R script is now controlled by the Zorro script (for this it must have the same name, DeepLearn. r , only with different extension). It is identical to our R script above since we’re using the same network parameters. Only one additional function is needed for supporting a WFO test:


The neural. save function stores the Models list – it now contains 2 models for long and for short trades – after every training run in Zorro’s Data folder. Since the models are stored for later use, we do not need to train them again for repeated test runs.


This is the WFO equity curve generated with the script above (EUR/USD, without trading costs):


EUR/USD equity curve with 50-100-50 network structure.


Although not all WFO cycles get a positive result, it seems that there is some predictive effect. The curve is equivalent to an annual return of 89%, achieved with a 50-100-50 hidden layer structure. We’ll check in the next step how different network structures affect the result.


Since the neural. init , neural. train , neural. predict , and neural. save functions are automatically called by Zorro’s adviseLong/adviseShort functions, there are no R functions directly called in the Zorro script. Thus the script can remain unchanged when using a different machine learning method. Only the DeepLearn. r script must be modified and the neural net, for instance, replaced by a support vector machine. For trading such a machine learning system live on a VPS, make sure that R is also installed on the VPS, the needed R packages are installed, and the path to the R terminal set up in Zorro’s ini file. Otherwise you’ll get an error message when starting the strategy.


Step 8: The experiment.


If our goal had been developing a strategy, the next steps would be the reality check, risk and money management, and preparing for live trading just as described under model-based strategy development. But for our experiment we’ll now run a series of tests, with the number of neurons per layer increased from 10 to 100 in 3 steps, and 1, 2, or 3 hidden layers (deepnet does not support more than 3). So we’re looking into the following 9 network structures: c(10), c(10,10), c(10,10,10), c(30), c(30,30), c(30,30,30), c(100), c(100,100), c(100,100,100). For this experiment you need an afternoon even with a fast PC and in multiple core mode. Here are the results (SR = Sharpe ratio, R2 = slope linearity):


We see that a simple net with only 10 neurons in a single hidden layer won’t work well for short-term prediction. Network complexity clearly improves the performance, however only up to a certain point. A good result for our system is already achieved with 3 layers x 30 neurons. Even more neurons won’t help much and sometimes even produce a worse result. This is no real surprise, since for processing only 8 inputs, 300 neurons can likely not do a better job than 100.


Conclusão.


Our goal was determining if a few candles can have predictive power and how the results are affected by the complexity of the algorithm. The results seem to suggest that short-term price movements can indeed be predicted sometimes by analyzing the changes and ranges of the last 4 candles. The prediction is not very accurate – it’s in the 58%..60% range, and most systems of the test series become unprofitable when trading costs are included. Still, I have to reconsider my opinion about price action trading. The fact that the prediction improves with network complexity is an especially convincing argument for short-term price predictability.


It would be interesting to look into the long-term stability of predictive price patterns. For this we had to run another series of experiments and modify the training period ( WFOPeriod in the script above) and the 90% IS/OOS split. This takes longer time since we must use more historical data. I have done a few tests and found so far that a year seems to be indeed a good training period. The system deteriorates with periods longer than a few years. Predictive price patterns, at least of EUR/USD, have a limited lifetime.


Where can we go from here? There’s a plethora of possibilities, for instance:


Use inputs from more candles and process them with far bigger networks with thousands of neurons. Use oversampling for expanding the training data. Prediction always improves with more training samples. Compress time series f. i. with spectal analysis and analyze not the candles, but their frequency representation with machine learning methods. Use inputs from many candles – such as, 100 – and pre-process adjacent candles with one-dimensional convolutional network layers. Use recurrent networks. Especially LSTM could be very interesting for analyzing time series – and as to my knowledge, they have been rarely used for financial prediction so far. Use an ensemble of neural networks for prediction, such as Aronson’s “oracles” and “comitees”.


Papers / Articles.


(3) V. Perervenko, Selection of Variables for Machine Learning.


I’ve added the C and R scripts to the 2016 script repository. You need both in Zorro’s Strategy folder. Zorro version 1.474, and R version 3.2.5 (64 bit) was used for the experiment, but it should also work with other versions.


75 thoughts on “Better Strategies 5: A Short-Term Machine Learning System”


I’ve tested your strategy using 30min AAPL data but “sae. dnn. train” returns all NaN in training.


(It works just decreasing neurons to less than (5,10,5)… but accuracy is 49%)


Can you help me to understand why?


Desde já, obrigado.


If you have not changed any SAE parameters, look into the. csv data. It is then the only difference to the EUR/USD test. Maybe something is wrong with it.


Another fantastic article, jcl. Zorro is a remarkable environment for these experiments. Thanks for sharing your code and your approach – this really opens up an incredible number of possibilities to anyone willing to invest the time to learn how to use Zorro.


The problem with AAPL 30min data was related to the normalizing method I used (X-mean/SD).


The features range was not between -1:1 and I assume that sae. dnn need it to work…


Anyway performances are not comparable to yours 🙂


I have one question:


why do you use Zorro for creating the features in the csv file and then opening it in R?


why not create the file with all the features in R in a few lines and do the training on the file when you are already in R? instead of getting inside Zorro and then to R.


When you want R to create the features, you must still transmit the price data and the targets from Zorro to R. So you are not gaining much. Creating the features in Zorro results usually in shorter code and faster training. Features in R make only sense when you need some R package for calculating them.


Really helpful and interesting article! I would like to know if there are any English version of the book:


“Das Börsenhackerbuch: Finanziell unabhängig durch algorithmische Handelssysteme”


I am really interested on it,


Not yet, but an English version is planned.


Thanks JCL! Please let me now when the English version is ready, because I am really interested on it.


Works superbly (as always). Muito Obrigado. One small note, if you have the package “dlm” loaded in R, TestOOS will fail with error: “Error in TestOOS() : cannot change value of locked binding for ‘X'”. This is due to there being a function X in the dlm package, so the name is locked when the package is loaded. Easily fixed by either renaming occurrences of the variable X to something else, or temporarily detaching the dlm package with: detach(“package:dlm”, unload=TRUE)


Thanks for the info with the dlm package. I admit that ‘X’ is not a particular good name for a variable, but a function named ‘X’ in a distributed package is even a bit worse.


Results below were generated by revised version of DeepSignals. r – only change was use of LSTM net from the rnn package on CRAN. The authors of the package regard their LSTM implementation as “experimental” and do not feel it is as yet learning properly, so hopefully more improvement to come there. (Spent ages trying to accomplish the LSTM element using the mxnet package but gave up as couldn’t figure out the correct input format when using multiple training features.)


Will post results of full WFO when I have finished LSTM version of DeepLearn. r.


Confusion Matrix and Statistics.


95% CI : (0.5699, 0.5956)


No Information Rate : 0.5002.


P-Value [Acc > NIR] : <2e-16.


Mcnemar's Test P-Value : 0.2438.


Pos Pred Value : 0.5844.


Neg Pred Value : 0.5813.


Detection Rate : 0.2862.


Detection Prevalence : 0.4897.


Balanced Accuracy : 0.5828.


Results of WFO test below. Again, only change to original files was the use of LSTM in R, rather than DNN+SAE.


Walk-Forward Test DeepLearnLSTMV4 EUR/USD.


Simulated account AssetsFix.


Bar period 1 hour (avg 87 min)


Simulation period 15.05.2014-07.06.2016 (12486 bars)


Test period 04.05.2015-07.06.2016 (6649 bars)


Lookback period 100 bars (4 days)


WFO test cycles 11 x 604 bars (5 weeks)


Training cycles 12 x 5439 bars (46 weeks)


Monte Carlo cycles 200.


Assumed slippage 0.0 sec.


Spread 0.0 pips (roll 0.00/0.00)


Contracts per lot 1000.0.


Gross win/loss 3628$ / -3235$ (+5199p)


Average profit 360$/year, 30$/month, 1.38$/day.


Max drawdown -134$ 34% (MAE -134$ 34%)


Total down time 95% (TAE 95%)


Max down time 5 weeks from Aug 2015.


Max open margin 40$


Max open risk 35$


Trade volume 5710964$ (5212652$/year)


Transaction costs 0.00$ spr, 0.00$ slp, 0.00$ rol.


Capital required 262$


Number of trades 6787 (6195/year, 120/week, 25/day)


Percent winning 57.6%


Max win/loss 16$ / -14$


Avg trade profit 0.06$ 0.8p (+12.3p / -14.8p)


Avg trade slippage 0.00$ 0.0p (+0.0p / -0.0p)


Avg trade bars 1 (+1 / -2)


Max trade bars 3 (3 hours)


Time in market 177%


Max open trades 3.


Max loss streak 17 (uncorrelated 11)


Annual return 137%


Profit factor 1.12 (PRR 1.08)


Sharpe ratio 1.79.


Kelly criterion 2.34.


R2 coefficient 0.435.


Ulcer index 13.3%


Prediction error 152%


Confidence level AR DDMax Capital.


Portfolio analysis OptF ProF Win/Loss Wgt% Cycles.


EUR/USD .219 1.12 3907/2880 100.0 XX/\//\X///


EUR/USD:L .302 1.17 1830/1658 65.0 /\/\//\////


EUR/USD:S .145 1.08 2077/1222 35.0 \//\//\\///


Interessante! For a still experimental LSTM implementation that result looks not bad.


Sorry for being completely off topic but could you please point me to the best place where i can learn to code trend lines?? I’m a complete beginner, but from trading experience i see them as an important part of what i would like to build…


Robot Wealth has an algorithmic trading course for that – you can find details on his blog robotwealth/.


I think you misunderstand the meaning pretrening. See my articles mql5/ru/articles/1103.


I think there is more fully described this stage.


I don’t think I misunderstood pretraining, at least not more than everyone else, but thanks for the links!


You can paste your LTSM r code please ?


Could you help me answering some questions?


I have few question below:


1.I want to test Commission mode.


If I use interactive broker, I should set Commission = ? in normal case.


2.If I press the “trade” button, I see the log the script will use DeepLearn_EURUSD. ml.


So real trade it will use DeepLearn_EURUSD. ml to get the model to trade?


And use neural. predict function to trade?


3.If I use the slow computer to train the data ,


I should move DeepLearn_EURUSD. ml to the trade computer?


I test the real trade on my interactive brokers and press the result button.


Can I use Commission=0.60 to train the neural and get the real result?


Result button will show the message below:


Trade Trend EUR/USD.


Bar period 2 min (avg 2 min)


Trade period 02.11.2016-02.11.2016.


Spread 0.5 pips (roll -0.02/0.01)


Contracts per lot 1000.0.


Commission should be normally not set up in the script, but entered in the broker specific asset list. Otherwise you had to change the script every time when you want to test it with a different broker or account. IB has different lot sizes and commissions, so you need to add the command.


to the script when you want to test it for an IB account.


Yes, DeepLearn_EURUSD. ml is the model for live trading, and you need to copy it to the trade computer.


Do I write assetList(“AssetsIB. csv”) in the right place?


So below code’s result includes Commission ?


I test the result with Commission that seems pretty good.


Annual +93% +3177p.


BarPeriod = 60; // 1 hour.


WFOPeriod = 252*24; // 1 year.


NumCores = -1; // use all CPU cores but one.


Spread = RollLong = RollShort = Commission = Slippage = 0;


if(Train) Hedge = 2;


I run the DeepLearn. c in the IB paper trade.


The code “LifeTime = 3; // prediction horizon” seems to close the position that you open after 3 bars(3 hours).


But I can’t see it close the position on third bar close.


I see the logs below:


Closing prohibited – check NFA flag!


[EUR/USD::L4202] Can’t close 1@1.10995 at 09:10:51.


In my IB paper trade, it the default order size is 1k on EUR/USD.


How to change the order size in paper trade?


Muito obrigado.


IB is an NFA compliant broker. You can not close trades on NFA accounts. You must set the NFA flag for opening a reverse position instead. And you must enable trading costs, otherwise including the commission has no effect. I don’t think that you get a positive result with trading costs.


Those account issues are not related to machine learning, and are better asked on the Zorro forum. Or even better, read the Zorro manual where all this is explained. Just search for “NFA”.


I do some experiment to change the neural’s parameter with commission.


The code is below:


BarPeriod = 60; // 1 hour.


WFOPeriod = 252*24; // 1 year.


NumCores = -1; // use all CPU cores but one.


Spread = RollLong = RollShort = Slippage = 0;


if(Train) Hedge = 2;


I get the result with commission that Annual Return is about +23%.


But I don’t complete understand the zorro’s setting and zorro’s report.


Walk-Forward Test DeepLearn EUR/USD.


Simulated account AssetsIB. csv.


Bar period 1 hour (avg 86 min)


Simulation period 15.05.2014-09.09.2016 (14075 bars)


Test period 23.04.2015-09.09.2016 (8404 bars)


Lookback period 100 bars (4 days)


WFO test cycles 14 x 600 bars (5 weeks)


Training cycles 15 x 5401 bars (46 weeks)


Monte Carlo cycles 200.


Simulation mode Realistic (slippage 0.0 sec)


Spread 0.0 pips (roll 0.00/0.00)


Contracts per lot 20000.0.


Gross win/loss 24331$ / -22685$ (+914p)


Average profit 1190$/year, 99$/month, 4.58$/day.


Max drawdown -1871$ 114% (MAE -1912$ 116%)


Total down time 92% (TAE 41%)


Max down time 18 weeks from Dec 2015.


Max open margin 2483$


Max open risk 836$


Trade volume 26162350$ (18916130$/year)


Transaction costs 0.00$ spr, 0.00$ slp, 0.00$ rol, -1306$ com.


Capital required 5239$


Number of trades 1306 (945/year, 19/week, 4/day)


Percent winning 52.5%


Max win/loss 375$ / -535$


Avg trade profit 1.26$ 0.7p (+19.7p / -20.3p)


Avg trade slippage 0.00$ 0.0p (+0.0p / -0.0p)


Avg trade bars 2 (+2 / -3)


Max trade bars 3 (3 hours)


Time in market 46%


Max open trades 3.


Max loss streak 19 (uncorrelated 10)


Annual return 23%


Profit factor 1.07 (PRR 0.99)


Sharpe ratio 0.56.


Kelly criterion 1.39.


R2 coefficient 0.000.


Ulcer index 20.8%


Confidence level AR DDMax Capital.


10% 29% 1134$ 4153$


20% 27% 1320$ 4427$


30% 26% 1476$ 4656$


40% 24% 1649$ 4911$


50% 23% 1767$ 5085$


60% 22% 1914$ 5301$


70% 21% 2245$ 5789$


80% 19% 2535$ 6216$


90% 16% 3341$ 7403$


95% 15% 3690$ 7917$


100% 12% 4850$ 9625$


Portfolio analysis OptF ProF Win/Loss Wgt% Cycles.


EUR/USD .256 1.07 685/621 100.0 /X/XXXXXXXXXXX.


The manual is your friend:


Great read…I built this framework to use XGB to analyze live ETF price movements. Let me know what you think:


Hi, deep learning researcher and programmer here. 🙂


Great blog and great article, congratulations! I have some comments:


& # 8211; if you use ReLUs as activation functions, pretraining is not necessary.


& # 8211; AE is genarraly referred to as networks with same input and output, I would call the proposed network rather a MLP (multi-layer perceptron).


Do you think it is possible to use Python (like TensorFlow) or LUA (like Torch7) based deep learing libraries with Zorro?


I have also heard that ReLUs make a network so fast that you can brute force train it in some cases, with no pretraining. But I have not yet experimented with that. The described network is commonly called ‘SAE’ since it uses autoencoders, with indeed the same number of inputs and outputs, for the pre-training process. & # 8211; I am not familiar with Torch7, but you can theoretically use Tensorflow with Zorro with a DLL based interface. The network structure must still be defined in Python, but Zorro can use the network for training and prediction.


Would you do YouTube Tutorials to your work, this series of articles. And where can I subscribe this kinda of algorithmic trading tutorials. Obrigado pela sua contribuição.


I would do YouTube tutorials if someone payed me very well for them. Until then, you can subscribe this blog with the link on the right above.


Why not feed economic data from a calendar like forexfactory into the net as well? I suggested that several times before. This data is what makes me a profitable manual trader (rookie though), if there is any intelligence in these neuronal networks it should improve performance greatly. input must be name (non farm payrolls for example or some unique identifier) , time left to release, predicted value (like 3-5 days before) last value and revision. Some human institutional traders claim its possible to trade profitably without a chart from this data alone. Detecting static support and resistance areas (horizontal lines) should be superior to any simple candle patterns. It can be mathematically modeled, as the Support and Resistance indicator from Point Zero Trading proves. Unfortunately i dont have a clue how Arturo the programmer did it. I imagine an artificial intelligence actually “seeing” what the market is focussed on (like speculation on a better than expected NFP report based on other positive Data in the days before, driving the dollar up into the report). “seeing” significant support and resistance levels should allow for trading risk, making reasonable decisions on where to place SL and TP.


We also made the experience that well chosen external data, not derived from the price curve, can improve the prediction. There is even a trading system based on Trump’s twitter outpourings. I can’t comment on support and resistance since I know no successful systems that use them, and am not sure that they exist at all.


thank you very much for everything that you did so far.


I read the book (German here, too) and am working through your blog articles right now.


I already learnt a lot and still am learning more and more about the really important stuff (other than: Your mindset must be perfect and you need to have well-defined goals. I never was a fan of such things and finally I found someone that is on the same opinion and actually teaches people how to correctly do it).


So, thank you very much and thanks in advance for all upcoming articles that I will read and you will post.


As a thank you I was thinking about sending you a corrected version of your book (there are some typos and wrong articles here and there…). Would you be interested in that?


Again thank you for everything and please keep up the good work.


Obrigado! And I’m certainly interested in a list of all my mistakes.


Thank you for this interesting post. I ran it on my pc and obtained similar results as yours. Then I wanted to see if it could perform as well when commission and rollover and slippage were included during test. I used the same figures as the ones used in the workshops and included in the AssetFix. csv file. The modifications I did in your DeepLearn. c file are as follows:


Spread = RollLong = RollShort = Commission = Slippage = 0;


The results then were not as optimistic as without commission:


Walk-Forward Test DeepLearn_realistic EUR/USD.


Simulated account AssetsFix.


Bar period 1 hour (avg 86 min)


Simulation period 09.05.2014-27.01.2017 (16460 bars)


Test period 22.04.2015-27.01.2017 (10736 bars)


Lookback period 100 bars (4 days)


WFO test cycles 18 x 596 bars (5 weeks)


Training cycles 19 x 5367 bars (46 weeks)


Monte Carlo cycles 200.


Simulation mode Realistic (slippage 5.0 sec)


Spread 0.5 pips (roll -0.02/0.01)


Contracts per lot 1000.0.


Gross win/loss 5608$ / -6161$ (-6347p)


Average profit -312$/year, -26$/month, -1.20$/day.


Max drawdown -635$ -115% (MAE -636$ -115%)


Total down time 99% (TAE 99%)


Max down time 85 weeks from Jun 2015.


Max open margin 40$


Max open risk 41$


Trade volume 10202591$ (5760396$/year)


Transaction costs -462$ spr, 46$ slp, -0.16$ rol, -636$ com.


Capital required 867$


Number of trades 10606 (5989/year, 116/week, 24/day)


Percent winning 54.9%


Max win/loss 18$ / -26$


Avg trade profit -0.05$ -0.6p (+11.1p / -14.8p)


Avg trade slippage 0.00$ 0.0p (+1.5p / -1.7p)


Avg trade bars 1 (+1 / -2)


Max trade bars 3 (3 hours)


Time in market 188%


Max open trades 3.


Max loss streak 19 (uncorrelated 12)


Annual return -36%


Profit factor 0.91 (PRR 0.89)


Sharpe ratio -1.39.


Kelly criterion -5.39.


R2 coefficient 0.737.


Ulcer index 100.0%


Confidence level AR DDMax Capital.


Portfolio analysis OptF ProF Win/Loss Wgt% Cycles.


EUR/USD .000 0.91 5820/4786 100.0 XX/\XX\X\X/X/\\X\\


I am a very beginner with Zorro, maybe I did a mistake ? O que você acha ?


No, your results look absolutely ok. The predictive power of 4 candles is very weak. This is just an experiment for finding out if price action has any predictive power at all.


Although it apparently has, I have not yet seen a really profitable system with this method. From the machine learning systems that we’ve programmed so far, all that turned out profitable used data from a longer price history.


Thank you for the great article, it’s exactly what I needed in order to start experimenting with ML in Zorro.


I’ve noticed that the results are slightly different each time despite using the random seed. Here it doesn’t matter thanks to the large number of trades but for example with daily bars the performance metrics fluctuate much more. My question is: do you happen to know from where does the randomness come? Is it still the training process in R despite the seed?


It is indeed so. Deepnet apparently uses also an internal function, not only the R random function, for randomizing some initial value.


any idea about how to use machine learning like in this example with indicators? you could do as better strategy 6.


would be very interesting.


Is it grid search inside the neural. train function allowed? I get error when I try it.


Besides Andy, how did you end up definining the LSTM structure using rnn? Is it not clear for me after reading inside the package.


where is the full code?(or where is the repository?)


You said” Use genetic optimization for determining the most important signals just by the most profitable results from the prediction process. Great for curve fitting” How about after using genetic optimization process for determining the most profitable signals , match and measure the most profitable signals with distance metrics/similarity analysis(mutual information, DTW, frechet distance algorithm etc…) then use the distance metrics/similarity analysis as function for neural network prediction? Does that make sense ?


Distance to what? To each other?


Yes find similar profitable signal-patterns in history and find distance between patterns/profitable signals then predict the behavior of the profitable signal in the future from past patterns.


Was wondering about this point you made in Step 5:


“Our target is the return of a trade with 3 bars life time.”


But in the code, doesn’t.


mean that we are actually predicting the SIGN of the return, rather than the return itself?


Sim. Only the binary win/loss result, but not the magnitude of the win or loss is used for the prediction.


“When you used almost 1 year’s data for training a system, it can obviously not deteriorate after a single day. Or if it did, and only produced positive test results with daily retraining, I would strongly suspect that the results are artifacts by some coding mistake.”


There is an additional trap to be aware of related to jcl’s comment above that applies to supervised machine learning techniques (where you train a model against actual outcomes). Assume you are trying to predict the return three bars ahead (as in the example above – LifeTime = 3;). In real time you obviously don’t have access to the outcomes for one, two and three bars ahead with which to retrain your model, but when using historical data you do. With frequently retrained models (especially if using relatively short blocks of training data) it is easy to train a model offline (and get impressive results) with data you will not have available for training in real time. Then reality kicks in. Therefore truncating your offline training set by N bars (where N is the number of bars ahead you are trying to predict) may well be advisable…


Amazing work, could you please share the WFO code as well. I was able to run the code till neural. save but unable to generate the WFO results.


Muito obrigado.


The code above does use WFO.


Dear jcl, in the text you mentioned that you could predict the current leg of zig-zag indicator, could you please elaborate on how to do that? what features and responses would you reccomend?


I would never claim that I could predict the current leg of zigzag indicator. But we have indeed coded a few systems that attempted that. For this, simply use not the current price movement, but the current zigzag slope as a training target. Which parameters you use for the features is completely up to you.


Bom trabalho. I was wondering if you ever tried using something like a net long-short ratio of the asset (I. e. the FXCM SSI index – real time live data) as a feature to improve prediction?


Not with the FXCM SSI index, since it is not available as historical data as far as I know. But similar data of other markets, such as order book content, COT report or the like, have been used as features to a machine learning system.


I see, thanks, and whats’s the experience on those? do they have any predictive power? if you know any materials on this, I would be very interested to read it. (fyi, the SSI index can be exported from FXCM Trading Station (daily data from 2003 for most currency pairs)


Thanks for the info with the SSI. Yes, additional market data can have predictive power, especially from the order book. But since we gathered this experience with contract work for clients, I’m not at liberty to disclose details. However we plan an own study with ML evaluation of additional data, and that might result in an article on this blog.


Thanks jcl, looking forward to it! there is a way to record SSI ratios in a CSV file from a LUA Strategy script (FXCM’s scripting language) for live evaluation. happy to give you some details if you decide to evaluate this. (drop me an email) MyFxbook also has a similar indicator, but no historical data on that one unfortunately.


Does random forest algorithm have any advantage over deep net or neural networks for classification problems in financial data? I make it more clear ; I use number of moving averages and oscillators slope colour change for trading decision(buy - sell-hold).Sometimes one oscillator colour change is lagging other is faster etc..There is no problem at picking tops and bottoms but It is quite challenging to know when to hold. Since random forest doesnt’ need normalization, do they have any advantage over deep net or neural networks for classification? Thanks.


This depends on the system and the features, so there is no general answer. In the systems we did so far, a random forest or single decision tree was sometimes indeed better than a standard neural network, but a deep network beats anything, especially since you need not care as much about feature preselection. We meanwhile do most ML systems with deep networks.


I see thank you. I have seen some new implementations of LSTM which sounds interesting. One is called phased LSTM another one is from Yarin Gaal. He is using Bayesian technique(gaussian process) as dropout cs. ox. ac. uk/people/yarin. gal/website/blog_2248.html.


I hooked up the news flow from forexfactory into this algo and predictive power has improved by 7%.


I downloaded forexfactory news history from 2010. Used a algo to convert that into a value of -1 to 1 for EUR. This value becomes another parameter into the neural training network. I think there is real value there …let me see if we can get the win ratio to 75% and then I thik we have a real winner on hands here. …..


The neural training somehow only yields results with EURUSD.


Anyone tried GBPUSD or EURJPY.


That’s also my experience. There are only a few asset types with which price pattern systems seem to really work, and that’s mainly EUR/USD and some cryptos. We also had pattern systems with GBP/USD und USD/JPY, but they work less well and need more complex algos. Most currencies don’t expose patterns at all.


JCL, you are saying “The R script is now controlled by the Zorro script (for this it must have the same name, NeuralLearn. r, only with different extension).”


…same name as what ? Shouldn’t it say DeepLearn. r (instead of NeuralLearn. r) ? Where is the name “NeuralLearn” coming from, we don’t seem to have used it anywhere else. Sorry I am not sure what I am missing here, could you please clarify?


That’s right, DeepLearn. r it is. That was a wrong name in the text. The files in the repository should be correctly named.


Thanks for your reply jcl, much appreciated.


I love your work. And I have got lots to learn.


Hope you don’t mind me asking another question …


Further down you are saying “The neural. save function stores the Models list – it now contains 2 models for long and for short trades – after every training run in Zorro’s Data folder”.


Again, I am not sure why, but I don’t seem to be able to locate that Models list file in the Data folder. In fact it does not seem to make any difference if the neural. save function is there or not. When I [Train] DeepLearn, only the files DeepLearn_EURUSD_x. ml and signals0.csv are being created regardless of whether the function exist or not.


The *.ml files contain the models list.


Do you have any experience with generative adversarial networks (GANs)?Are they suitable for financial time series ?


We have not yet done a GAN based system. AFAIK GANs are best suited for a different class of problems, not for trading, except maybe in special cases where no immediate success function is available.

No comments:

Post a Comment