К основному контенту

Entradas da rede neural forex


Rede neural.
A rede neural é uma das palavras-chave mais recentes na negociação. Parece legal e sofisticado. Muitas pessoas não parecem entender o que são as redes neurais.
Neurônios no mundo real.
Nossos cérebros são fenomenalmente complicados. O que surpreende a maioria das pessoas, no entanto, é que o cérebro é mais ou menos uma enorme caixa de circuitos. Os neurônios são células que atuam como circuitos com "fios elétricos", chamados de axônios, que se acabam e se conectam através do corpo humano. Todo movimento, percepção ou ação que você faz é a soma de todos os axônios que disparam impulsos elétricos. A mudança ocorre sempre que a freqüência de impulsos elétricos enviados do neurônio varia. Mais impulsos causam uma reação, uma redução provoca outra.
As redes neurais tentam imitar processos do cérebro humano através da organização da informação nos neurônios. Ao contrário das células neuronais reais, um neurônio de rede só existe na máquina. É um peso da máquina que contém informações sobre o que está em estudo.
Uma rede neural para um sistema comercial pode decidir estudar indicadores comuns, como uma média móvel, o oscilador RSI e Stochastics. O valor médio móvel para a barra atual conta como seu próprio neurônio. O RSI é diferente, então ele é um neurônio separado. Se eu tiver dez indicadores na minha caixa de ferramentas, então eu tenho 10 neurônios na minha rede.
Os computadores tradicionalmente resolvem problemas simples e lineares. Se você quer saber o resultado de operações matemáticas como a raiz do cubo de 355, os computadores são perfeitos para a tarefa. Eles calculam rapidamente uma resposta precisa.
Como nos cérebros humanos, as redes neurais formam sinapses com outros neurônios. Quando treinados, grupos de neurônios podem aprender a reconhecer padrões. É essa propriedade que torna as redes neurais tão úteis. Isso nos permite criar programas que seriam impossíveis com a computação tradicional. Criar um programa de software para reconhecer um rosto, por exemplo, seria extremamente difícil. É muito mais fácil treinar uma rede para reconhecer um rosto ao mostrar repetidamente os rostos da rede.
O cérebro é um tema fascinante por direito próprio. Como uma aparência, minha esposa e eu estamos fazendo um curso de pesquisa em neurociências através de uma série de vídeos de The Great Courses. Se você tem algum interesse no assunto, eu recomendo Compreender o cérebro por Jeanette Norden. Abrange em detalhes como os neurônios se conectam à anatomia em todo o cérebro e todo o corpo.
Redes Neurais e Forex Trading.
As redes neurais entram em jogo quando a resposta não é tão precisa. Fugindo com o tema deste blog sobre o comércio forex, não há uma resposta correta para o que faz o sistema de negociação perfeito. Um investidor de varejo típico pode dizer que o melhor sistema de negociação é aquele que ganha mais dinheiro. Outro pode dizer que o melhor sistema de negociação é aquele com o maior índice de Sharpe. Muitos querem algo no meio.
O problema do "melhor sistema comercial" é ambíguo, o que o torna um candidato ideal para atacar com redes neurais. O designer delineia conjuntos de regras que, na opinião do comerciante, formam uma forma numérica de medir o melhor sistema.
Os cérebros humanos acolhem cerca de 100 bilhões de neurônios. Apesar dos melhores esforços de muitos de nossos clientes, ainda tenho que conhecer alguém com 100 bilhões de indicadores de mercado à sua disposição. Uma maneira de amplificar o efeito dos neurônios em nossa caixa de ferramentas é criar camadas ocultas.
Uma rede é composta por múltiplas camadas, cada uma composta por múltiplos neurônios. Cada neurônio está conectado a cada neurônio na próxima camada. Toda conexão traz seu próprio valor ponderado único. Um neurônio irá transmitir seu valor multiplicando o valor do neurônio e pelo peso da conexão de saída. O neurônio no final da conexão de saída somará todas as suas conexões de entrada e propagará esse resultado na próxima camada através de todas as suas conexões de saída.
As imagens tornam a idéia muito mais intuitiva. A Figura 1 contém um pequeno exemplo. Os 2 e 3 à esquerda são as entradas para a rede. Essas entradas são multiplicadas pelo peso da conexão para a próxima camada. O 2 é multiplicado por 0,5 dando-nos 1 e 3 por 2 nos dando 6. A segunda camada contém um nó que resume os resultados da camada anterior, dando-nos 7. O próximo passo seria multiplicar 7 pelos pesos em as conexões de saída e passá-lo para a próxima camada.
Figura 1: Um exemplo de uma rede neural que propaga resultados para a frente.
O pequeno exemplo acima pode ser repetido e encadeado para formar uma rede maior. Abaixo, na Figura 2, temos um exemplo de uma rede maior. O exemplo de rede tem 3 entradas que estão conectadas a uma camada oculta. A camada oculta é então conectada a uma única saída. As camadas escondidas são para facilitar o treinamento. Quanto mais complexo o problema, mais camadas e nós precisavam.
Figura 2: Um exemplo de uma rede neural maior.
A rede aprende atualizando os pesos de suas muitas conexões. Existem muitos algoritmos de software que são utilizados para realizar a aprendizagem em redes neurais. Eles se dividem em duas categorias, aprendizado supervisionado e aprendizado sem supervisão. A aprendizagem supervisionada é realizada com o usuário informando a rede se suas previsões estão corretas ou não. A rede então calcula seu erro e usa um dos algoritmos para corrigir o erro. Um exemplo disso é a propagação reversa, que calcula o erro da previsão de uma rede. A rede usa então um algoritmo rápido para atualizar cada um dos pesos de conexão com esse erro. A propagação reversa é uma das estratégias de treinamento mais comuns.
O aprendizado não supervisionado usa algum tipo de algoritmo de aptidão ou pontuação em que a rede se anotará e tentará melhorar todas as tentativas subseqüentes. Um exemplo de treinamento não supervisionado é o algoritmo genético. Este algoritmo cria uma população de redes neurais e usa um algoritmo de pontuação projetado pelo usuário para classificar a população. Depois disso, é a sobrevivência do mais apto. As redes mais bem sucedidas conseguem ficar e "se reproduzem" e as classificações mais baixas são jogadas fora. As redes se reproduzem misturando e combinando pesos de conexão.
As redes neurais podem ajudar substancialmente os comerciantes de sistemas no seu projeto de algoritmo, explorando bilhões de combinações entre uma caixa de ferramentas relativamente pequena. Isso difere da otimização padrão, que envolve a conexão de números em vários indicadores procurando qualquer combinação que retorne mais dinheiro.
O fato de que as redes podem considerar medidas múltiplas (saldo, Ratio Sharpe, etc.) para determinar o melhor sistema comercial ajuda a reduzir a probabilidade de enfatizar demais uma determinada medida. Um bom exemplo disso é o saldo da conta. Se um sistema pesa a entrega e a entrega entre o retorno líquido e o retorno ajustado ao risco, ele começa a se afastar do crunching de números para descobrir os melhores números para usar e dirigir-se para a aprendizagem real e o reconhecimento de padrões.
As redes neurais estão se mostrando muito úteis em uma ampla gama de aplicações, desde o reconhecimento facial até as previsões do mercado monetário. Eles se destacam onde existem padrões que são difíceis de reconhecer. Essa capacidade torna as redes inestimáveis ​​na resolução de problemas difíceis envolvendo múltiplas variáveis.

entradas da rede neural Forex
Estratégias de Stop-and-Reverse da Rede Neural Híbrida para Forex.
por Michael R. Bryant.
As redes de neurônios têm sido utilizadas em sistemas de negociação por muitos anos com vários graus de sucesso. Sua principal atração é que sua estrutura não linear é mais capaz de capturar as complexidades do movimento de preços do que as regras de negociação padrão, baseadas em indicadores. Uma das críticas foi que as estratégias de negociação baseadas na rede neural tendem a ser excessivas e, portanto, não funcionam bem em novos dados. Uma possível solução para este problema é combinar redes neurais com lógica de estratégia baseada em regras para criar um tipo de estratégia híbrida. Este artigo mostrará como isso pode ser feito usando o Adaptrade Builder.
Em particular, este artigo irá ilustrar o seguinte:
Combinando rede neural e lógica baseada em regras para entradas de comércio.
Segmentação múltipla de plataformas simultaneamente (MetaTrader 4 e TradeStation)
Desenvolvendo uma estratégia com lógica de parada e inversa assimétrica.
Usando dados forex intraday.
Será utilizada uma abordagem de dados de três segmentos, com o terceiro segmento usado para validar as estratégias finais. O código de estratégia resultante para MetaTrader 4 e TradeStation será mostrado, e será demonstrado que os resultados de validação são positivos para cada plataforma.
Redes Neurais como Filtros de Entrada Comercial.
Matematicamente, uma rede neural é uma combinação não linear de uma ou mais entradas ponderadas que gera um ou mais valores de saída. Para negociação, uma rede neural geralmente é usada de duas maneiras: (1) como previsão de movimento futuro de preços, ou (2) como indicador ou filtro para negociação. Aqui, será usado como indicador ou filtro comercial.
Como um indicador, uma rede neural age como uma condição ou filtro adicional que deve ser satisfeito antes que uma troca possa ser inserida. As entradas para a rede normalmente são outros indicadores técnicos, tais como dinâmica, estocástica, ADX, médias móveis, etc., bem como preços e combinações dos anteriores. As entradas são dimensionadas e a rede neural é projetada para que a saída seja um valor entre -1 e +1. Uma abordagem é permitir uma entrada longa se a saída for maior ou igual a um valor limiar, como 0,5 e uma entrada curta, se a saída for menor ou igual ao negativo do limite; por exemplo, -0,5. Esta condição seria adicional a quaisquer condições de entrada existentes. Por exemplo, se houvesse uma condição de entrada longa, teria que ser verdadeira e a saída da rede neural teria que ser pelo menos igual ao valor limite para uma entrada longa.
Ao configurar uma rede neural, um comerciante normalmente seria responsável por escolher as entradas e a topologia da rede e para "treinamento" a rede, que determina os melhores valores de pesos. Como será mostrado abaixo, o Adaptrade Builder executa essas etapas automaticamente como parte do processo de compilação evolutiva no qual o software se baseia. Usar a rede neural como um filtro de comércio permite que ele seja facilmente combinado com outras regras para criar uma estratégia de negociação híbrida, que combine as melhores características das abordagens tradicionais baseadas em regras e as vantagens das redes neurais. Como um exemplo simples, o Builder pode combinar uma regra de cruzamento média móvel com uma rede neural de modo que uma posição longa seja tomada quando a média móvel rápida cruza acima da média lenta e a saída da rede neural está em ou acima do seu limite.
Estratégias de negociação Stop-and-Reverse.
Uma estratégia de negociação de parada e reversa é uma que está sempre no mercado, seja longa ou curta. Estritamente falando, "stop-and-reverse" significa que você inverte o comércio quando sua ordem de parada é atingida. No entanto, uso-o como uma mão curta para qualquer estratégia de negociação que reverte de longo para curto para longo e assim por diante, para que você esteja sempre no mercado. Por esta definição, não é necessário que as ordens sejam pedidos de parada. Você pode entrar e reverter usando pedidos de mercado ou limite também. Também não é necessário que cada lado use a mesma lógica ou mesmo o mesmo tipo de ordem. Por exemplo, você pode entrar em um período longo (e sair curto) em uma ordem de parada e digitar curto (e sair por muito tempo) em uma ordem de mercado, usando diferentes regras e condições para cada entrada / saída. Este seria um exemplo de uma estratégia de parada e inversão assimétrica.
A principal vantagem de uma estratégia de parar e reverter é que, sempre no mercado, você nunca perca nenhuma grande jogada. Outra vantagem é a simplicidade. Quando existem regras e condições separadas para entrar e sair de negócios, há mais complexidade e mais que podem dar errado. A combinação de entradas e saídas significa que há menos decisões de tempo, o que pode significar menos erros.
Por outro lado, pode-se argumentar que as melhores condições para sair de um comércio raramente são as mesmas para entrar na direção oposta; que entrar e sair trades são decisões inerentemente separadas que, portanto, deveriam empregar regras e lógica separadas. Outra desvantagem potencial de estar sempre no mercado é que a estratégia irá trocar todo o intervalo de abertura. Um grande intervalo de abertura contra a posição pode significar uma grande perda antes que a estratégia seja capaz de reverter. Estratégias que entram e saem mais seletivamente ou que saem ao final do dia podem minimizar o impacto das brechas de abertura.
Uma vez que o objetivo é construir uma estratégia forex, o MetaTrader 4 (MT4) é uma escolha óbvia para a plataforma de negociação, dado que o MetaTrader 4 foi projetado principalmente para o forex e é amplamente utilizado para comercializar esses mercados (veja, por exemplo, MetaTrader vs. TradeStation : Uma comparação de linguagem). No entanto, nos últimos anos, a TradeStation segmentou os mercados de divisas de forma muito mais agressiva. Dependendo do seu volume de negociação e / ou nível da conta, é possível negociar os mercados de divisas através da TradeStation sem incorrer em taxas de plataforma ou pagar comissões. Spreads são supostamente apertado com boa liquidez nos principais pares de divisas. Por estas razões, ambas as plataformas foram direcionadas para este projeto.
Várias questões surgem ao direcionar várias plataformas simultaneamente. Primeiro, os dados podem ser diferentes em diferentes plataformas, com diferenças em fusos horários, cotações de preços para algumas barras, volume e faixas de datas disponíveis. Para suavizar essas diferenças, os dados foram obtidos de ambas as plataformas, e as estratégias foram construídas em ambas as séries de dados simultaneamente. As melhores estratégias foram, portanto, as que funcionaram bem em ambas as séries de dados, apesar das diferenças nos dados.
As configurações de dados usadas no Builder são mostradas abaixo na Fig. 1. Como se pode inferir da tabela Market Data na figura, o mercado de Forex Euro / dólar foi segmentado (EURUSD) com um tamanho de barra de 4 horas (240 minutos). Outros tamanhos de barras ou mercados teriam servido também. Eu só consegui obter tantos dados através da minha plataforma MT4 como indicado pelo intervalo de datas mostrado na Fig. 1 (série de dados nº 2), de modo que o mesmo intervalo de datas foi usado na obtenção de séries de dados equivalentes da TradeStation (data series # 1). 80% dos dados foram utilizados para construção (combinado na amostra e "fora da amostra"), com 20% (6/20/14 a 2/10/15) reservado para validação. 80% dos 80% originais foram então ajustados para "na amostra" com 20% definido para "out-of-sample", & quot; como mostrado na Fig. 1. O spread de oferta / solicitação foi fixado em 5 pips, e os custos de negociação de 6 pips ou US $ 60 por lote completo (100.000 ações) foram assumidos por rodada. Ambas as séries de dados foram incluídas na compilação, conforme indicado pelas marcas de seleção na coluna da esquerda da tabela de dados do mercado.
Figura 1. Configurações de dados do mercado para construir uma estratégia forex para MetaTrader 4 e TradeStation.
Outro problema potencial ao direcionar várias plataformas é que o Builder foi projetado para duplicar a forma como cada plataforma suportada calcula seus indicadores, o que pode significar que os valores dos indicadores serão diferentes dependendo da plataforma selecionada. Para evitar esta possível fonte de discrepância, todos os indicadores que avaliem de forma diferente no MetaTrader 4 do que na TradeStation devem ser eliminados da compilação, o que significa que os seguintes indicadores devem ser evitados:
Slow D estocástico.
Fast estocástico D.
Todos os outros indicadores que estão disponíveis para ambas as plataformas são calculados da mesma maneira em ambas as plataformas. O TradeStation inclui todos os indicadores que estão disponíveis no Builder, enquanto o MetaTrader 4 não. Portanto, para incluir apenas indicadores que estão disponíveis em ambas as plataformas, a plataforma MetaTrader 4 deve ser selecionada como o tipo de código no Builder. Isso eliminará automaticamente qualquer indicador do conjunto de compilação que não esteja disponível para MT4, o que deixará os indicadores disponíveis em ambas as plataformas. Além disso, como notei diferenças nos dados de volume obtidos de cada plataforma, removi todos os indicadores dependentes do volume do conjunto de compilação. Por fim, o indicador do horário do dia foi removido devido a diferenças nos fusos horários entre os arquivos de dados.
Na Fig. 2, abaixo, a lista de indicadores utilizados no conjunto de compilação é mostrada ordenada por se o indicador foi ou não considerado pelo processo de compilação ("Considere" coluna). Os indicadores removidos da consideração pelos motivos discutidos acima são mostrados no topo da lista. Os indicadores restantes, começando com "Simple Mov Ave", foram todos parte do conjunto de compilação.
Figura 2. Seleções de indicadores no Builder, mostrando os indicadores removidos do conjunto de compilação.
As opções de avaliação usadas no processo de compilação são mostradas na Fig. 3. Conforme discutido, o MetaTrader 4 foi selecionado como a escolha de saída do código. Depois que as estratégias são criadas no Builder, qualquer uma das opções na guia Opções de avaliação, incluindo o tipo de código, pode ser alterada e as estratégias reavaliadas, que também reescreverão o código em qualquer idioma selecionado. Esse recurso foi usado para obter o código da TradeStation para a estratégia final depois que as estratégias foram criadas para o MetaTrader 4.
Figura 3. Opções de avaliação no Builder para a estratégia forex EURUSD.
Para criar estratégias de parada e reversão, todos os tipos de saída foram removidos do conjunto de compilação, conforme mostrado abaixo na Fig. 4. Todos os três tipos de pedidos de entrada - mercado, parada e limite - foram deixados como "considerar" , o que significa que o processo de compilação poderia considerar qualquer um deles durante o processo de compilação.
Figura 4. Tipos de ordem selecionados no Builder para criar uma estratégia de parada e reversão.
O software Builder gera automaticamente condições lógicas baseadas em regras para entrada e / ou saída. Para adicionar uma rede neural à estratégia, basta selecionar a opção "Incluir uma rede neural nas condições de entrada" na guia Opções de Estratégia, como mostrado abaixo na Fig. 5. As configurações de rede neural foram deixadas em seus padrões. Como parte da lógica stop-and-reverse, a opção Market Sides foi definida para Long / Short e a opção para "Wait for exit before enter new trade". estava desmarcado. O último é necessário para habilitar a ordem de entrada para sair da posição atual em uma inversão. Todas as outras configurações foram deixadas nos padrões.
Figura 5. Opções de estratégia selecionadas no Builder para criar uma estratégia híbrida usando condições de rede baseadas em regras e neurais.
A natureza evolutiva do processo de construção no Builder é orientada pela aptidão, que é calculada a partir dos objetivos e condições definidos na guia Metrics, conforme mostrado abaixo na Figura 6. Os objetivos de construção foram mantidos simples: maximizando o lucro líquido e minimizando a complexidade, que recebeu um pequeno peso em relação ao lucro líquido. Mais ênfase foi colocada nas condições de construção, que incluíram o coeficiente de correlação e significância para a qualidade geral da estratégia, bem como as barras médias nos negócios e a quantidade de negócios.
Inicialmente, apenas as barras médias em negociações foram incluídas como condição de construção. No entanto, em algumas das construções iniciais, o lucro líquido foi favorecido ao longo do prazo comercial, de modo que a métrica do número de negociações foi adicionada. O intervalo especificado para o número de trades (entre 209 e 418) é equivalente ao comprimento médio de comércio entre 15 e 30 barras com base no número de barras no período de compilação. Como resultado, a adição desta métrica colocou mais ênfase no objetivo de longo prazo, o que resultou em mais membros da população com o intervalo desejado de comprimentos comerciais.
Figura 6. Construir objetivos e condições definidos na guia Métrica determinar como a aptidão é calculada.
As "condições para selecionar estratégias superiores" duplicar as condições de compilação, exceto que as principais condições de estratégias são avaliadas em toda a gama de dados (não incluindo o segmento de validação, que é separado), em vez de apenas ao longo do período de compilação, como é o caso das condições de construção. As principais condições de estratégias são usadas pelo programa para deixar de lado quaisquer estratégias que atendam a todas as condições em uma população separada.
As configurações finais são feitas na guia Configurações de Configuração, como mostrado abaixo na Figura 7. As opções mais importantes aqui são o tamanho da população, o número de gerações ea opção para redefinir com base no "out-of-sample" desempenho. O tamanho da população foi escolhido para ser grande o suficiente para obter uma boa diversidade na população, enquanto ainda é pequeno o suficiente para construir em uma quantidade razoável de tempo. O número de gerações foi baseado em quanto tempo levou durante algumas compilações preliminares para que os resultados começassem a convergir.
Figura 7. As opções de construção incluem o tamanho da população, o número de gerações e as opções para redefinir a população com base em "out-of-sample" desempenho.
A opção para & quot; Reset on Out-of-Sample (OOS) Performance & quot; inicia o processo de compilação após o número especificado de gerações se a condição especificada for atendida; neste caso, a população será redefinida se o "out-of-sample" O lucro líquido é inferior a US $ 20.000. Esse valor foi escolhido com base em testes preliminares para ser um valor suficientemente alto que provavelmente não seria alcançado. Como resultado, o processo de compilação foi repetido a cada 30 gerações até parar manualmente. Esta é uma maneira de permitir que o programa identifique estratégias com base nas condições de Top Strategies durante um longo período de tempo. Periodicamente, a população Top Strategies pode ser verificada e o processo de compilação é cancelado quando são encontradas estratégias adequadas.
Observe que eu coloco "out-of-sample" entre citações. Quando o "fora da amostra" O período é usado para redefinir a população desta maneira, a "saída de amostra" O período não é mais verdadeiramente fora da amostra. Uma vez que esse período agora está sendo usado para orientar o processo de compilação, é efetivamente parte do período de exibição. É por isso que é aconselhável reservar um terceiro segmento para validação, conforme discutido acima.
Após várias horas de processamento e uma série de reconstruções automáticas, uma estratégia adequada foi encontrada na população Top Strategies. A curva de equidade comercial fechada é mostrada abaixo na Figura 8. A curva de equidade demonstra um desempenho consistente em ambos os segmentos de dados com um número adequado de negócios e, essencialmente, os mesmos resultados em ambas as séries de dados.
Figura 8. Curva de equidade de comércio fechado para a estratégia de paragem e reversão do EURUSD.
Para verificar a estratégia durante o período de validação, a data controlada na guia Mercados (veja a Fig. 1) foi alterada para a data final dos dados (2/11/2015) e a estratégia foi reavaliada selecionando a opção Avaliar comando no menu Estratégia no Builder. Os resultados são mostrados abaixo na Fig. 9. Os resultados de validação na caixa vermelha demonstram que a estratégia mantida em dados não utilizados durante o processo de compilação.
Figura 9. Curva de equidade de comércio fechado para a estratégia de paragem e reversão do EURUSD, incluindo o período de validação.
A verificação final é ver como a estratégia realizada em cada série de dados separadamente usando a opção de saída de código para essa plataforma. Isso é necessário porque, como explicado acima, pode haver diferenças nos resultados dependendo (1) do tipo de código, e (2) das séries de dados. Precisamos verificar se as configurações escolhidas minimizaram essas diferenças, conforme pretendido. Para testar a estratégia do MetaTrader 4, a série de dados da TradeStation foi desmarcada na guia Mercados e a estratégia foi reavaliada. Os resultados são mostrados abaixo na Fig. 10, que duplica a curva inferior na Fig. 9.
Figura 10. Curva de equidade de comércio fechado para a estratégia de paragem e reversão do EURUSD, incluindo o período de validação, para o MetaTrader 4.
Finalmente, para testar a estratégia para a TradeStation, a série de dados da TradeStation foi selecionada e a série para o MetaTrader 4 foi desmarcada na aba Mercados, a saída do código foi alterada para "TradeStation", "quot; e a estratégia foi reavaliada. Os resultados são mostrados abaixo na Fig. 11 e parecem ser muito semelhantes à curva do meio na Fig. 9, conforme esperado.
Figura 11. Curva de equidade de comércio fechado para a estratégia de paragem e reversão do EURUSD, incluindo o período de validação, para a TradeStation.
O código para ambas as plataformas é fornecido abaixo na Fig. 12. Clique na imagem para abrir o arquivo de código para a plataforma correspondente. Examinar o código revela que a parte baseada em regras da estratégia usa diferentes condições relacionadas à volatilidade para os lados longo e curto. As entradas da rede neural consistem em uma variedade de indicadores, incluindo o dia-semana, a tendência (ZLTrend), o intraday high, osciladores (InvFisherCycle, InvFisherRSI), as bandas de Bollinger e o desvio padrão.
A natureza híbrida da estratégia pode ser vista diretamente na declaração de código (do código da TradeStation):
Se EntCondL e NNOutput & gt; = 0.5 então começarem.
Compre (& quot; EnMark-L & quot;); NShares compartilha a próxima barra no mercado;
A variável "EntCondL" representa as condições de entrada baseadas em regras, e "NNOuput & quot; é o resultado da rede neural. Ambas as condições devem ser verdadeiras para colocar a ordem de entrada longa. A condição de entrada curta funciona da mesma maneira.
Figura 12. Código de estratégia de negociação para a estratégia de parada e reversa do EURUSD (à esquerda, MetaTrader 4, à direita, TradeStation). Clique na figura para abrir o arquivo de código correspondente.
Este artigo analisou o processo de construção de uma estratégia de rede baseada em regras híbridas / neural para o EURUSD usando uma abordagem stop-and-reverse (sempre no mercado) com o Adaptrade Builder. Foi mostrado como o código da estratégia pode ser gerado para várias plataformas, selecionando um subconjunto comum dos indicadores que funcionam da mesma maneira em cada plataforma. As configurações necessárias para gerar estratégias que se revertem de longo para curto e para trás foram descritas, e foi demonstrado que a estratégia resultante foi realizada positivamente em um segmento separado de validação de dados. Verificou-se também que a estratégia gerou resultados semelhantes com a opção de dados e código para cada plataforma.
Conforme discutido acima, a abordagem de parar e reverter tem várias desvantagens e pode não atrair a todos. No entanto, uma abordagem sempre no mercado pode ser mais atraente com os dados de divisas, porque os mercados de divisas são comercializados 24 horas por dia. Como resultado, não há lacunas de abertura de sessão e as ordens de negociação sempre estão ativas e disponíveis para reverter o comércio quando o mercado muda. O uso de dados intradía (barras de 4 horas) proporcionou mais barras de dados para uso no processo de compilação, mas foi de outra forma bastante arbitrário, na medida em que a natureza sempre dentro do mercado da estratégia significa que os negócios são transportados durante a noite.
O processo de compilação permitiu evoluir diferentes condições para inserção longa e curta, resultando em uma estratégia de parada e inversão assimétrica. Apesar do nome, a estratégia resultante entra em negociações longas e curtas em ordens de mercado, embora as ordens de mercado, parada e limite fossem consideradas pelo processo de construção de forma independente para cada lado. Na prática, a reversão de longo a curto significaria vender curto o dobro do número de ações no mercado, já que a estratégia era longa; por exemplo, se a posição longa atual fosse de 100.000 ações, você venderia 200.000 ações curtas no mercado. Da mesma forma, se a posição curta atual fosse de 100.000 ações, você compraria 200.000 ações no mercado para reverter de curto para longo.
Foi usado um histórico de preços mais curto do que seria ideal. No entanto, os resultados foram positivos no segmento de validação, sugerindo que a estratégia não estava em excesso. Isso apóia a idéia de que uma rede neural pode ser usada em uma estratégia comercial sem necessariamente superar a estratégia para o mercado.
A estratégia apresentada aqui não se destina a negociação real e não foi testada em rastreamento ou negociação em tempo real. No entanto, este artigo pode ser usado como um modelo para o desenvolvimento de estratégias similares para o EURUSD ou outros mercados. Como sempre, qualquer estratégia de negociação que você desenvolver deve ser testada completamente no rastreamento em tempo real ou em dados separados para validar os resultados e familiarizar-se com as características de negociação da estratégia antes da negociação ao vivo.
Este artigo apareceu na edição de fevereiro de 2015 do boletim informativo do Adaptrade Software.
OS RESULTADOS DE DESEMPENHO HIPOTÉTICOS OU SIMULADOS TÊM CERTAS LIMITAÇÕES INERENTES. DESEJO UM REGISTRO DE DESEMPENHO REAL, OS RESULTADOS SIMULADOS NÃO REPRESENTAM A NEGOCIAÇÃO REAL. TAMBÉM, DESDE QUE OS NEGÓCIOS NÃO SEJAM REALMENTE EXECUTOS, OS RESULTADOS PODEM TENER SOB OU COMENTÁRIOS COMPLEMENTARES PARA O IMPACTO, SE HAVER, DE CERTOS FATORES DE MERCADO, TAL COMO FALTA DE LIQUIDEZ. PROGRAMAS DE NEGOCIAÇÃO SIMULADOS EM GERAL SÃO TAMBÉM SUJEITOS AO FATO QUE ESTÃO DESIGNADOS COM O BENEFÍCIO DE HINDSIGHT. NENHUMA REPRESENTAÇÃO ESTÁ FAZENDO QUE QUALQUER CONTA VÁ OU SEJA PROBABILITÁVEL PARA ALCANÇAR LUCROS OU PERDAS SIMILARES ÀOS MOSTRADOS.
Se você quiser ser informado de novos desenvolvimentos, novidades e ofertas especiais do Adaptrade Software, por favor, junte-se à nossa lista. Obrigado.
Copyright © 2004-2015 Adaptrade Software. Todos os direitos reservados.

Forex Mecânico.
Negociação no mercado FX usando estratégias mecânicas de negociação.
Redes Neurais na Negociação: Escolhendo Entradas e Saídas.
Quando você constrói uma rede neural, uma das primeiras coisas que você precisa decidir é quais valores serão as entradas e quais valores serão os resultados da sua rede. As saídas são os valores que você deseja prever & # 8211; para obter lucro dentro de um sistema de negociação & # 8211; e as entradas são os valores que permitirão prever as saídas com precisão suficiente para constituir uma ineficiência. Agora, escolher entradas e saídas não é tarefa trivial, pois isso constitui a maioria do sucesso ou falha de uma rede neural de negociação. Dentro do post de hoje, vou compartilhar com você algumas dicas sobre como escolher entradas e saídas e como elas podem levar a ineficiências de maneiras que podem não ser muito intuitivas. Eu também vou explicar por que as soluções de entrada / saída mais computacionalmente sonoras podem não ser as melhores e por que esse é o caso.
Uma rede neural é formada por um conjunto de camadas de função que transformam um determinado conjunto de variáveis ​​de entrada (a camada de entrada) em um dado conjunto de valores de saída (a camada de saída). Entre as camadas de entrada e saída, você encontrará uma quantidade variada de camadas e funções (neurônios) e # 8211; dependendo do que você escolher & # 8211; que tentará transformar entradas em saídas com o menor erro possível. Isso é feito com a ajuda de conjuntos de treinamento que permitem à rede ajustar seus coeficientes de camada oculta para se adequar a um conjunto de dados para os quais os dados de entrada e saída já são conhecidos. A esperança é, é claro, que a rede mantenha pelo menos o mesmo poder preditivo dentro de um conjunto não treinado.
A primeira coisa que você precisa escolher quando você constrói uma rede neural para negociação é exatamente quais valores você deseja prever. Você quer prever o próximo dia & # 8217; s perto? Na próxima semana, está perto? O próximo suporte ou nível de resistência? Escolher a saída da rede primeiro permite que você saiba como você vai construir suas entradas, pois você precisa escolher valores que possam prever a saída desejada. Um ponto muito importante aqui é considerar como você irá normalizar a saída e se o resultado cai no que a rede neural é & # 8220; melhor em fazer & # 8221 ;. Lembre-se que, nas redes neurais, os valores de saída precisam variar de -1 a 1 (quando se usam funções simétricas sigmóficas eficientes), uma vez que as saídas arbitrárias exigem o uso de funções lineares que são & # 8220; muito ruins & # 8221; ao encaixar a rede.
Depois de escolher a saída desejada, o próximo passo lógico é criar entradas que você acredita serem previsíveis em relação a esse resultado. Certainly before building the network there is no way of telling if one input will be better than another but you can obviously reduce the amount of variables you will use by doing a PCA (Principal Component Analysis) to filter out those variables which are evidently and heavily correlated. For example you might be interested in predicting the next week’s close and you decide to use as inputs past weekly closes, open, highs and lows but it turns out that a PCA analysis – as an example, I don’t know if this is the case – tells you that the close and open are very correlated and therefore it makes sense to only use the close, high and low.
The PCA technique allows us to eliminate those variables which might be redundant within the network and therefore only increase complexity without increasing the quality of the results. Once you have a set of variables which are not correlated it is time to test how muchВ predictiveВ power they actually have against your desired output. If the results are initially discouraging it may be because you are missing an important piece of information within your inputs or because the shape of your output isn’tВ appropriate. For example if you want to predict the weekly close and you have attempted to normalize it В by diving it over the last week’s close and then dividing it by two then doing a different mathematical operation over the output might increase the predictive quality of your network. Sometimes including information related with all inputsВ withinВ the output can be a handy trick to “force” the network into “using” every piece of knowledge it has although the results will vary and you will need to assess which one works better.
A very difficult aspect of neural network development for trading systems is to actually chooseВ outputsВ which are useful for trading system development and yet accurate enough. В For example you may be tempted to choose outputs and inputs that are very efficient for the neural network – such as an output between 0 an 1 attempting to predict a week’s change – but it turns out that this is not predicted as well as predicting the week’s close because predicting the weekly change using weekly change data makes the network loose a very important piece of information (absolute support and resistance levels) which are derived from direct price information. From a computational point of view it seems like the best solution but from a trading point of view you’re missing a vital piece of information which is not included in weekly change data.
A very interesting thing I have found out in the networks I have developed for Sunqu is that the use of absolute price values is very good since the network learns about support and resistance levels as they develop, actually trading around them in a certain way. Obviously the actual calculations done by the networks and their meaning are not known (remember that a neural network is for all practical purposes a black box) but looking at how trades are executed by the network shows a certain “taking into account” of things such as support and resistance. Since price is what you want to capture then taking into account absolute price values and basing predictors on them is a more straighforward way to system building than attempting to develop indicator output based networks.
However this doesn’t mean that you couldn’t get good results in this way. Predicting things like RSI extremes will allow you to take advantage of rapid price movements before they happen and predicting moving average shifts in the long term will allow you to take long term trend following positions. Nonetheless whatever you want to predict (your output choice) needs to be accompanied by a very judicious decision of which inputs you will use, reinforced by an adequate PCA analysis which can show you the quality of your inputs and how well separated they are from one another. The pair choice will also be very important as certain pairs need fundamental inputs as they deeply affect the way in which they behave (a good example is a USD/CAD neural network using US oil futures data).
If you would like to learn more about my work in automated trading and how you too can get a true education in this fieldВ please consider joiningВ Asirikuy, a website filled with educational videos, trading systems, development and a sound, honest and transparent approach towards automated trading in general . I hope you enjoyed this article ! :o)
One Response to “Neural Networks in Trading: Choosing Inputs and Outputs”
Quote: “USD/CAD neural network using US oil futures data”
Is there an overview or table on your page or somewhere about such correlations between currencies and other indices?

SnowCron.
FREE E. Mail Classes.
In this article: an example of using of our Neural Networks Software to create a complete neural network trading system .
This example uses the Cortex built-in scripting language, so please read the scripting language guide first.
Using Neural Networks to create FOREX Trading Strategy.
In this free online tutorial you will find the "full cycle" of using neural networks (Cortex Neural Networks Software ) for Forex trading (or stock market trading , the idea is the same).
You will learn how to choose inputs for the artificial neural networks , and how to decide what to use as the output.
You will find an example of a ready to use script that allows to perform neural networks optimization of both the structure of Neural Network (number of neurons) and the forex trading system (stop loss etc.)
Finally (the part that is not present in most tutorials), you will learn what to do next. After all, Cortex Neural Networks Software cannot do real time trading, you need to use something like Trade Station, MetaQuotes or MetaTrader. How to port the FOREX trading system from Cortex to your favorite trading platform? Do you have to deal with DLLs, ActiveX controls and low-level programming? The answer is NO.
Cortex Neural Networks Software comes with the easy to use feature that allows you to easily port the resulting (trained) Neural Network to the scripting language of your trading platform. No DLLs, DDE, ActiveX or any other low-level solutions - everything is plain and simple.
Important note: this is NOT a "how to trade" tutorial. Instead, it tells you how to use Cortex Neural Networks Software, but you still need to invent your own trading system. The one we use here is barely a starting point, and shouldn't be used as a forex trading strategy "as is". The idea of this text is to teach you to create NN-based trading systems and to port them to the trading platform of your choice. The example is, however, ovesimplified, and can only be used as the illustration of trading principles. Same way, the MACD trading system, that can be found in many tutorials, is not working well anymore (as markets have changed), but still is a good example of using indicators for mechanical trading.
In two words: do your own analysis.
Another important note: the tutorial uses examples, lots of them. To make your life easier, I have included them all, not just fragments. However it makes the text much longer. Also, I am going from the very first, clumsy, forex trading system , to more advanced, every time explaining what had been improved and why. Be patient, or jump directly to the section you need.
Final important note: the code is not something carved in stone, it could change while this text was written. The final versions of script files are included in Cortex archive.
Pitfalls of FOREX BUY / SELL Signals: What is wrong with "simple" examples?
In the Cortex Neural Networks Software user's guide we used a simple example of an aftifficial Neural Network , predicting the price of GENZ stock. To find out what is wrong with this approach, let's do the same "simple" example, using MSFT. TXT, instead of the GENZ. TXT (use 800 records in the learning set, as MSFT. TXT is a little bit shorter, then GENZ. TXT).
It just wouldn't work! Por quê?
The reason will become evident, if you ask yourself: "What is the reason neural network forecasting of future values can be done on the first place?"
The answer is: it is learning to do what is called neural networks pattern recognition , to recognize patterns, and if there is a hidden logic in these patterns, then even a new pattern (with the same logic) will be recognized.
That's a trick - "with the same logic". There is not even one, but three problems here.
First of all, if you look at the Microsoft's stock price, you will notice, that it was going down in the "learning" part of our data, and sideways - in the "testing" part. So it is possible, that the logic had changed.
Second, and even more important - WHAT IS THE PATTERN? You see, if we teached the neural network in the range 10 - 100, and then presented it with something in the 1 to 3 range - they are different patterns! 10, 20, 30 and 1, 2, 3 look similar to the human because - BECAUSE - we have this ability to divide by ten, when presented with numbers ending with zero. It is what is called a pre-processing of the data, and by default, the NN can not do it.
Can we teach it? Claro. What is it EXACTLY we need to teach it?
This is the third, and the most important one. We do not need the price prediction! We do not care! What we need is FOREX buy sell signals.
Now, wait a minute! We need a) to have our input (both learning and testing) in the same range, and we need b) to be able to make trading decisions based on it? Isn't it what we call an indicator? Bingo?
So, that's what we are going to do - we will build an indicator, to feed it to the NN as an input, and we will try to get a prediction of the indicator value, not the worthless stock price!
In our first example, we will load stock quotes from the disk, open the Neural Network file and start the learning - all in an automated mode.
Create a new script file (or open the one that came with the Cortex Neural Networks Software archive) and call it stocks_nn. tsc.
First of all, we need to download the price values from the MSFT. TXT file. We are going to use the CLV indicator (see below), but to calculate it, we need split-adjusted values for High and Low, not just for close. Here is how to get them.
stocks_nn. tsc, part 1.
The first line assigns the path to the strStockPath variable, of course, you will have to edit it, if your data file is located in the different directory.
In the second line we specify, that this path is not relative (the "relative" to the location of Cortex. exe file).
The TABLE_LOADER receives the path, the empty string for the "start line", 1 - to skip the first line (column names), part of the file's footer line (the last line in MSFT. TXT does not contain data), it is also instructed to load the column number 0 (and call it arrDate), 2 (arrHigh), 3 (arrLow), 4 (arrC) and 6 (arrClose).
For a full description of TABLE_LOADER, see the SLANG reference guide.
Then we calculate split, by dividing the Adjusted Close by Close, and use this value to adjust Low and High.
The MSFT. TXT file contains newest data FIRST, while we want them LAST.
Next, we need to create an indicator. Let's say, it is going to be a Close Location Value indicator, though in the "real life" I would probably use more than one indicator as the NN input.
The Close Location Value indicator is calculated like.
CLV = ((Close - Low) - (High - Close)) / (High - Low), where Close, Low and High are for the interval, not necessarily for a single bar. Note, that we want it in the 0 - 1 range, to make it easier to normalize to our NN's range (which is, again, 0-1).
stocks_nn. tsc, part 3.
Next, we need to create a lag file. Let's use lags equal to 1, 2. 9 (For details on file functions, see the SLANG reference guide). Note, that the Cortex's NN dialog can produce simple lags automatically (you can use a "Generate lag" button). But later in this text, we are going to work with complex lags (which means, they are not 1, 2, 3. but 1, 3, 64. whatever), so we need to create the code that can handle this task in a more flexible way.
stocks_nn. tsc, part 4.
Having the lag file, we are ready to create our first neural network. This function takes a lot of parameters, so be carefull. However, the code is really simple.
By the way, most of this code can be removed, if you think you can handle numbers, instead of meaningfull names in your code, however, that would be a very bad coding practice.
stocks_nn. tsc, part 5.
Now, after we have a neural network and the lagged file with data, we need to teach the network. The lag file (msft_ind. lgg) has 1074 records, so it is reasonable to use 800 as a learning set, and the remaining 274 as a testing set.
You can, of course, open a network file and to click the "Run" button on the "Learning" tab. But as this is an introduction to advanced Cortex Neural Networks Software programming, let's use SLANG built_in scripting language instead.
The following code brings up the modal dialog with ann NN settings. Note, that if you want to have a privilege of clicking the "Run" button, you need to change the.
stocks_nn. tsc, part 6.
The bStartLearning can be 0, in which case the dialog will wait for your input, or 1, then the learning will begin aytomatically.
The bResumeScript, if equals 1, will resume the script, if you close the dialog by clicking the OK button.
The bReset is used to reset the network before the learning begins.
Run the script, and wait for the epoch counter to exceed 1000, then click "Stop". Go to the "Apply" tab, and click "Apply". This will run the entire data set (both learning and testing) through the NN, and create the. APL file, containing both original input-output, and the NN-generated prediction, this way you can easily plot them and compate against each other.
Go to the "Output" tab, select msft_ind. apl file, click "Browse file", "Select fields", then select the "No" in the left list box, and (by holding down the CTRL key while selecting with the mouse) Clv and NN:Clv in the right list box. Click "Chart" to see how good our prediction is. Bem. It is more or less good, from what we can say by looking at it. Still, nothing extraordinary.
This was just an example of what you can do with SLANG scripting, and how to automate Cortex's routine tasks. However, until now, we did nothing you couldn't do "by hand". Bem. almost nothing, because if you want to create a custom lag file, with, say, Clv-100, Clv-50, Clv-25. columns, then you will have to use SLANG (or Excel. ), because you cannot do in in Cortex without scripting.
FOREX Trading Strategy: what to optimize?
Here is our next problem. Do we need a good-looking prediction, or do we need the one we can use to trade with profit? The question seems odd, but just think about it for a moment. Let's say we have a VERY good 1-hour prediction. 95% de precisão. Still, how far can the price go in one hour? Not too far, I am afraid. Compare it to the situation, when you have a rather inaccurate 10-hours prediction. Will it be better?
To answer this question, we need to actually trade, a simple comparison of the mean errors produced by the two NNs will not help.
The second part (of the same problem) is in the way we define a "good prediction". Let's say we have a network, that produces the prediction, which is 75% accurate. Compare it to the NN, that is producing 100% accurate prediction. The last one is better. Now, DIVIDE the output (prediction) of the 100% accurate NN by 10. We will have a VERY inaccurate network, as its signal is nowhere near the signal we used as a "desired output". And yet, it can be used same way we used 100% accurate NN, all we have to do is to multiply it to 10!
See, the NN is created, by tuning the mean quadratic error, and not the correlation, so, at least in theory, a better NN can show poor results, when used for the actual stock / Forex trading.
To solve this problem, we need to test our NNs using trading, and to use results of this trading (profit and drawdowns) to decide, if this NN is better than the other one.
Let's do it. Let's create a program, that can be used to fine-tune NN, and this time, by fine-tuning, we will mean trading results.
Neural Network Trading: Few short notes.
First of all, in our example above, the "automatic" learning will never stop, because we haven't specified any stop criteria. In the dialog, or in the CREATE_NN function, you can provide the min. error (when the NN reaches it, it stops and, if bResumeScript is set to 1, the dialog will close and the script will resume). Also yo can provide the maximum number of epochs, or both. I am not using it in the example below, at least not always, because I am planning to watch the learning and to click STOP when I think the NN is ready. If you want to do it in fully automatic mode, pay attention to these parameters.
Segundo. One of the ways to make a network smaller, faster and more accurate, is to begin with the small network, and increase it's size, neuron by neuron. Obwiously, the number of the input neurons is determined by the number of input data columns (but we can vary them, too), and the number of output neurons should be equal to the number of output data columns (usually one, but not necessarily). This means we need to optimize the number of neurons in the hidden layer(s).
Also, as I have mentioned, we don't really know which data to use. Will Clv-15 (15 days delayed) increase the accuracy of our prediction? Do we need Clv-256? Will it be better to use both of them in the same NN, or will adding Clv-256 ruin our performance?
Using nested cycles to try different input parameters, you can:
Create the NN, same way we did it for the stock data (let me repeate, for the NN, there is no difference between stocks and FOREX, it just happened that I have couple of high quality data files for FOREX that I want to process, while writing this text). Try different combinations of lags. Try different number of neurons in the hidden layer. . and different combinations of different indicators. . e assim por diante.
However, if you try all possible combinations of all possible parameters, you will NEVER get your results, no matter how fast your computer is. Below, we will use couple of tricks to reduce calculations to a bare minimum.
By the way, it may seem, that if you start from one hidden neuron, then increase it to 2, 3 and so on, and at some point the error (quality of the prediction) or the profit (if you test the NN by trading using it) will begin to go down, then you have your winner. Unfortunately, I cannot prove, that after the first "performance peak" there can be no second one. It means, that the error may go like 100, 30, 20, 40, 50 (it was just at its minimum, right?) and then 30, 20, 10, 15, . (the second minimum). We just have to test all reasonable numbers.
Third. Optimization is a two-edged sword. If you over-optimize your code, it may not work outside the data you used to fine-tune it. I will do my best to avoid this pitfall. If you want to do additional optimizations to your code or NN, I advise you to do a research in the Internet, to learn more about hidden problems of this approach. ALso, I am going to pay some attention to the smoothness of the profit curve. The profit that looks like 0, -500, 1000, -100, 10000 may be great, but the profit 0, 100, 200, 300, 400. is better, as it is less risky. We may talk about it later.
Finally, for this example we are going to use FOREX, rather than stock prices. From the point of view of the NN there is no difference, and from my point - Forex is much more fun to trade. If you prefer stocks, the code can easily be modified.
A FOREX Trading Strategy to play with.
First of all, let's create a prototype of our code, one that can easily be optimized in future. It is going to be a trading system, that uses a Neural Network to trade and produces a chart (profit against trade number). It will also calculate drawdown, as a measure of robustness of our trading system.
forex_nn_01.tsc, part 1.
The main difference here is that we use functions, instead of placing all the code in the main block of the program. This way it is much easier to manage.
Second, we have a TestNet function. I am using a very simple algorithm of trading . The CLV indicator is confined to 0 - 1 interval (our version of CLV is), so when the indicator crosses up the dBuyLevel (see code above), I am buying, when it is crossing down the dSellLevel, I am selling.
Obviously, it is not the best trading strategy, but it will do for our purpose (just for now). If you want to improve it, here are some pointers. First, you may want to have a system, that is not ALWAYS in the market. Second, you may want to use more than one indicator as inputs, and maybe, more than one NN, so that the trading decision is made based on few predicted indicators. We will add some improvements to the trading algorithm later.
We use some standard assumptions of the FOREX trading: spread is 5 points, leverade is 100, min. lot is $100 (mini-FOREX).
Let's take a look at our "trading" system. Once again, it is an oversimplified one. An important note: the TestNn() is called last, and it has access to all variables that were created to that point. So if you see a variable that I am using, without initializing it, it probably means that it was initialized in NewNn(), TeachNn() or some other function that was called prior to TestNn().
To make things easier, comments are placed in the code.
forex_nn_01.tsc, part 2.
Few words about the drawdown. There are few ways of calculating it, and we are using what I consider the most "honest". The drawdown is a measure of instability of our system. What is a chance, that it will loose money? Lets say the initial amount is $1000. If the profit goes 100, 200, 300, 400. the drawdown is 0. If it goes 100, 200, 100. then the drawdown is 0.1 (10%), as we have just lost an amount, equal to 1/10 of the initial deposit (from 1200 to 1100).
I would strongly advice against using trading systems with large drawdowns.
Also, here I use a drawdown, that is to be used with variable lot size. However, in the actual samples, that come with the eBook, you will see another version:
As you can see, here we always use 1000 (the initial amount) to calculate the drawdown. The reason is simple: we always use the same lot size (no money management yet), so there is no difference, how much money we have already accumulated on our account, an average profit should be constant. The worse possible scenario in this case looks like this: from the very beginning ($1000 on account) we are loosing money. If we use 1000$ to calculate the drawdown, we will get the worse drawdown. This will help us not to trick ourselves. For example, say, we traded for some time, and we have $10,000$ on our account. Then we loose some money, and we now have $8,000. Then we have recovered, and got $12,000. Good trading system? Provavelmente não.
Let's repeat the logic again, as it is very important (and it will become even more important, when we start doing money management). We trade using fixed size lots. So, statistically, there is no guarantee, that the maximum loss will not happen at the very beginning, when we only have $1000. And if it happens, we will have -1000$ (10,000 - 8,000), so the trading system is probably too risky.
When we talk about the money management (probably, not in this text), we will have to use different approach to drawdown calculation.
Note, that in this trading system, I am using the worse possible scenario: I am buying using High and selling, using Low. Many testers do not follow these rules, and create trading systems, that work fine on historical data. But in the real life, these trading systems have very poor performance. Por quê?
Take a look at the price bar. It has Open, High, Low and Close. Do you know, how the price was moving inside the bar? No. So, let's say, your trading system generated a "buy" signal, at the bottom of the price bar (if dLow.
Note that I am using dLotSize equal 0.1 lot ($100). Obviously, in the "real" trading, you will benefit greatly, if the lot size is calculated depending on the money you have, something like:
forex_nn_01.tsc, part 3.
However, we are doing testing here, not trading. And for testing, we need, among other things, to see how smooth the profit curve is. This is much easier to do if the lot size is the same (in ideal situation, for dLotSize = 100 we will get a straight line, with some positive slope, while in case of the adjustable lot size we will get an exponent, that is much harder to analyze).
Later in this text, we will apply money management rules to our trading system, but not yet.
After we are done with the last part of our testing function, let's walk through the rest of the code.
The following function creates a CLV indicator. It takes the interval as a parameter, which means that we can call it many times, during the optimization, passing different numbers.
Note, that I am using the NN that works in the 0 - 1 interval. The data can be normalized, of course, but I chose to divide the indicator by 2 and to add 0.5, so that it is in 0 - 1 range.
forex_nn_01.tsc, part 4.
To make lag file, we can use the CREATE_LAG_FILE function. Alternatively, we can do it by explicitly providing all the necessary code. In this case, we have more control, and we are going to need it, if we begin varying number of lagged columns and so on.
forex_nn_01.tsc, part 5.
The nRemoveFirst parameter is important. Many functions, like indicators, moving averages, lag generators, for that matter, do not work well within the first few records of the dataset. Let's say we have MA(14) - what will it place in the records 1 - 13? So we choose to simply remove the first few (unreliable) records.
For the NewNn, as well as for all functions of this program, we need to pass as parameters only what can be changed during optimization process. For example, there is no need to pass a "skip before" parameter, as it is always the same.
forex_nn_01.tsc, part 6.
The TeachNn function simply brings up the NN dialog.
forex_nn_01.tsc, part 7.
Finally, we need a charting function. It is not mandatory, but it is always a good idea to see what our profit line looks like. The following code uses the XML to produce a chart, so it is a good idea to read the tutorial. Alternatively, you can draw the chart, rather than saving it in a file. To do it, use one of the samples, that are in the samples/scripts directory. Finally, you can modify the code, to produce HTML, rather than XML. HTML is easier to learn, but the code itself will be a bit less readable.
forex_nn_01.tsc, part 8.
Compile and Run the script.
Bem. As expected, using 7 hours as an interval for the CLV produced very poor results:
FOREX Trading Strategies and Optimization.
The reason for the poor results is quite obvious: we used the Interval, Stop Loss, buy and sell levels and other parameters, that were purely random - we just picked first that came in mind! What if we try few combinations?
FOREX Trading Signals: What to optimize?
First of all, by overoptimizing the buy and sell levels, we can ruin our future performance. However we still can tune them, especially, if the performance is close for close values of buy and sell limits. For example, if we have -10% profit at buy limit equal 0.3, and +1000% profit when it equals 0.35, then there is probably a lucky coincidence, and we should not use 0.35 for our trading system, as in future it will probably not happen again. If, instead, we have -10% and +10% (instead of +1000%), it may be safer to use.
Generally, our trading system should be built for WORSE possible scenario, as if during the "real" trading the performance will be better, then during the test, we will survive, but not the other way around.
We can vary the value for the indicator interval, provided we have enough trades, so that we can be confident, in terms of statistics, in the performance of a system.
We certainly can vary the number of neurons, I don't think it can be overoptimized easily.
We can vary number of inputs and lags for inputs. It is possible to overoptimize this, but it is not very likely to happen.
And, of course, we can try different indicators.
Accurate FOREX Signals: How to optimize?
As have already been mentioned, if we start trying all possible combinations, it will take forever. So we are going to cheat. We will create pre-defined sets of parameters, that we think are reasonable, and pass them to the program.
To make as few calculations as possible, note, that Clv-1 and Clv-2 are, probably, important, but what about Clv-128? And - if we already have Clv-128, do we need Clv-129? Probably, not. So we are going to have something like Clv-1, Clv-2, Clv-4, Clv-8, . Clv-128 with just few variations, which will make our calculation time thousands times shorter.
FOREX Professional System Trading: Can it work at all?
What is it exactly we want to predict? Until this point we have used 1 hour chart for EURUSD, and we were predicting the next bar's CLV. Will the CLV+2 be better? What about CLV+3?
Also, especially considering the poor performance of our first trading system, it would be nice to know, that - at least in the "ideal" world, the goal (profitable trading) can be achieved.
To answer these questions, let's create a simple testing program. We assume, that our prediction is 100 % accurate, and, based on this assumption, we will use CLV+N, not the NN predicted one. That's right - we are going to take data from the future, and to use them instead of the NN prediction. This approach wouldn't work in the real life, of course, but at leats, it will give us some ideas of what to expect.
When looking at the results, please keep in mind, that we are not using any advanced money management, our lot size is set to a minimum $100. If you use variable lot sizes, results will be dramatically different. But even at a lot size set to 0.1 we can see (below) that getting the information from the future is an ultimate trader's "holly graal".
forex_nn_02.tsc, part 1.
You are already familiar with this code, it was used in FOREX_NN_01.TSC. It handles data loading. The only difference is in the part that obtains the list of files in the "images" directory and deletes all files with the. PNG extention. The reason for this code is simple: during our tests we are going to create many - may be, thousands - image files. We don't want them to hung around after we are done. So at the beginning of the script we are deleting images, created by other scripts.
forex_nn_02.tsc, part 2.
Just a few comments. We do not want to try all possible values for, for example, CLV interval. Instead, we can create an array, that contains only values we want to test. Then (see below) we will walk through this array.
Stop losses are important part of any trading strategy, so I have decided to vary them as well. It is a dangerous idea, however, as it is easy to overoptimize the system.
I am planning to test different values for buy and sell levels, but it will be done in cycle, without using arrays.
Unlike in our previous example, we want to have a large XML file, containing many images. To do it, I have moved the code, that is forming the XML header and footer outside of the Chart function. Read one of the online XML tutorials for details.
Note, that I am using 0 as the first lag, which means, that first I am testing the indicator (CLV) that was not "shifted" from the future. Just to get an idea, how good out "trading system" would be without NN (horrible, is the right word. It is loosing all the money).
Cortex uses the Internet Explorer control to display XML pages. When pages grow large, it takes a lot of memory. If your computer cannot handle it, consider creating multiple XML or HTML pages, instead. In the case of forex_nn_02, it should not be a problem, as the page is relatively short. Alternatively (that is what I am doing in scripts later in this text), create XML file, but do not open it from Cortex. Open them using Internet Explorer instead - unlike IE control, the Internet Explorer does not have the memory problem.
Now the code that is trying different combinations of parameters.
forex_nn_02.tsc, part 3.
Here, we are using nested cycles. In every cycle, we are assidning some variable (for example, nInterval for the outer cycle). This way the cycle will assign values of all elements of a corresponding array, one in a time. Then WITHIN it, the inner cycle is used, and so on, so that all combinations of all array elements are tested.
In the innermost cycle, I am calling the Test() function, to "test trade", and Chart() to add a new picture to a list of images saved on disk. Note, that this Chart() does not show any images, until all cycles are completed.
The Test() and CreateClv() functions are almost the same as in the previous example. The only real difference is due to the fact that it is called more then once. To do it, I am calling ARRAY_REMOVE to cleanup arrays.
Also, notice, that we are only creating charts for the combinations of parameters, that produce trading system with positive profit. Otherwise, we call "continue", to skip the Chart() function.
Finally, we have Take Profit now, so our trading system can be a bit more flexible.
forex_nn_02.tsc, part 4.
The Chart() function was broken into two pieces. The header and the footer should be written to the XML file only once, so they were moved to the main part of the program.
Also, I am using the counter, to save files under the different names. The information about parameters is written to the header of an image, so we can easily see which one it is. Finally, images are only saved for winning configurations, meaning the balance at the end should be more, then at the beginning.
forex_nn_02.tsc, part 5.
Run the program (it will take some time to complete). You will end up with a large XML page with images, one for each winning configuration.
Some of the results are great, however, as we used data "from the future", this system will not work in the real life. Actually, if you look at the Test() function, you will notice, that the cycle stops before we reach the last element of arrClose:
for(nBar = nRemoveFirst + 1; nBar.
THIS IS C++, just an example.
As you can see, the code is really simple. Now lets do the same using the SLANG script. As in examples before, we will keep the overall structure of the code, so that this example looks familiar. The only difference is that instead of using the built-in APPLY_NN function, we call the function of our own. The code that we do not use (such as cycles) is commented, but not removed.
Note, that the logic behind it was discussed in Neural Networks and Stock / Forex Trading article already. Briefly, the output of this script is formated to be compatible with the MQL, MetaTrader's scripting engine. MetaTrader is a trading platform we use, if you want something different, like TradeStation, for example, you will have to alter the code to comply to its syntax.
Then, in the following chapters, we are going to insert this code in the MetaTrader's indicator, and to use it to trade.
Porting script to trading platform.
The next step is not really required, but it is something, that may be useful. We are going to create a version of a tsc file (one above), but this time, we will use SLANG (Cortex scripting language) to emulate APPLY_NN function. The reason is, in the next chapter we are going to port it to the scripting language of a MetaTrader trading platform, so it is a good idea to make sure everything works.
After we run this function, we discover, that the result it produces is the same, as the forex_nn_05a produced, which means the code works fine. :
Note, that there is a difference at the beginning of the charts, as "our" NN does not try to process the data at the beginning (where lag is incomplete), while the built-in NN does not "know" about this problem. Of course, it doesn't affect the result, as the beginning of the chart is ignored by using the nRemoveFirst parameter in our script (set to 200, which is guaranteed to be larger, then our lag).
Using third-party trading platform.
We have the NN that (more or less) can be used. We have the script, implementing this NN without calls to the Cortex-specific NN functions. Now we are going to port it to the trading platform that can be used for the real trading, which means it can contact brocker, place orders and earn (or loose) money.
As a trading platform, I am going to use MetaTrader.
Disclaimer: I am not related to MetaQuotes in any way. I do not work for them, I am not their affiliate and so on. I use MetaTrader, ONLY because I like it.
I find this program user-friendly, flexible and powerful, and "not a monster". Also, it is free (compare to other packages of this class).
The only (minor) problem is that it is not always easy to find the dealer using MT in your area. Then, when you do a research, you may find couple of brockers, with screenshots on their web sites, that look suspiciously familiar. Yes, they use MetaTrader, but they don't call it MetaTrader!
I have asked for clarification at the company's forum, and they have told me, that they don't reveal brockers using their services. Very strange.
One of the brockers that is not hiding the fact they use MT, is Alpari. They will allow you to open a Demo account, so that you can trade in a real time, but without risking your money.
I am not going to recommeng services of Alpari. Once again, I am not being paid for that. Try their Demo account, and use your own judgement. Or you can start your own research at Internet forums.
Finally, if you do not like the MT, you can probably follow the example below using TS, MS or some other trading platform. This is just an example.
Our MT-based trading system will include two files, the indicator and an expert. This is the way they call it in MQL (scripting language of MT), and I am going to follow this naming convention.
The indicator implements the neural network and draws a chart. An expert takes these data and does trading. As MetaTrader has a "strategy tester", we will be able to test our strategy, to see how good it is.
I will assume, that you are familiar with MQL programming, it is quite close to SLANG and tutorials can be found both at MetaQuotes and Alpari.
Finally, I am using the code structure, that is borrowed from MetaQuotes forum, permission to use it the author of the corresponding posts had granted me permission to use fragments of his code.
Also, as some of our MetaTrader code is the same for all experts and indicators, we moved it to a separate library file. MetaTrader's libraries are nothing but includable files. This library takes care of synhronization, when two or more expert are trying to run in the same time, as well as of few other things. If you use MetaTrader, it will help you to create robust experts, in any case, the MQL language is easy to understand.
mylib. mql, a helper library.
The code should look familiar, all I did was re-writing it, using slightly different language syntax of MQL.
This indicator has two buffers, and draws two lines, one for the original NOC, and one for the NN-predicted NOC. For trading, you don't have to draw both indicator lines, of course (see MQL tutorials to learn how to do it), but I have decided to show them together, so you can compare.
Another difference, that you should know about, is the way MT performs testing. It may, in some cases, be more accurate, then one we did (we did the worse case scenario). Of course, you can always to change the SLANG script from the examples above, to implement any logic you want.
The result of our testing in MT is a bit better, then in Cortex, due to all these reasons.
Keep in mind, that MT calculates the DD in a different way. I still think, that my way is better.
In should be especially noted, that no additional optimization had been performed using MetaTrader's optimizer. We have just plugged our MTS (mechanical trading system) in, and it worked as expected.
É isso. You can now create Cortex Neural Network, optimize it to do trading, and to port it to the trading platform of your choice.

Комментарии

Популярные сообщения из этого блога

Download de livros de scalping forex

Livros sobre indicadores técnicos. O que significam os indicadores técnicos? Quanto eles são úteis para você? Quais são os princípios básicos que você deve saber? Como usá-los? Como implementar o melhor método de cálculo? Indicadores de negociação de Bill Williams. De acordo com Bill Williams, para alcançar o sucesso no campo comercial, um comerciante deve conhecer a estrutura exata e completa do mercado. Isso pode ser alcançado através da análise do mercado em cinco dimensões e levando em consideração certos indicadores Forex. Osciladores de Forex. O que é Oscillator e por que precisamos disso? Este é um índice de análise técnica que é usado para prever o comportamento do mercado Forex. O valor do oscilador flutua no intervalo limitado, enquanto os limites mais baixos e mais altos dessa faixa correspondem aos estados de "overbought" e "oversold" do mercado. Os instrumentos de análise de gráficos podem ser aplicados aos osciladores. Indicadores de Tendências Forex. ...

Exemplo de estratégias de negociação de alta freqüência

Exemplo de estratégias de negociação de alta freqüência Obter através da App Store Leia esta publicação em nosso aplicativo! Onde posso encontrar alguns exemplos de algoritmos de negociação de alta frequência ou stat arborativos além de negociação básica de livros didáticos? tem vários algoritmos de nome. Eu entendo que a maioria dos algoritmos HFT são proprietários, mas estou procurando exemplos de estratégias HFT (mesmo as que não ganham mais dinheiro) apenas para entender o que é. Haim Bodek trabalhou para Goldman e UBS e depois teve sua própria empresa comercial. Ele começou a Consultar em estratégias HFT e foi mencionado em Dark Pools por Scott Patterson. Confira a introdução da estratégia '0+'. Como afirmou uma resposta anterior, ninguém dará uma estratégia vencedora. O Guia do Heretic para Finanças Globais: Hacking the Future of Money. Aventuras Anárquicas em Artes, Ativismo, Antropologia e Economia Alternativa. Quarta-feira, 17 de junho de 2015. Surrealismo algorítmico...

Ets revisão do sistema de negociação

O Sistema de Comércio de Emissões da UE (EU ETS) O Sistema de Comércio de Emissões da UE explicou. O sistema de comércio de emissões da UE (EU ETS) é uma pedra angular da política da UE para combater as alterações climáticas e a sua ferramenta chave para reduzir as emissões de gases com efeito de estufa de forma rentável. É o primeiro mercado de carbono do mundo e continua sendo o maior. opera em 31 países (todos os 28 países da UE, mais a Islândia, o Liechtenstein e a Noruega) limita as emissões de mais de 11 mil instalações de energia pesada (centrais eléctricas e instalações industriais) e as companhias aéreas que operam entre esses países cobre cerca de 45% dos gases de efeito estufa da UE emissões. Para uma visão geral detalhada, veja: Um sistema "cap and trade". O EU ETS trabalha no princípio do "capital e do comércio". Um limite é fixado na quantidade total de certos gases de efeito estufa que podem ser emitidos por instalações cobertas pelo sistema. A tampa ...