Aprendizagem mecânica de previsão de divisas


Jon V.
BigData. Iniciantes. Negociação.
BigData. Iniciantes. Negociação.
Machine Beats Human: Usando Aprendizado de Máquinas em Forex.
A aprendizagem e o comércio de máquinas são um assunto muito interessante. Também é um assunto onde você pode gastar toneladas de tempo escrevendo código e lendo documentos e, em seguida, uma criança pode vencê-lo enquanto joga Mario Kart.
Nas postagens nexts, vamos falar sobre:
Otimize entradas e saídas. Isto e só isso pode fazer uma tonelada de diferença em seu rolo de banco. Calcule o tamanho da posição (no caso de você não gostar do critério de Kelly) Encontre a possível correlação entre diferentes pares (negociação em pares). Adoro a correlação EURUSD vs GBPJPY! Calcule suporte e amp; linhas de resistência.
Mas o que é a Aprendizagem de Máquinas?
Os algoritmos de aprendizagem de máquina são algoritmos em que uma máquina pode identificar padrões em seus dados. Yeap, é assim tão simples. Por exemplo, encontre todos os animais nesta foto e desenhe uma caixa ao redor deles. Além disso, nomeie esse animal. Louco, eu sei. Para negociar como você pode imaginar, é bastante semelhante:
Para que uma máquina "aprenda", você precisa ensinar o que é certo ou errado (aprendizado supervisionado) ou dar-lhe um grande conjunto de dados e deixá-lo ficar selvagem (sem supervisão). Para identificar objetos, isso é direto, e o que é negociar?
Eu olhei em volta para ver se há algum programa de aprendizado de máquina que pode identificar as linhas S / R, mas sem sucesso. Então eu decidi escrever o primeiro programa de aprendizagem de máquinas em python que identifica linhas de suporte e resistência em Python. Outro primeiro! Hooray!
Mas como um algoritmo pode identificar essas áreas? Hoooooow? Senhoras e colegas (e robôs), permitam-me que lhe apresente o MeanShift, um algoritmo sem supervisão que é usado principalmente para o reconhecimento de imagens e que é bastante trivial para configurar e executar (mas também muito lento).
A idéia é que este algoritmo me permita dividir meus dados (txs forex) em áreas e então eu posso usar as "bordas" como suporte e linhas de resistência. Ideia legal, mas isso funciona?
Analisamos cerca de 12 milhões de pontos de dados da EURUSD em 2018 e alguns meses de 2018. As linhas de resistência são colocadas automaticamente por um algoritmo de aprendizado de máquina.
O que é realmente legal (e assustador) é que o algoritmo praticamente o engana. NAILS é difícil. Isso fica realmente assustador quando vamos usar o algoritmo para identificar microestruturas e começar a curar.
O sistema é capaz de processar qualquer tipo de dados temporários (ações, forex, ouro, seja o que for) e renderá um gráfico interativo html (como o gráfico acima) com seus dados e a máquina gerada S / L. O código está aqui, então fique louco.
Agora vamos passar pelo código. Depois de ter seu conjunto de dados, você precisa lê-los e limpá-los. Prepare-se para alguns pandas de magia.
Nós deixamos cair os valores vazios (fins de semana) e depois reescrevemos os dados para candelas de 24 horas (ohcl). Isso torna muito mais fácil traçar. Os dados agrupados são os dados que inseriremos no algoritmo ml.
Em seguida, preparamos os dados que vamos usar no algo.
Na próxima publicação, vamos discutir como melhorar esse trabalho, discutir alguns resultados muito interessantes (o algoritmo pode realmente prever sobre o futuro?) E começar a usá-lo em nossa própria negociação. Se você quiser verificar o próximo artigo e ler mais sobre comércio e investimento usando algoritmos, inscreva-se no boletim informativo.
Próxima próxima: Machine Learning Gone Wild - Usando o código!
Se você tiver mais comentários, clique-me no jonromero ou inscreva-se no boletim informativo.
Legal outro. Este é um tutorial de engenharia sobre como construir uma plataforma algotrading para experimentação e FUN. Qualquer sugestão aqui não é um conselho financeiro. Se você perder qualquer (ou todos) o seu dinheiro porque seguiu quaisquer conselhos de negociação ou implantou este sistema na produção, não pode culpar este blog aleatório (e / ou eu). Aproveite a seu próprio risco.

Aprendizado de máquinas de previsão de divisas
Puxe pedidos 0.
Participe do GitHub hoje.
O GitHub é o lar de mais de 20 milhões de desenvolvedores que trabalham juntos para hospedar e rever o código, gerenciar projetos e criar software juntos.
Clone com HTTPS.
Use o Git ou o check-out com o SVN usando o URL da web.
Este é um exemplo que prevê preços futuros de movimentos de preços passados. Aqui o implementamos com taxa EUR / USD como exemplo, e você também pode prever os preços das ações mudando o símbolo.
Usando preços diários fechados de 2008 a 2018, primeiro 95% para treinamento e últimos 5% para testes. As linhas verticais verdes e vermelhas representam o comércio vencedor e a perda de comércio, respectivamente.
Para executar esta demo, você precisa do seguinte ambiente e bibliotecas.
Nota: você pode precisar de bibliotecas extras para instalar acima.
Licença MIT, Copyright (c) 2017.
&cópia de; 2018 GitHub, Inc. Termos Privacidade Segurança Status Ajuda.
Você não pode executar essa ação neste momento.
Você fez login com outra guia ou janela. Recarregue para atualizar sua sessão. Você se separou em outra guia ou janela. Recarregue para atualizar sua sessão.

Aprendizado de máquina e sua aplicação em mercados de Forex [MODELO DE TRABALHO]
Na última publicação, cobrimos o conceito de Aprendizado de Máquinas (ML) em breve. Nesta publicação, explicamos alguns mais termos ML e, em seguida, enquadramos regras para uma estratégia forex usando o algoritmo SVM em R.
Para usar o ML na negociação, começamos com dados históricos (estoque / dados forex) e adicionamos indicadores para construir um modelo em R / Python / Java. Em seguida, selecionamos o algoritmo de aprendizagem da máquina certo para fazer as previsões.
Primeiro, vejamos alguns dos termos relacionados ao ML.
Algoritmos de Aprendizagem de Máquina - Existem muitos algoritmos ML (lista de algoritmos) projetados para aprender e fazer previsões sobre os dados. Os algoritmos ML podem ser usados ​​para prever uma categoria (problema de classificação de tackle) ou para prever a direção e a magnitude (enfrentar o problema de regressão).
Prever o preço de uma ação em 3 meses, com base nos últimos resultados trimestrais da empresa. Prever se o Fed aumentará sua taxa de juros de referência.
Indicadores / Características - Os indicadores podem incluir indicadores técnicos (EMA, BBANDS, MACD, etc.), indicadores fundamentais ou indicadores macroeconômicos.
Exemplo 1 & # 8211; RSI (14), preço - SMA (50) e CCI (30). Podemos usar esses três indicadores, construir nosso modelo e usar um algoritmo ML adequado para prever valores futuros.
Exemplo 2 & # 8211; RSI (14), RSI (5), RSI (10), preço - SMA (50), preço - SMA (10), CCI (30), CCI (15), CCI (5)
Neste exemplo, selecionamos 8 indicadores. Alguns desses indicadores podem ser irrelevantes para o nosso modelo. Para selecionar o subconjunto certo de indicadores, utilizamos técnicas de seleção de características.
Seleção de recursos - É o processo de selecionar um subconjunto de recursos relevantes para uso no modelo. As técnicas de seleção de recursos são colocadas em 3 grandes categorias: métodos de filtragem, métodos baseados no Wrapper e métodos incorporados. Para selecionar o subconjunto certo, basicamente fazemos uso de um algoritmo ML em alguma combinação. Os recursos selecionados são conhecidos como preditores na aprendizagem em máquina.
Support Vector Machine (SVM) - O SVM é um algoritmo bem conhecido para o Aprendizado de Máquinas supervisionado e é usado para resolver problemas de classificação e regressão.
Um algoritmo SVM funciona nos pontos de dados rotulados e os separa através de um limite ou um Hyperplane. SVM tenta maximizar a margem em torno do hiperplano separador. Os vetores de suporte são os pontos de dados mais próximos da superfície de decisão.
Regras de enquadramento para uma estratégia forex usando SVM em R & # 8211; Dada a nossa compreensão de recursos e SVM, comecemos com o código em R. Selecionamos o par de moedas EUR / USD com um período de tempo de 1 hora que data de 2018. Os indicadores aqui utilizados são MACD (12, 26, 9), e Parabolic SAR com configurações padrão de (0.02, 0.2).
Primeiro, carregamos as bibliotecas necessárias em R e, em seguida, lemos os dados EUR / USD. Em seguida, calculamos MACD e Parabolic SAR usando suas respectivas funções disponíveis no pacote "TTR". Para calcular a tendência, subtravemos o preço de encerramento EUR / USD do valor SAR para cada ponto de dados. Nós atrasamos os valores dos indicadores para evitar o viés futuro. Nós também criamos uma classe Up / Down com base na mudança de preço.
Posteriormente, mesclamos os indicadores e a classe em um quadro de dados chamado dados do modelo. Os dados do modelo são então divididos em treinamento e dados de teste.
Em seguida, usamos a função SVM do pacote "e1071" e treinamos os dados. Fazemos previsões usando a função de previsão e também traçamos o padrão. Estamos obtendo uma precisão de 53% aqui.
Do enredo, vemos duas áreas distintas, uma área superior maior em vermelho, onde o algoritmo fez previsões curtas e a menor área menor em azul, onde foi longo.
O indicador SAR traça o preço à medida que a tendência se estende ao longo do tempo. A SAR está abaixo dos preços quando os preços estão subindo e acima dos preços quando os preços estão caindo. O SAR pára e inverte quando a tendência do preço reverte e quebra acima ou abaixo dele. Estamos interessados ​​no crossover de Price e SAR, e, portanto, estão tomando medidas de tendência como a diferença entre preço e SAR no código. Da mesma forma, estamos usando os valores do histograma MACD, que é a diferença entre os valores da linha MACD e da linha de sinal.
Olhando para o enredo, enquadramos nossas duas regras e avaliá-las sobre os dados do teste.
Regra curta = (Preço-SAR) & gt; -0,0025 & amp; (Preço - SAR) & lt; 0,0100 & amp; MACD & gt; -0,0010 & amp; MACD & lt; 0,0010.
Long rule = (Price-SAR) & gt; -0,0150 & amp; (Preço - SAR) & lt; -0,0050 & amp; MACD & gt; -0,0005.
Estamos obtendo uma precisão de 54% para nossos negócios curtos e uma precisão de 50% para nossos negócios longos. O algoritmo SVM parece estar fazendo um bom trabalho aqui. Paramos neste ponto e, na nossa próxima publicação na Aprendizagem da máquina, veremos como as regras emolduradas, como as descritas acima, podem ser codificadas e testadas para verificar a viabilidade de uma estratégia comercial.

Melhores estratégias 5: um sistema de aprendizado de máquina a curto prazo.
O tempo para a 5ª 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 da mineração de dados e da aprendizagem mecânica foram o tema da parte 4. Para o nosso exemplo de negociação a curto prazo, usaremos um algoritmo de aprendizado profundo, um autoencoderado empilhado, mas funcionará da mesma maneira com muitas outras máquinas algoritmos de aprendizagem. Com as ferramentas de software de hoje, apenas são necessárias 20 linhas de código para uma estratégia de aprendizado de máquina. Vou tentar explicar todas as etapas em detalhes.
Nosso exemplo será um projeto de pesquisa # 8211; um experimento de aprendizado de máquina para responder duas perguntas. Existe um algoritmo mais complexo & # 8211; tais como, mais neurônios e aprendizado mais profundo # 8211; produzir uma melhor previsão? E os movimentos de preços a curto prazo são previsíveis pelo histórico de preços de curto prazo? A última questão surgiu devido ao meu ceticismo sobre a negociação de ações de preços na parte anterior desta série. Recebi vários e-mails perguntando sobre os geradores do sistema de negociação & # 8220; & # 8221; ou ferramentas de ação de preços similares que são louvadas em alguns sites. Não há evidências concretas de que tais ferramentas tenham produzido algum lucro (exceto para os fornecedores) e # 8211; Mas isso significa que todos eles são lixo? Nós veremos.
Nosso experimento é simples: coletamos informações das últimas velas de uma curva de preços, alimente-as em uma rede neural de aprendizado profundo e use-a para prever as próximas velas. Minha hipótese é que algumas velas não contêm qualquer informação preditiva útil. Claro, um resultado não-prévio do experimento ganhou significa que eu tenho razão, pois eu poderia ter usado parâmetros errados ou preparado os dados mal. Mas um resultado preditivo seria uma dica de que eu não é correto e a negociação de ações de preços pode realmente ser lucrativa.
Desenvolvimento da estratégia de aprendizagem de máquinas.
Passo 1: a variável alvo.
Para recapitular a parte anterior: um algoritmo de aprendizagem supervisionado é treinado com um conjunto de recursos para prever uma variável alvo. Então, a primeira coisa a determinar é o que esta variável alvo deve ser. Um alvo popular, usado na maioria dos papéis, é o sinal do retorno do preço no próximo bar. Melhor adequado para a previsão, uma vez que menos suscetível à aleatoriedade, é a diferença de preço para um horizonte de previsão mais distante, como 3 barras a partir de agora, ou no mesmo dia da próxima semana. Como praticamente qualquer coisa nos sistemas comerciais, o horizonte de previsão é um compromisso entre os efeitos da aleatoriedade (menos barras são pior) e a previsibilidade (menos barras são melhores).
Às vezes, você não está interessado em prever diretamente o preço, mas na previsão de algum outro parâmetro # 8211; como a perna atual de um indicador de Zigzag & # 8211; que de outra forma só poderia ser determinado em retrospectiva. Ou você quer saber se uma certa ineficiência do mercado estará presente na próxima vez, especialmente quando você estiver usando o aprendizado automático da máquina não diretamente para negociação, mas para filtrar negócios em um sistema baseado em modelo. Ou você quer prever algo completamente diferente, por exemplo, a probabilidade de um acidente no mercado amanhã. Tudo isso geralmente é mais fácil de prever do que o retorno do futuro popular.
Em nosso experimento de ação de preço, usaremos o retorno de um comércio de ação de preço a curto prazo como variável alvo. Uma vez que o alvo é determinado, o próximo passo é selecionar os recursos.
Passo 2: os recursos.
Uma curva de preços é o pior caso para qualquer algoritmo de aprendizado de máquina. Não só carrega pouco sinal e principalmente ruído, também não é estacionário e a relação sinal / ruído muda o tempo todo. A proporção exata de sinal e ruído depende do significado do sinal & # 8220 ;, mas normalmente é muito baixo para qualquer algoritmo de aprendizagem de máquina conhecido para produzir qualquer coisa útil. Portanto, devemos derivar os recursos da curva de preços que contém mais sinal e menos ruído. O sinal, nesse contexto, é qualquer informação que possa ser usada para prever o alvo, seja lá o que for. O resto é ruído.
Assim, selecionar os recursos é crítico para o sucesso # 8211; muito mais crítico do que decidir qual algoritmo de aprendizagem de máquina que você vai usar. Existem duas abordagens para selecionar recursos. O primeiro e o mais comum é extrair toda a informação da curva de preços possível. Como você não sabe onde a informação está escondida, você apenas gera uma coleção selvagem de indicadores com uma ampla gama de parâmetros e espera que pelo menos alguns deles contenha a informação que o algoritmo precisa. Esta é a abordagem que você normalmente encontra na literatura. O problema deste método: qualquer algoritmo de aprendizagem de máquina é facilmente confundido por preditores não preditores. Então, ganhou apenas fazer 150 indicadores nela. Você precisa de algum algoritmo de pré-seleção que determine qual deles carrega informações úteis e que pode ser omitido. Sem reduzir os recursos dessa maneira até talvez oito ou dez, mesmo o algoritmo de aprendizado mais profundo não produziu nada útil.
A outra abordagem, normalmente para experiências e pesquisas, está usando apenas informações limitadas da curva de preços. Este é o caso aqui: uma vez que queremos examinar a negociação de ações de preço, usamos apenas os últimos preços como insumos e devemos descartar todo o resto da curva. Isso tem a vantagem de que não precisamos de nenhum algoritmo de pré-seleção, pois a quantidade de recursos está limitada de qualquer maneira. Aqui estão as duas funções de preditores simples que usamos em nossa experiência (em C):
As duas funções devem levar as informações necessárias para a ação de preço: movimento por percurso e volatilidade. A função de mudança é a diferença do preço atual ao preço de n barras antes, dividido pelo preço atual. A função de alcance é a distância total-baixa total das últimas n velas, também dividida pelo preço atual. E a função de escala centra e comprime os valores para o intervalo +/- 100, então nós os dividimos em 100 para obtê-los normalizados para +/- 1. Lembramos que a normalização é necessária para algoritmos de aprendizagem de máquina.
Etapa 3: preditores de pré-seleção / pré-processamento.
Quando você selecionou um grande número de indicadores ou outros sinais como recursos para seu algoritmo, você deve determinar qual deles é útil e qual não. Existem muitos métodos para reduzir o número de recursos, por exemplo:
Determine as correlações entre os sinais. Remova aqueles com uma forte correlação com outros sinais, uma vez que não contribuem para a informação. Compare o conteúdo de informação dos sinais diretamente, com algoritmos como entropia de informação ou árvores de decisão. Determine o conteúdo da informação indiretamente comparando os sinais com sinais randomizados; Existem algumas bibliotecas de software para isso, como o pacote R Boruta. Use um algoritmo como Análise de Componentes Principais (PCA) para gerar um novo conjunto de sinais com dimensionalidade reduzida. Use a otimização genética para determinar os sinais mais importantes apenas pelos resultados mais lucrativos do processo de previsão. Ótimo para ajuste de curva se você quiser publicar resultados impressionantes em um trabalho de pesquisa.
Para o nosso experimento, não precisamos pré-selecionar ou pré-processar os recursos, mas você pode encontrar informações úteis sobre isso nos artigos (1), (2) e (3) listados no final da página.
Etapa 4: selecione o algoritmo de aprendizagem da máquina.
R oferece muitos pacotes ML diferentes, e qualquer um deles oferece vários algoritmos diferentes com muitos parâmetros diferentes. Mesmo se você já decidiu sobre o método # 8211; aqui, aprendizado profundo & # 8211; você ainda escolheu diferentes abordagens e diferentes pacotes R. A maioria é bastante nova, e você não pode encontrar muitas informações empíricas que ajudem a sua decisão. Você deve tentar todos eles e ganhar experiência com diferentes métodos. Para a nossa experiência, escolhemos o pacote Deepnet, que provavelmente é a biblioteca de aprendizado profundo mais simples e fácil de usar. Isso mantém nosso código curto. Nós estamos usando o seu algoritmo SAE (Stacked Autoencoder) para pré-treinar a rede. A Deepnet também oferece uma Máquina Boltzmann Restrita (RBM) para pré-treinamento, mas não consegui obter bons resultados. Existem outros e mais complexos pacotes de aprendizagem profunda para R, para que você possa passar muito tempo examinando todos eles.
Como os trabalhos de pré-treinamento são facilmente explicados, mas porque funciona é uma questão diferente. Quanto ao meu conhecimento, ninguém já apresentou uma sólida prova matemática de que tudo funciona. De qualquer forma, imagine uma grande rede neural com muitas camadas ocultas:
Treinar a rede significa configurar os pesos de conexão entre os neurônios. O método usual é a alteração de erro de backpropagation. Mas resulta que as camadas mais escondidas que você tem, pior funciona. Os termos de erro de backpropagated ficam cada vez menores de camada para camada, fazendo com que as primeiras camadas da rede aprendam quase nada. O que significa que o resultado previsto se torna cada vez mais dependente do estado inicial aleatório dos pesos. Isso limitou severamente a complexidade das redes neurais baseadas em camadas e, portanto, as tarefas que elas podem resolver. Pelo menos até 10 anos atrás.
Em 2006, cientistas em Toronto publicaram pela primeira vez a idéia de pré-treinar os pesos com um algoritmo de aprendizado sem supervisão, uma máquina Boltzmann restrita. Isso resultou em um conceito revolucionário. Ele impulsionou o desenvolvimento da inteligência artificial e permitiu todo o tipo de novas aplicações das máquinas de jogar em direção aos carros auto-dirigidos. No caso de um autoencoder empilhado, funciona desta forma:
Selecione a camada oculta para treinar; comece com a primeira camada oculta. Conecte suas saídas a uma camada de saída temporária que tenha a mesma estrutura que a camada de entrada da rede. Alimente a rede com as amostras de treino, mas sem os alvos. Treine-o para que a primeira camada oculta reproduza o sinal de entrada & # 8211; as características & # 8211; nas suas saídas exatamente como possível. O resto da rede é ignorado. Durante o treino, aplique um termo de "pena de peso" & # 8217; de modo que, como poucos pesos de conexão possível, são usados ​​para reproduzir o sinal. Agora alimente as saídas da camada oculta treinada para as entradas da próxima camada oculta não treinada e repita o processo de treinamento para que o sinal de entrada seja agora reproduzido nas saídas da próxima camada. Repita esse processo até que todas as camadas ocultas sejam treinadas. Nós temos agora uma rede # 8216; esparsa & # 8217; com muito poucas conexões de camada que podem reproduzir os sinais de entrada. Agora, treine a rede com backpropagation para aprender a variável alvo, usando os pesos pré-treinados das camadas ocultas como ponto de partida.
A esperança é que o processo pré-treinamento não supervisionado produz uma abstração interna reduzida de ruído dos sinais de entrada que podem ser usados ​​para facilitar a aprendizagem do alvo. E isso realmente parece funcionar. Ninguém realmente sabe o porquê, mas várias teorias & # 8211; veja o papel (4) abaixo de & # 8211; tente explicar esse fenômeno.
Etapa 5: gere um conjunto de dados de teste.
Primeiro, precisamos produzir um conjunto de dados com recursos e metas para que possamos testar nosso processo de previsão e testar parâmetros. Os recursos devem basear-se nos mesmos dados de preço que na negociação ao vivo, e para o objetivo, devemos simular um comércio de curto prazo. Então, faz sentido gerar os dados não com R, mas com nossa plataforma de negociação, o que é de qualquer forma muito mais rápido. Aqui é um pequeno script Zorro para isso, DeepSignals. c:
Nós estamos gerando 2 anos de dados com recursos calculados pelas nossas funções de variação e alcance definidos acima. Nosso alvo é o resultado de um comércio com 3 bares de vida. Os custos de negociação são ajustados para zero, então, neste caso, o resultado é equivalente ao sinal da diferença de preço em 3 barras no futuro. A função advisLong é descrita no manual Zorro; é uma função poderosa que lida automaticamente com treinamento e previsão e permite usar qualquer algoritmo de aprendizagem de máquina baseado em R, como se fosse um indicador simples.
Em nosso código, a função usa o próximo retorno comercial como alvo e o preço muda e varia de 4 barras como recursos. A bandeira SIGNALS diz para não treinar os dados, mas para exportá-lo para um arquivo. csv. A bandeira BALANCED garante que recebemos tantos retornos positivos como negativos; Isso é importante para a maioria dos algoritmos de aprendizado de máquinas. Execute o script no modo [Trem] com nosso recurso de teste usual EUR / USD selecionado. Ele gera um arquivo de planilha denominado DeepSignalsEURUSD_L. csv que contém os recursos nas primeiras 8 colunas e o retorno comercial na última coluna.
Passo 6: Calibre o algoritmo.
Algoritmos complexos de aprendizagem de máquinas têm muitos parâmetros a serem ajustados. Alguns oferecem ótimas oportunidades para ajustar o algoritmo para as publicações. Ainda assim, devemos calibrar parâmetros, já que o algoritmo raramente funciona bem com suas configurações padrão. Para isso, aqui é um script R que lê o conjunto de dados criado anteriormente e o processa com o algoritmo de aprendizagem profunda (DeepSignal. r):
Nós definimos três funções neural. train, neural. predict e neural. init para treinamento, previsão e inicialização da rede neural. Os nomes das funções não são arbitrários, mas seguem a convenção utilizada pela função Zorro & # 8217; aconselho (NEURAL.). Não importa agora, mas importará mais tarde quando usarmos o mesmo roteiro R para treinar e negociar a estratégia de aprendizado profundo. Uma quarta função, TestOOS, é usada para testes fora da amostra, nossa configuração.
A função neural. init soma o gerador aleatório R com um valor fixo (365 é o meu número pessoal de sorte). Caso contrário, obteríamos um resultado ligeiramente diferente sempre que a rede neural fosse inicializada com pesos aleatórios. Ele também cria uma lista R global chamada & # 8220; Models & # 8221 ;. A maioria dos tipos de variáveis ​​R não precisam ser criados de antemão, alguns fazem (não me perguntem por que). O & # 8216; & lt; & lt; - & # 8216; O operador é para acessar uma variável global dentro de uma função.
A função neural. train leva como entrada um número de modelo e o conjunto de dados a ser treinado. O número do modelo identifica o modelo treinado no & # 8220; Modelos & # 8221; Lista. Uma lista não é realmente necessária para este teste, mas precisamos disso para estratégias mais complexas que treinem mais do que um modelo. A matriz que contém os recursos e o alvo é passada para a função como segundo parâmetro. Se os dados XY não forem uma matriz adequada, o que freqüentemente acontece em R dependendo de como você o gerou, ele é convertido em um. Em seguida, ele é dividido em características (X) e o alvo (Y) e, finalmente, o alvo é convertido em 1 para um resultado comercial positivo e 0 para um resultado negativo.
Os parâmetros de rede são então configurados. Alguns são óbvios, outros são livres para brincar com:
A estrutura de rede é dada pelo vetor oculto: c (50,100,50) define 3 camadas ocultas, a primeira com 50, a segunda com 100 e a terceira com 50 neurônios. Esse é o parâmetro que mais tarde modificaremos para determinar se mais profundo é melhor. A função de ativação converte a soma dos valores de entrada do neurônio para a saída do neurônio; mais frequentemente utilizados são sigmoides que satura para 0 ou 1, ou tanh que satura para -1 ou +1.
Usamos tanh aqui, pois nossos sinais também estão no intervalo +/- 1. A saída da rede é uma função sigmoide, pois queremos uma predição na faixa 0..1. Mas a saída SAE deve ser & # 8220; linear & # 8221; de modo que o Autocodificador Empilhado possa reproduzir os sinais de entrada analógicos nas saídas.
A taxa de aprendizagem controla o tamanho do passo para a descida do gradiente no treinamento; uma taxa mais baixa significa passos mais finos e possivelmente uma previsão mais precisa, mas um tempo de treinamento mais longo. Momentum adiciona uma fração do passo anterior ao atual. Isso impede que a descida do gradiente fique presa em um mínimo mínimo local ou ponto de sela. A escala da taxa de aprendizado é um fator de multiplicação para mudar a taxa de aprendizagem após cada iteração (não tenho certeza do que é bom, mas pode haver tarefas em que uma menor taxa de aprendizado em épocas superiores melhora o treinamento). Uma época é uma iteração de treinamento em todo o conjunto de dados. O treinamento irá parar uma vez que o número de épocas seja atingido. Mais épocas significam uma melhor previsão, mas um treinamento mais longo. O tamanho do lote é uma série de amostras aleatórias e # 8211; um mini lote & # 8211; retirado do conjunto de dados para uma única corrida de treinamento. A divisão dos dados em mini lotes acelera o treinamento, pois o gradiente de peso é calculado a partir de menos amostras. Quanto maior o tamanho do lote, melhor é o treinamento, mas o tempo será mais longo. O abandono é uma série de neurônios selecionados aleatoriamente que são desativados durante um mini lote. Desta forma, a rede aprende apenas com uma parte de seus neurônios. Isso parece uma idéia estranha, mas pode efetivamente reduzir a superposição.
Todos esses parâmetros são comuns para redes neurais. Jogue com eles e verifique seu efeito no resultado e no tempo de treinamento. A calibração adequada de uma rede neural não é trivial e pode ser o tema de outro artigo. Os parâmetros são armazenados no modelo juntamente com a matriz de pesos de conexão treinados. Portanto, eles não precisam ser devolvidos novamente na função de predição, neural. predict. Leva o modelo e um vetor X de recursos, o executa através das camadas e retorna a saída de rede, o destino previsto Y. Em comparação com o treinamento, a previsão é bastante rápida, pois só precisa de um par de mil multiplicações. Se X era um vetor de linha, ele era transposto e, assim, convertido em um vetor de coluna, caso contrário, a função nn. predict não aceitou.
Use RStudio ou algum ambiente semelhante para trabalhar convenientemente com R. Edite o caminho para os dados. csv no arquivo acima, crie-o, instale os pacotes R necessários (deepnet, e1071 e caret) e, em seguida, chame a função TestOOS do comando linha. Se tudo funcionar, ele deve imprimir algo assim:
O TestOOS lê primeiro nosso conjunto de dados da pasta de dados do Zorro & # 8217; s. Ele divide os dados em 80% para treinamento (XY. tr) e 20% para testes fora da amostra (XY. ts). O conjunto de treinamento é treinado eo resultado armazenado na lista de Modelos no índice 1. O conjunto de teste é dividido em recursos (X) e em alvos (Y). Y é convertido em binário 0 ou 1 e armazenado em Y. ob, nosso vetor de alvos observados. Então, preveemos os alvos do conjunto de teste, convertamos-os novamente para 0 ou 1 binário e armazená-los em Y. pr. Para comparar a observação com a predição, usamos a função confusionMatrix do pacote de caret.
Uma matriz de confusão de um classificador binário é simplesmente uma matriz 2 & # 215; 2 que diz quantos 0 e # 8217; s e quantos 1 & # 8217; s foram preditos erroneamente e corretamente. Muitas métricas são derivadas da matriz e impressas nas linhas acima. O mais importante no momento é a precisão de previsão de 62%. Isso pode sugerir que eu baixei a ação de preço um pouco prematuramente. Mas é claro que os 62% podem ter sido apenas sorte. Nós veremos isso mais tarde quando executarmos um teste WFO.
Um conselho final: os pacotes R são ocasionalmente atualizados, com a conseqüência possível de que o código R anterior de repente possa funcionar de forma diferente ou não. Isso realmente acontece, então, teste cuidadosamente após qualquer atualização.
Passo 7: a estratégia.
Agora que nós testamos nosso algoritmo e obtivemos uma precisão de previsão superior a 50% com um conjunto de dados de teste, podemos finalmente codificar nossa estratégia de aprendizagem de máquinas. Na verdade, nós já codificamos a maior parte, precisamos adicionar algumas linhas ao script Zorro acima que exportou o conjunto de dados. Este é o roteiro final para treinar, testar e (teoricamente) negociar o sistema (DeepLearn. c):
Nós estamos usando um ciclo WFO de um ano, dividido em 90% de treinamento e um período de teste de 10% fora de amostra. Você pode perguntar por que eu usei anteriormente os dados de dois anos e uma divisão diferente, 80/20, para calibrar a rede no passo 5. Isso é para usar dados compostos de forma diferente para calibração e para testes avançados. Se usássemos exatamente os mesmos dados, a calibração pode superá-lo e comprometer o teste.
Os parâmetros WFO selecionados significam que o sistema é treinado com cerca de 225 dias de dados, seguido por um período de 25 dias de teste ou comércio. Assim, na negociação ao vivo, o sistema treinaria a cada 25 dias, usando os preços dos 225 dias anteriores. Na literatura, às vezes, você encontra a recomendação de treinar um sistema de aprendizado da máquina após qualquer troca, ou pelo menos qualquer dia. Mas isso não faz muito sentido para mim. Quando você usou quase 1 ano de dados para treinar um sistema, obviamente não pode deteriorar-se após um único dia. Ou se isso acontecesse, e apenas produziu resultados de testes positivos com a reciclagem diária, eu suspeitaria fortemente que os resultados são artefatos por algum erro de codificação.
Treinar uma rede profunda leva muito tempo, no nosso caso cerca de 10 minutos para uma rede com 3 camadas ocultas e 200 neurônios. Na negociação ao vivo, isso seria feito por um segundo processo Zorro que é iniciado automaticamente pelo Zorro comercial. No backtest, o sistema treina em qualquer ciclo WFO. Portanto, usar múltiplos núcleos é recomendado para treinar muitos ciclos em paralelo. A variável NumCores em -1 ativa todos os núcleos da CPU, mas um. Múltiplos núcleos só estão disponíveis no Zorro S, então um teste completo para a frente com todos os ciclos WFO pode demorar várias horas com a versão gratuita.
No roteiro, agora treinamos trocas longas e curtas. Para isso, temos que permitir a cobertura no modo Treinamento, pois as posições longas e curtas estão abertas ao mesmo tempo. A entrada de uma posição agora depende do valor de retorno da função de aviso, que, por sua vez, chama o neural. train ou a função neural. predict do script R. Portanto, estamos aqui entrando em posições quando a rede neural prevê um resultado acima de 0,5.
O script R agora é controlado pelo script Zorro (para isso, ele deve ter o mesmo nome, NeuralLearn. r, apenas com extensão diferente). É idêntico ao nosso script R acima, pois usamos os mesmos parâmetros de rede. É necessária apenas uma função adicional para suportar um teste WFO:
A função neural. save armazena a lista Modelos & # 8211; agora contém 2 modelos por longo e para trades curtos e # 8211; Após cada treinamento executado na pasta de dados do Zorro & # 8217; s. Uma vez que os modelos são armazenados para uso posterior, não precisamos treiná-los novamente para testes de teste repetidos.
Esta é a curva de equidade WFO gerada com o script acima (EUR / USD, sem custos de negociação):
Curva de capital EUR / USD com estrutura de rede 50-100-50.
Embora nem todos os ciclos WFO tenham um resultado positivo, parece que há algum efeito preditivo. A curva é equivalente a um retorno anual de 89%, alcançado com uma estrutura de camada oculta 50-100-50. Nós verificaremos no próximo passo como diferentes estruturas de rede afetam o resultado.
Uma vez que as funções neural. init, neural. train, neural. predict e neural. save são chamadas automaticamente pelas funções de recomendarLong / adviseShort do Zorro & # 8217; não há funções R diretamente chamadas no script Zorro. Assim, o script pode permanecer inalterado ao usar um método de aprendizado de máquina diferente. Somente o script DeepLearn. r deve ser modificado e a rede neural, por exemplo, é substituída por uma máquina vetorial de suporte. Para comercializar um sistema de aprendizagem de máquina ao vivo em um VPS, verifique se R também está instalado no VPS, os pacotes R necessários estão instalados e o caminho para o terminal R configurado no arquivo ini do Zorro & # 8217; s. Caso contrário, você receberá uma mensagem de erro ao iniciar a estratégia.
Passo 8: o experimento.
Se nosso objetivo estivesse desenvolvendo uma estratégia, os próximos passos seriam o controle de realidade, o gerenciamento de riscos e dinheiro e a preparação para negociação ao vivo, tal como descrito no desenvolvimento de estratégias baseadas em modelo. Mas, para o nosso experimento, agora executamos uma série de testes, com o número de neurônios por camada aumentados de 10 a 100 em 3 etapas e 1, 2 ou 3 camadas ocultas (deepnet não suporta mais de 3) . Então, estamos olhando para as seguintes 9 estruturas de rede: 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). Para esta experiência, você precisa de uma tarde, mesmo com um PC rápido e no modo de múltiplos núcleos. Aqui estão os resultados (SR = razão de Sharpe, R2 = linearidade da inclinação):
Nós vemos que uma rede simples com apenas 10 neurônios em uma única camada escondida ganhou n "o trabalho correto para predição de curto prazo. A complexidade da rede melhora claramente o desempenho, no entanto, até certo ponto. Um bom resultado para o nosso sistema já foi alcançado com 3 camadas x 30 neurônios. Ainda mais neurônios não ajudaram muito e, às vezes, produzem um resultado pior. Esta não é uma surpresa real, uma vez que, para processar apenas 8 entradas, 300 neurônios provavelmente não podem fazer um trabalho melhor do que 100.
Conclusão.
Nosso objetivo era determinar se algumas velas podem ter poder preditivo e como os resultados são afetados pela complexidade do algoritmo. Os resultados parecem sugerir que os movimentos de preços a curto prazo podem, de fato, ser previstos às vezes, analisando as mudanças e os intervalos das últimas 4 velas. A previsão não é muito precisa & # 8211; está na faixa de 58% .. 60%, e a maioria dos sistemas da série de testes tornam-se não lucrativos quando os custos de negociação estão incluídos. Ainda assim, tenho que reconsiderar a minha opinião sobre a negociação de ações de preço. O fato de que a previsão melhora com a complexidade da rede é um argumento especialmente convincente para a previsibilidade de preços a curto prazo.
Seria interessante analisar a estabilidade a longo prazo dos padrões de preços preditivos. Para isso, tivemos que executar outra série de experiências e modificar o período de treinamento (WFOPeriod no script acima) e a divisão 90% IS / OOS. Isso leva mais tempo, pois devemos usar mais dados históricos. Eu fiz alguns testes e descobriu até agora que um ano parece ser realmente um bom período de treinamento. O sistema deteriora-se com períodos superiores a alguns anos. Os padrões de preços preditivos, pelo menos de EUR / USD, têm uma vida útil limitada.
onde podemos ir a partir daqui? Há uma infinidade de possibilidades, por exemplo:
Use entradas de mais velas e processe-as com redes muito maiores com milhares de neurônios. Use oversampling para expandir os dados de treinamento. A previsão sempre melhora com mais amostras de treinamento. Compressar séries temporais f. i. com análise de espectro e não analise as velas, mas a sua representação de frequência com métodos de aprendizagem de máquinas. Use entradas de muitas velas & # 8211; como, 100 & # 8211; e pré-processar velas adjacentes com camadas de rede convolucional unidimensionais. Use redes recorrentes. Especialmente LSTM poderia ser muito interessante para analisar séries temporais e # 8211; e quanto ao meu conhecimento, eles raramente foram usados ​​para previsão financeira até agora. Use um conjunto de redes neurais para predição, como Aronson & # 8217; s & # 8220; oráculos & # 8221; e & # 8220; comitees & # 8221 ;.
Artigos / Artigos.
(3) V. Perervenko, Seleção de Variáveis ​​para Aprendizado de Máquinas.
Eu acrescentei os scripts C e R ao repositório de script 2018. Você precisa de ambos na pasta Estratégia Zorro & # 8217; s. A versão Zorro 1.474 e a versão R 3.2.5 (64 bits) foram usadas para o experimento, mas também devem funcionar com outras versões.
69 pensamentos sobre & ldquo; Better Strategies 5: A Short-term Machine Learning System & rdquo;
Eu testei sua estratégia usando dados AAPL de 30min, mas # 8220; sae. dnn. train & # 8221; Retorna todo o NaN no treino.
(Isso funciona apenas diminuindo os neurônios para menos de (5,10,5) e # 8230, mas a precisão é de 49%)
Você pode me ajudar a entender o porquê?
Desde já, obrigado.
Se você não alterou nenhum parâmetro SAE, examine os dados. csv. É então a única diferença para o teste EUR / USD. Talvez algo esteja errado com isso.
Outro artigo fantástico, jcl. Zorro é um ambiente notável para esses experimentos. Obrigado por compartilhar seu código e sua abordagem & # 8211; Isso realmente abre um número incrível de possibilidades para qualquer pessoa disposta a investir o tempo para aprender a usar o Zorro.
O problema com os dados AAPL 30min foi relacionado ao método de normalização que usei (X-mean / SD).
O intervalo de recursos não foi entre -1: 1 e eu suponho que sae. dnn precisa dele para funcionar & # 8230;
De qualquer modo, as performances não são comparáveis ​​às suas 🙂
Eu tenho uma pergunta:
Por que você usa o Zorro para criar os recursos no arquivo csv e depois abri-lo em R?
Por que não criar o arquivo com todos os recursos em R em algumas linhas e fazer o treinamento no arquivo quando você já estiver em R? em vez de entrar dentro do Zorro e depois para R.
Quando você deseja que R crie os recursos, você ainda deve transmitir os dados de preço e os alvos de Zorro para R. Então você não está ganhando muito. Criando os recursos nos resultados Zorro geralmente em código mais curto e treinamento mais rápido. Os recursos em R só fazem sentido quando você precisa de algum pacote R para calculá-los.
Artigo realmente útil e interessante! Gostaria de saber se existe alguma versão em inglês do livro:
& # 8220; Das Börsenhackerbuch: Finanziell unabhängig durch algorithmische Handelssysteme & # 8221;
Estou realmente interessado nisso,
Ainda não, mas uma versão em inglês está planejada.
Obrigado JCL! Por favor, deixe-me agora quando a versão em inglês estiver pronta, porque estou muito interessada nisso.
Funciona soberbamente (como sempre). Muito Obrigado. Uma pequena nota, se você tiver o pacote & # 8220; dlm & # 8221; carregado em R, TestOOS falhará com erro: & # 8220; Erro no TestOOS (): não é possível alterar o valor da ligação bloqueada para & # 8216; X '& # 8221 ;. Isto é devido a uma função X no pacote dlm, então o nome está bloqueado quando o pacote é carregado. Facilmente corrigido, renomeando as ocorrências da variável X para outra coisa ou destacando temporariamente o pacote dlm com: separar (& # 8220; pacote: dlm & # 8221 ;, descarregar = VERDADEIRO)
Obrigado pela informação com o pacote dlm. Eu admito que & # 8216; X & # 8217; não é um nome bom particular para uma variável, mas uma função chamada & # 8216; X & # 8217; em um pacote distribuído é mesmo um pouco pior.
Os resultados abaixo foram gerados pela versão revisada do DeepSignals. r & # 8211; A única mudança foi o uso de LSTM net do pacote rnn no CRAN. Os autores do pacote consideram sua implementação LSTM como & # 8220; experimental & # 8221; 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.2018-07.06.2018 (12486 bars)
Test period 04.05.2018-07.06.2018 (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 2018.
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 https://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.2018-02.11.2018.
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.2018-09.09.2018 (14075 bars)
Test period 23.04.2018-09.09.2018 (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 2018.
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. Thanks for your contribution.
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.2018-27.01.2017 (16460 bars)
Test period 22.04.2018-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 2018.
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 2018. 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.

Better Strategies 4: Machine Learning.
Deep Blue was the first computer that won a chess world championship. That was 1996, and it took 20 years until another program, AlphaGo , could defeat the best human Go player. Deep Blue was a model based system with hardwired chess rules. AlphaGo is a data-mining system, a deep neural network trained with thousands of Go games. Not improved hardware, but a breakthrough in software was essential for the step from beating top Chess players to beating top Go players.
In this 4th part of the mini-series we’ll look into the data mining approach for developing trading strategies. This method does not care about market mechanisms. It just scans price curves or other data sources for predictive patterns. Machine learning or “Artificial Intelligence” is not always involved in data-mining strategies. In fact the most popular – and surprisingly profitable – data mining method works without any fancy neural networks or support vector machines.
Machine learning principles.
A learning algorithm is fed with data samples , normally derived in some way from historical prices. Each sample consists of n variables x 1 .. x n , commonly named predictors , features , signals , or simply input . These predictors can be the price returns of the last n bars, or a collection of classical indicators, or any other imaginable functions of the price curve (I’ve even seen the pixels of a price chart image used as predictors for a neural network!). Each sample also normally includes a target variable y , like the return of the next trade after taking the sample, or the next price movement. In the literature you can find y also named label or objective . In a training process , the algorithm learns to predict the target y from the predictors x 1 .. x n . The learned ‘memory’ is stored in a data structure named model that is specific to the algorithm (not to be confused with a financial model for model based strategies!). A machine learning model can be a function with prediction rules in C code, generated by the training process. Or it can be a set of connection weights of a neural network.
The predictors, features, or whatever you call them, must carry information sufficient to predict the target y with some accuracy. They m ust also often fulfill two formal requirements. First, all predictor values should be in the same range, like -1 .. +1 (for most R algorithms) or -100 .. +100 (for Zorro or TSSB algorithms). So you need to normalize them in some way before sending them to the machine. Second, the samples should be balanced , i. e. equally distributed over all values of the target variable. So there should be about as many winning as losing samples. If you do not observe these two requirements, you’ll wonder why you’re getting bad results from the machine learning algorithm.
Regression algorithms predict a numeric value, like the magnitude and sign of the next price move. Classification algorithms predict a qualitative sample class, for instance whether it’s preceding a win or a loss. Some algorithms, such as neural networks, decision trees, or support vector machines, can be run in both modes.
A few algorithms learn to divide samples into classes without needing any target y . That’s unsupervised learning , as opposed to supervised learning using a target. Somewhere inbetween is reinforcement learning , where the system trains itself by running simulations with the given features, and using the outcome as training target. AlphaZero, the successor of AlphaGo, used reinforcement learning by playing millions of Go games against itself. In finance there are few applications for unsupervised or reinforcement learning. 99% of machine learning strategies use supervised learning.
Whatever signals we’re using for predictors in finance, they will most likely contain much noise and little information, and will be nonstationary on top of it. Therefore financial prediction is one of the hardest tasks in machine learning. More complex algorithms do not necessarily achieve better results. The selection of the predictors is critical to the success. It is no good idea to use lots of predictors, since this simply causes overfitting and failure in out of sample operation. Therefore data mining strategies often apply a preselection algorithm that determines a small number of predictors out of a pool of many. The preselection can be based on correlation between predictors, on significance, on information content, or simply on prediction success with a test set. Practical experiments with feature selection can be found in a recent article on the Robot Wealth blog.
Here’s a list of the most popular data mining methods used in finance.
1. Indicator soup.
Most trading systems we’re programming for clients are not based on a financial model. The client just wanted trade signals from certain technical indicators, filtered with other technical indicators in combination with more technical indicators. When asked how this hodgepodge of indicators could be a profitable strategy, he normally answered: “Trust me. I’m trading it manually, and it works.”
It did indeed. At least sometimes. Although most of those systems did not pass a WFA test (and some not even a simple backtest), a surprisingly large number did. And those were also often profitable in real trading. The client had systematically experimented with technical indicators until he found a combination that worked in live trading with certain assets. This way of trial-and-error technical analysis is a classical data mining approach, just executed by a human and not by a machine. I can not really recommend this method – and a lot of luck, not to speak of money, is probably involved – but I can testify that it sometimes leads to profitable systems.
2. Candle patterns.
Not to be confused with those Japanese Candle Patterns that had their best-before date long, long ago. The modern equivalent is price action trading . You’re still looking at the open, high, low, and close of candles. You’re still hoping to find a pattern that predicts a price direction. But you’re now data mining contemporary price curves for collecting those patterns. There are software packages for that purpose. They search for patterns that are profitable by some user-defined criterion, and use them to build a specific pattern detection function. It could look like this one (from Zorro’s pattern analyzer):
This C function returns 1 when the signals match one of the patterns, otherwise 0. You can see from the lengthy code that this is not the fastest way to detect patterns. A better method, used by Zorro when the detection function needs not be exported, is sorting the signals by their magnitude and checking the sort order. An example of such a system can be found here.
Can price action trading really work? Just like the indicator soup, it’s not based on any rational financial model. One can at best imagine that sequences of price movements cause market participants to react in a certain way, this way establishing a temporary predictive pattern. However the number of patterns is quite limited when you only look at sequences of a few adjacent candles. The next step is comparing candles that are not adjacent, but arbitrarily selected within a longer time period. This way you’re getting an almost unlimited number of patterns – but at the cost of finally leaving the realm of the rational. It is hard to imagine how a price move can be predicted by some candle patterns from weeks ago.
Still, a lot effort is going into that. A fellow blogger, Daniel Fernandez, runs a subscription website (Asirikuy) specialized on data mining candle patterns. He refined pattern trading down to the smallest details, and if anyone would ever achieve any profit this way, it would be him. But to his subscribers’ disappointment, trading his patterns live (QuriQuant) produced very different results than his wonderful backtests. If profitable price action systems really exist, apparently no one has found them yet.
3. Linear regression.
The simple basis of many complex machine learning algorithms: Predict the target variable y by a linear combination of the predictors x 1 .. x n .
The coefficients a n are the model. They are calculated for minimizing the sum of squared differences between the true y values from the training samples and their predicted y from the above formula:
For normal distributed samples, the minimizing is possible with some matrix arithmetic, so no iterations are required. In the case n = 1 – with only one predictor variable x – the regression formula is reduced to.
which is simple linear regression , as opposed to multivariate linear regression where n > 1. Simple linear regression is available in most trading platforms, f. i. with the LinReg indicator in the TA-Lib. With y = price and x = time it’s often used as an alternative to a moving average. Multivariate linear regression is available in the R platform through the lm(..) function that comes with the standard installation. A variant is polynomial regression . Like simple regression it uses only one predictor variable x , but also its square and higher degrees, so that x n == x n :
With n = 2 or n = 3 , polynomial regression is often used to predict the next average price from the smoothed prices of the last bars. The polyfit function of MatLab, R, Zorro, and many other platforms can be used for polynomial regression.
4. Perceptron.
Often referred to as a neural network with only one neuron. In fact a perceptron is a regression function like above, but with a binary result, thus called logistic regression . It’s not regression though, it’s a classification algorithm. Zorro’s advise(PERCEPTRON, …) function generates C code that returns either 100 or -100, dependent on whether the predicted result is above a threshold or not:
You can see that the sig array is equivalent to the features x n in the regression formula, and the numeric factors are the coefficients a n .
5. N eural networks.
Linear or logistic regression can only solve linear problems. Many do not fall into this category – a famous example is predicting the output of a simple XOR function. And most likely also predicting prices or trade returns. An artificial neural network (ANN) can tackle nonlinear problems. It’s a bunch of perceptrons that are connected together in an array of layers . Any perceptron is a neuron of the net. Its output goes to the inputs of all neurons of the next layer, like this:
Like the perceptron, a neural network also learns by determining the coefficients that minimize the error between sample prediction and sample target. But this requires now an approximation process, normally with backpropagating the error from the output to the inputs, optimizing the weights on its way. This process imposes two restrictions. First, the neuron outputs must now be continuously differentiable functions instead of the simple perceptron threshold. Second, the network must not be too deep – it must not have too many ‘hidden layers’ of neurons between inputs and output. This second restriction limits the complexity of problems that a standard neural network can solve.
When using a neural network for predicting trades, you have a lot of parameters with which you can play around and, if you’re not careful, produce a lot of selection bias :
Number of hidden layers Number of neurons per hidden layer Number of backpropagation cycles, named epochs Learning rate, the step width of an epoch Momentum, an inertia factor for the weights adaption Activation function.
The activation function emulates the perceptron threshold. For the backpropagation you need a continuously differentiable function that generates a ‘soft’ step at a certain x value. Normally a sigmoid , tanh , or softmax function is used. Sometimes it’s also a linear function that just returns the weighted sum of all inputs. In this case the network can be used for regression, for predicting a numeric value instead of a binary outcome.
Neural networks are available in the standard R installation ( nnet , a single hidden layer network) and in many packages, for instance RSNNS and FCNN4R .
6. Deep learning.
Deep learning methods use neural networks with many hidden layers and thousands of neurons, which could not be effectively trained anymore by conventional backpropagation. Several methods became popular in the last years for training such huge networks. They usually pre-train the hidden neuron layers for achieving a more effective learning process. A Restricted Boltzmann Machine ( RBM ) is an unsupervised classification algorithm with a special network structure that has no connections between the hidden neurons. A Sparse Autoencoder ( SAE ) uses a conventional network structure, but pre-trains the hidden layers in a clever way by reproducing the input signals on the layer outputs with as few active connections as possible. Those methods allow very complex networks for tackling very complex learning tasks. Such as beating the world’s best human Go player.
Deep learning networks are available in the deepnet and darch R packages. Deepnet provides an autoencoder, Darch a restricted Boltzmann machine. I have not yet experimented with Darch, but here’s an example R script using the Deepnet autoencoder with 3 hidden layers for trade signals through Zorro’s neural() function:
7. Support vector machines.
Like a neural network, a support vector machine (SVM) is another extension of linear regression. When we look at the regression formula again,
we can interpret the features x n as coordinates of a n - dimensional feature space . Setting the target variable y to a fixed value determines a plane in that space, called a hyperplane since it has more than two (in fact, n-1 ) dimensions. The hyperplane separates the samples with y > o from the samples with y < 0 . The a n coefficients can be calculated in a way that the distances of the plane to the nearest samples – which are called the ‘support vectors’ of the plane, hence the algorithm name – is maximum. This way we have a binary classifier with optimal separation of winning and losing samples.
The problem: normally those samples are not linearly separable – they are scattered around irregularly in the feature space. No flat plane can be squeezed between winners and losers. If it could, we had simpler methods to calculate that plane, f. i. linear discriminant analysis . But for the common case we need the SVM trick: Adding more dimensions to the feature space. For this the SVM algorithm produces more features with a kernel function that combines any two existing predictors to a new feature. This is analogous to the step above from the simple regression to polynomial regression, where also more features are added by taking the sole predictor to the n-th power. The more dimensions you add, the easier it is to separate the samples with a flat hyperplane. This plane is then transformed back to the original n-dimensional space, getting wrinkled and crumpled on the way. By clever selecting the kernel function, the process can be performed without actually computing the transformation.
Like neural networks, SVMs can be used not only for classification, but also for regression. They also offer some parameters for optimizing and possibly overfitting the prediction process:
Kernel function. You normally use a RBF kernel (radial basis function, a symmetric kernel), but you also have the choice of other kernels, such as sigmoid, polynomial, and linear. Gamma, the width of the RBF kernel Cost parameter C, the ‘penalty’ for wrong classifications in the training samples.
An often used SVM is the libsvm library. It’s also available in R in the e1071 package. In the next and final part of this series I plan to describe a trading strategy using this SVM.
8. K-Nearest neighbor.
Compared with the heavy ANN and SVM stuff, that’s a nice simple algorithm with a unique property: It needs no training. So the samples are the model. You could use this algorithm for a trading system that learns permanently by simply adding more and more samples. The nearest neighbor algorithm computes the distances in feature space from the current feature values to the k nearest samples. A distance in n-dimensional space between two feature sets (x 1 .. x n ) and (y 1 .. y n ) is calculated just as in 2 dimensions:
The algorithm simply predicts the target from the average of the k target variables of the nearest samples, weighted by their inverse distances. It can be used for classification as well as for regression. Software tricks borrowed from computer graphics, such as an adaptive binary tree (ABT), can make the nearest neighbor search pretty fast. In my past life as computer game programmer, we used such methods in games for tasks like self-learning enemy intelligence. You can call the knn function in R for nearest neighbor prediction – or write a simple function in C for that purpose.
This is an approximation algorithm for unsupervised classification. It has some similarity, not only its name, to k-nearest neighbor. For classifying the samples, the algorithm first places k random points in the feature space. Then it assigns to any of those points all the samples with the smallest distances to it. The point is then moved to the mean of these nearest samples. This will generate a new samples assignment, since some samples are now closer to another point. The process is repeated until the assignment does not change anymore by moving the points, i. e. each point lies exactly at the mean of its nearest samples. We now have k classes of samples, each in the neighborhood of one of the k points.
This simple algorithm can produce surprisingly good results. In R, the kmeans function does the trick. An example of the k-means algorithm for classifying candle patterns can be found here: Unsupervised candlestick classification for fun and profit.
10. Naive Bayes.
This algorithm uses Bayes’ Theorem for classifying samples of non-numeric features (i. e. events ), such as the above mentioned candle patterns . Suppose that an event X (for instance, that the Open of the previous bar is below the Open of the current bar) appears in 80% of all winning samples. What is then the probability that a sample is winning when it contains event X ? It’s not 0.8 as you might think. The probability can be calculated with Bayes’ Theorem:
P(Y|X) is the probability that event Y (f. i. winning) occurs in all samples containing event X (in our example, Open(1) < Open(0) ). According to the formula, it is equal to the probability of X occurring in all winning samples (here, 0.8), multiplied by the probability of Y in all samples (around 0.5 when you were following my above advice of balanced samples) and divided by the probability of X in all samples.
If we are naive and assume that all events X are independent of each other, we can calculate the overall probability that a sample is winning by simply multiplying the probabilities P (X|winning) for every event X . This way we end up with this formula:
with a scaling factor s . For the formula to work, the features should be selected in a way that they are as independent as possible, which imposes an obstacle for using Naive Bayes in trading. For instance, the two events Close(1) < Close(0) and Open(1) < Open(0) are most likely not independent of each other. Numerical predictors can be converted to events by dividing the number into separate ranges.
The Naive Bayes algorithm is available in the ubiquitous e1071 R package.
11. Decision and regression trees.
Those trees predict an outcome or a numeric value based on a series of yes/no decisions, in a structure like the branches of a tree. Any decision is either the presence of an event or not (in case of non-numerical features) or a comparison of a feature value with a fixed threshold. A typical tree function, generated by Zorro’s tree builder, looks like this:
How is such a tree produced from a set of samples? There are several methods; Zorro uses the Shannon i nformation entropy , which already had an appearance on this blog in the Scalping article. At first it checks one of the features, let’s say x 1 . It places a hyperplane with the plane formula x 1 = t into the feature space. This hyperplane separates the samples with x 1 > t from the samples with x 1 < t . The dividing threshold t is selected so that the information gain – the difference of information entropy of the whole space, to the sum of information entropies of the two divided sub-spaces – is maximum. This is the case when the samples in the subspaces are more similar to each other than the samples in the whole space.
This process is then repeated with the next feature x 2 and two hyperplanes splitting the two subspaces. Each split is equivalent to a comparison of a feature with a threshold. By repeated splitting, we soon get a huge tree with thousands of threshold comparisons. Then the process is run backwards by pruning the tree and removing all decisions that do not lead to substantial information gain. Finally we end up with a relatively small tree as in the code above.
Decision trees have a wide range of applications. They can produce excellent predictions superior to those of neural networks or support vector machines. But they are not a one-fits-all solution, since their splitting planes are always parallel to the axes of the feature space. This somewhat limits their predictions. They can be used not only for classification, but also for regression, for instance by returning the percentage of samples contributing to a certain branch of the tree. Zorro’s tree is a regression tree. The best known classification tree algorithm is C5.0 , available in the C50 package for R.
For improving the prediction even further or overcoming the parallel-axis-limitation, an ensemble of trees can be used, called a random forest . The prediction is then generated by averaging or voting the predictions from the single trees. Random forests are available in R packages randomForest , ranger and Rborist .
Conclusão.
There are many different data mining and machine learning methods at your disposal. The critical question: what is better, a model-based or a machine learning strategy? There is no doubt that machine learning has a lot of advantages. You don’t need to care about market microstructure, economy, trader psychology, or similar soft stuff. You can concentrate on pure mathematics. Machine learning is a much more elegant, more attractive way to generate trade systems. It has all advantages on its side but one. Despite all the enthusiastic threads on trader forums, it tends to mysteriously fail in live trading.
Every second week a new paper about trading with machine learning methods is published (a few can be found below). Please take all those publications with a grain of salt. According to some papers, phantastic win rates in the range of 70%, 80%, or even 85% have been achieved. Although win rate is not the only relevant criterion – you can lose even with a high win rate – 85% accuracy in predicting trades is normally equivalent to a profit factor above 5. With such a system the involved scientists should be billionaires meanwhile. Unfortunately I never managed to reproduce those win rates with the described method, and didn’t even come close. So maybe a lot of selection bias went into the results. Or maybe I’m just too stupid.
Compared with model based strategies, I’ve seen not many successful machine learning systems so far. And from what one hears about the algorithmic methods by successful hedge funds, machine learning seems still rarely to be used. But maybe this will change in the future with the availability of more processing power and the upcoming of new algorithms for deep learning.
Classification using deep neural networks: Dixon. et. al.2018 Predicting price direction using ANN & SVM: Kara. et. al.2018 Empirical comparison of learning algorithms: Caruana. et. al.2006 Mining stock market tendency using GA & SVM: Yu. Wang. Lai.2005.
The next part of this series will deal with the practical development of a machine learning strategy.
30 thoughts on “Better Strategies 4: Machine Learning”
Bela postagem. There is a lot of potential in these approach towards the market.
Btw are you using the code editor which comes with zorro? how is it possible to get such a colour configuration?
The colorful script is produced by WordPress. You can’t change the colors in the Zorro editor, but you can replace it with other editors that support individual colors, for instance Notepad++.
Is it then possible that notepad detects the zorro variables in the scripts? I mean that BarPeriod is remarked as it is with the zorro editor?
Theoretically yes, but for this you had to configure the syntax highlighting of Notepad++, and enter all variables in the list. As far as I know Notepad++ can also not be configured to display the function description in a window, as the Zorro editor does. There’s no perfect tool…
Concur with the final paragraph. I have tried many machine learning techniques after reading various ‘peer reviewed’ papéis. 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,
you can earn extra bucks every month because you’ve got high quality content.
If you want to know how to make extra $$$, search for: Mrdalekjd methods for $$$
Technical analysis has always been rejected and looked down upon by quants, academics, or anyone who has been trained by traditional finance theories. I have worked for proprietary trading desk of a first tier bank for a good part of my career, and surrounded by those ivy-league elites with background in finance, math, or financial engineering. I must admit none of those guys knew how to trade directions. They were good at market making, product structures, index arb, but almost none can making money trading directions. Por quê? Because none of these guys believed in technical analysis. Then again, if you are already making your millions why bother taking the risk of trading direction with your own money. For me luckily my years of training in technical analysis allowed me to really retire after laying off from the great recession. I look only at EMA, slow stochastics, and MACD; and I have made money every year since started in 2009. Technical analysis works, you just have to know how to use it!!

Comments