Tuesday, 4 July 2017

Online Time Series Smoothing Algorithm Forex


Introdução O artigo Previsão de séries temporais usando suavização exponencial 1 forneceu um breve resumo dos modelos de suavização exponencial, ilustrou uma das possíveis abordagens para otimizar os parâmetros do modelo e, em última instância, propôs o indicador de previsão desenvolvido Com base no modelo de crescimento linear com amortecimento. Este artigo representa uma tentativa de aumentar um pouco a precisão deste indicador de previsão. É complicado prever cotações de moedas ou obter uma previsão bastante confiável, mesmo para três ou quatro passos à frente. No entanto, como no artigo anterior desta série, vamos produzir previsões de 12 passos à frente, percebendo claramente que será impossível obter resultados satisfatórios em um horizonte tão longo. As primeiras etapas da previsão com os intervalos de confiança mais estreitos devem, portanto, ser dada a máxima atenção. Uma previsão de 10 a 12 passos é destinada principalmente à demonstração de características comportamentais de diferentes modelos e métodos de previsão. Em qualquer caso, a precisão da previsão obtida para qualquer horizonte pode ser avaliada usando os limites do intervalo de confiança. Este artigo tem como objetivo essencial a demonstração de alguns métodos que podem ajudar a atualizar o indicador, conforme estabelecido no artigo 1. O algoritmo para encontrar o mínimo de uma função de várias variáveis ​​que é aplicado no desenvolvimento dos indicadores foi tratado no anterior Artigo e, portanto, não será aqui repetidamente descrito. Para não sobrecarregar o artigo, os insumos teóricos serão mantidos ao mínimo. 1. Indicador inicial O indicador IndicatorES. mq5 (ver artigo 1) será usado como ponto de partida. Para a compilação do indicador precisamos de IndicatorES. mq5, CIndicatorES. mqh e PowellsMethod. mqh, todos localizados no mesmo diretório. Os arquivos podem ser encontrados no arquivo files2.zip no final do artigo. Vamos atualizar as equações que definem o modelo exponencial de suavização utilizado no desenvolvimento deste indicador - o modelo de crescimento linear com amortecimento. O único parâmetro de entrada do indicador é o valor que determina o comprimento do intervalo de acordo com o qual os parâmetros do modelo serão otimizados e os valores iniciais (intervalo de estudo) selecionados. Após a determinação dos valores ótimos dos parâmetros do modelo em um dado intervalo e os cálculos necessários, a previsão, o intervalo de confiança ea linha correspondente à previsão de um passo à frente são produzidos. Em cada nova barra, os parâmetros são otimizados e a previsão é feita. Como o indicador em questão vai ser atualizado, o efeito das alterações que faremos será avaliado usando as seqüências de teste do arquivo Files2.zip localizado no final do artigo. O arquivo de dados Dataset2 contém arquivos com as cotações EURUSD, USDCHF, USDJPY e DXY do Dólar dos Estados Unidos. Cada um deles é fornecido para três intervalos de tempo, sendo M1, H1 e D1. Os valores abertos salvos nos arquivos estão localizados de modo que o valor mais recente está no final do arquivo. Cada arquivo contém 1200 elementos. Os erros de previsão serão estimados calculando o coeficiente de MAPE (Mean Absolute Percentage Error). Vamos dividir cada uma das doze seqüências de teste em 50 seções sobrepostas contendo 80 elementos cada e calcular o valor de MAPE para cada uma delas. A média das estimativas assim obtidas será utilizada como índice de erro de previsão em relação aos indicadores colocados em comparação. Valores MAPE para erros de previsão de duas e três etapas serão calculados da mesma maneira. Tais estimativas médias serão ainda indicadas como se segue: MAPE1 estimativa média do erro de previsão de um passo à frente MAPE2 estimativa média do erro de previsão de dois passos MAPE3 estimativa média do erro de previsão de três passos MAPE1-3 média (MAPE1MAPE2MAPE3) / 3. Ao calcular o valor MAPE, o valor absoluto de erro de previsão é em cada etapa dividida pelo valor atual da seqüência. A fim de evitar a divisão por zero ou obter valores negativos ao fazê-lo, as sequências de entrada são obrigados a tomar apenas valores positivos não nulos, como no nosso caso. Os valores da estimativa para o nosso indicador inicial são mostrados na Tabela 1. Tabela 1. Estimativas de erro de previsão do indicador inicial Os dados exibidos na Tabela 1 são obtidos usando o script ErrorsIndicatorES. mq5 (do arquivo files2.zip localizado no final do artigo) . Para compilar e executar o script, é necessário que CIndicatorES. mqh e PowellsMethod. mqh estão localizados no mesmo diretório como ErrorsIndicatorES. mq5 e as seqüências de entrada estão no diretório FilesDataset2. Após a obtenção das estimativas iniciais dos erros de previsão, podemos agora proceder à actualização do indicador em causa. 2. Critério de Otimização Os parâmetros do modelo no indicador inicial conforme estabelecido no artigo Previsão de Séries Temporais Utilizando Suavização Exponencial foram determinados minimizando a soma dos quadrados do erro de previsão de um passo à frente. Parece lógico que os parâmetros do modelo ótimos para uma previsão de um passo em frente não podem gerar erros mínimos para uma previsão mais adiante. Seria, naturalmente, desejável minimizar erros de previsão de 10 a 12 passos, mas obter uma previsão satisfatória sobre o intervalo dado para as sequências em consideração seria uma missão impossível. Sendo realista, ao otimizar os parâmetros do modelo, usaremos a soma dos quadrados dos erros de previsão de um, dois e três passos de frente como a primeira atualização do nosso indicador. Espera-se que o número médio de erros diminua ligeiramente ao longo dos três primeiros passos da previsão. Claramente, tal actualização do indicador inicial não diz respeito aos seus principais princípios estruturais, mas apenas altera o critério de optimização de parâmetros. Portanto, não podemos esperar que a precisão da previsão aumente várias vezes, embora o número de erros de previsão de duas e três etapas deve cair um pouco. Para comparar os resultados da previsão, criamos a classe CMod1 semelhante à classe CIndicatorES introduzida no artigo anterior com a função objetivo modificada func. Função func da classe CIndicatorES inicial: Após algumas modificações, a função func aparece agora da seguinte forma: Agora, ao calcular a função objetivo, é usada a soma dos quadrados dos erros de previsão de um, dois e três passos. Além disso, com base nessa classe, o script ErrorsMod1.mq5 foi desenvolvido permitindo estimar os erros de previsão, como o já mencionado script ErrorsIndicatorES. mq5. CMod1.mqh e ErrorsMod1.mq5 estão localizados no arquivo files2.zip no final do artigo. A Tabela 2 exibe as estimativas de erro de previsão para as versões inicial e atualizada. Tabela 2. Comparação das estimativas de erro de previsão Como pode ser visto, os coeficientes de erro MAPE2 e MAPE3 e o valor médio MAPE1-3 realmente se revelaram ligeiramente mais baixos para as sequências consideradas. Então vamos salvar esta versão e proceder à modificação do nosso indicador. 3. Ajuste de Parâmetros no Processo de Suavização A idéia de alterar os parâmetros de suavização dependendo dos valores atuais da seqüência de entrada não é nova ou original e vem do desejo de ajustar os coeficientes de suavização para que permaneçam ótimos, Natureza da sequência de entrada. Algumas maneiras de ajustar os coeficientes de suavização são descritas na literatura 2, 3. Para melhorar ainda mais o indicador, usaremos o modelo com o coeficiente de suavização de mudança dinâmica esperando que o uso do modelo de suavização exponencial adaptativa nos permita aumentar a precisão de previsão Do nosso indicador. Infelizmente, quando usados ​​em algoritmos de previsão, a maioria dos métodos adaptativos nem sempre produz os resultados desejados. A seleção do método adaptativo adequado pode parecer muito pesada e demorada, portanto, no nosso caso, faremos uso dos achados fornecidos na literatura 4 e tentamos empregar a abordagem de Alisamento Exponencial de Transição Suave (STES) estabelecida no artigo 5 A essência da abordagem é claramente delineada no artigo especificado, por isso vamos deixá-lo aqui e prosseguir diretamente para as equações para o nosso modelo (ver o início do artigo especificado), tendo em consideração o uso do coeficiente de suavização adaptativa. Como podemos ver agora, o valor do coeficiente de alisamento alfa é calculado em cada passo do algoritmo e depende do erro de previsão ao quadrado. Os valores dos coeficientes b e g determinam o efeito do erro de previsão no valor alfa. Em todos os outros aspectos, as equações para o modelo empregado permaneceram inalteradas. Informações adicionais sobre o uso da abordagem STES podem ser encontradas no artigo 6. Enquanto nas versões anteriores, tivemos que determinar o valor ótimo do coeficiente alfa sobre a seqüência de entrada dada, existem agora dois coeficientes adaptativos b e g que são Sujeito a otimização e o valor alfa será dinamicamente determinado no processo de suavização da seqüência de entrada. Esta actualização é implementada na forma da classe CMod2. As principais alterações (como o tempo anterior) diziam respeito principalmente à func função que agora aparece da seguinte forma. Ao desenvolver esta função, a equação que define o valor do coeficiente alfa foi ligeiramente modificada. Isto foi feito para estabelecer o limite do valor máximo e mínimo admissível deste coeficiente em 0,05 e 0,95, respectivamente. Para estimar os erros de previsão, como foi feito anteriormente, o script ErrorsMod2.mq5 foi escrito com base na classe CMod2. CMod2.mqh e ErrorsMod2.mq5 estão localizados no arquivo files2.zip no final do artigo. Os resultados do script são mostrados na Tabela 3. Tabela 3. Comparação das estimativas de erro de previsão Como a Tabela 3 sugere, o uso do coeficiente de suavização adaptativo tem permitido, em média, diminuir ligeiramente os erros de previsão para nossas seqüências de teste. Assim, após duas atualizações, conseguimos diminuir o coeficiente de erro MAPE1-3 em aproximadamente dois por cento. Apesar de um resultado de atualização bastante modesto, vamos ficar com a versão resultante e deixar novas atualizações fora do escopo do artigo. Como um próximo passo, seria interessante tentar usar a transformação Box-Cox. Esta transformação é usada principalmente para aproximar a distribuição de seqüência inicial para a distribuição normal. No nosso caso, ela poderia ser utilizada para transformar a seqüência inicial, calcular a previsão e transformar inversamente a previsão. O coeficiente de transformação aplicado ao fazê-lo deve ser selecionado para que o erro de previsão resultante seja minimizado. Um exemplo de utilização da transformação de Box-Cox nas seqüências de previsão pode ser encontrado no artigo 7. 4. Intervalo de confiança da previsão O intervalo de confiança da previsão no indicador IndicatorES. mq5 inicial (estabelecido no artigo anterior) foi calculado de acordo com a análise Expressões derivadas para o modelo de alisamento exponencial selecionado 8. As mudanças feitas em nosso caso levaram a mudanças no modelo em consideração. O coeficiente de alisamento variável torna inadequado usar as expressões analíticas acima mencionadas para estimativa do intervalo de confiança. O fato de que as expressões analíticas usadas anteriormente foram derivadas com base no pressuposto de que a distribuição de erro de previsão é simétrica e normal pode constituir uma razão adicional para alterar o método de estimação do intervalo de confiança. Esses requisitos não são atendidos para a nossa classe de seqüências ea distribuição de erro de previsão pode não ser normal ou simétrica. Ao estimar o intervalo de confiança no indicador inicial, calculou-se, em primeiro lugar, a variância de erro de previsão em um passo da seqüência de entrada, seguida pelo cálculo da variância para um avanço de dois, três e mais passos Previsão com base no valor obtido da variância do erro de previsão de um passo em frente utilizando as expressões analíticas. A fim de evitar o uso de expressões analíticas, existe uma saída simples pela qual a variância para uma previsão de dois, três e mais avanço é calculada diretamente a partir da seqüência de entrada, bem como a variância para uma etapa de um passo - Previsão antecipada. No entanto, esta abordagem tem uma desvantagem significativa: em curtas sequências de entrada, as estimativas do intervalo de confiança serão amplamente dispersas eo cálculo da variância eo erro quadrático médio não permitirão aliviar as restrições sobre a normalidade esperada dos erros. Uma solução neste caso pode ser encontrada na utilização de bootstrap não paramétrico (reamostragem) 9. A espinha dorsal da idéia expressa simplesmente: quando se faz uma amostragem aleatória (distribuição uniforme) com substituição da seqüência inicial, a distribuição do gerado A sequência artificial será a mesma da inicial. Suponhamos que temos uma seqüência de entrada de N membros gerando uma seqüência pseudo-aleatória uniformemente distribuída sobre o intervalo de 0, N-1 e usando esses valores como índices quando amostrando a matriz inicial, podemos gerar uma seqüência artificial de uma substancial Comprimento maior do que o inicial. Dito isto, a distribuição da sequência gerada será a mesma (quase a mesma) que a da inicial. O procedimento bootstrap para estimativa dos intervalos de confiança pode ser o seguinte: Determine os valores iniciais ótimos dos parâmetros do modelo, seus coeficientes e coeficientes adaptativos a partir da seqüência de entrada para o modelo de suavização exponencial obtido como resultado da modificação. Os parâmetros ótimos são, como antes, determinados usando o algoritmo que emprega o método de pesquisa Powells. Usando os parâmetros de modelo ótimos determinados, passam pela seqüência inicial e formam uma matriz de erros de previsão de um passo à frente. O número dos elementos da matriz será igual ao comprimento da seqüência de entrada N Alinhar os erros subtraindo de cada elemento da matriz de erros o valor médio da mesma Usando o gerador de seqüência pseudo-aleatória, gere índices dentro da faixa de 0, N-1 E usá-los para formar uma seqüência artificial de erros sendo 9999 elementos de comprimento (reamostragem) Formam um array contendo 9999 valores da seqüência de pseudo-entrada, inserindo os valores da matriz de erro gerado artificialmente nas equações que definem o modelo atualmente usado. Em outras palavras, enquanto anteriormente precisamos inserir os valores da seqüência de entrada nas equações do modelo, calculando assim o erro de previsão, agora os cálculos inversos são feitos. Para cada elemento da matriz, o valor de erro é inserido para calcular o valor de entrada. Como resultado, obtemos a matriz de 9999 elementos contendo a seqüência com a mesma distribuição da seqüência de entrada, enquanto que são de comprimento suficiente para estimar diretamente os intervalos de confiança previstos. Em seguida, estimar os intervalos de confiança usando a seqüência gerada de comprimento adequado. Para isso, exploraremos o fato de que se a matriz de erros de previsão gerada é classificada em ordem crescente, as células de matriz com índices 249 e 9749 para a matriz contendo 9999 valores terão os valores correspondentes aos limites do intervalo de confiança 95.Para obter uma estimativa mais precisa dos intervalos de predição, o comprimento do array será ímpar. Em nosso caso, os limites dos intervalos de confiança da previsão são estimados da seguinte forma: Usando os parâmetros de modelo otimizados como determinado anteriormente, percorrer a seqüência gerada e formar uma matriz de 9999 erros de previsão um passo à frente. , Selecione os valores com os índices 249 e 9749 que representam os limites do intervalo de confiança 95 Repita os passos 1, 2 e 3 para erros de previsão de dois, três e mais avanço. Esta abordagem para estimar os intervalos de confiança tem suas vantagens e desvantagens. Entre suas vantagens está a ausência de suposições quanto à natureza da distribuição dos erros de previsão. Eles não têm de ser normalmente ou simetricamente distribuídos. Além disso, esta abordagem pode ser útil onde é impossível derivar expressões analíticas para o modelo em uso. Um aumento dramático no âmbito requerido de cálculos e dependência das estimativas sobre a qualidade do gerador de sequência pseudo-aleatório utilizado pode ser considerado as suas desvantagens. A abordagem proposta para estimar os intervalos de confiança usando resampling e quantiles é bastante primitiva e deve haver maneiras de melhorá-lo. Mas uma vez que os intervalos de confiança no nosso caso são apenas destinados à avaliação visual, a precisão fornecida pela abordagem acima pode parecer ser bastante suficiente. 5. Versão Modificada do Indicador Tendo em conta as actualizações introduzidas no artigo, foi desenvolvido o indicador ForecastES. mq5. Para a reamostragem, usamos o gerador de seqüências pseudo-aleatórias proposto anteriormente no artigo 11. O gerador padrão MathRand () gerou resultados ligeiramente mais pobres, provavelmente devido ao fato de que o intervalo de valores que gerou 0,32767 não foi suficientemente amplo. Ao compilar o indicador ForecastES. mq5, PowellsMethod. mqh, CForeES. mqh e RNDXor128.mqh devem estar localizados no mesmo diretório com ele. Todos esses arquivos podem ser encontrados no arquivo fore. zip. Abaixo está o código-fonte do indicador ForecastES. mq5. Para fins de demonstração melhor, o indicador foi executado, na medida do possível, como um código de linha reta. Nenhuma otimização foi pretendida ao codificá-lo. As Figuras 1 e 2 demonstram os resultados de operação do indicador para dois casos diferentes. Figura 1. Exemplo da primeira operação do indicador ForecastES. mq5 Figura 2. Exemplo de segunda operação do indicador ForecastES. mq5 A Figura 2 mostra claramente que o intervalo de confiança da previsão 95 é assimétrico. Isto é devido ao fato de que a seqüência de entrada contém outliers consideráveis ​​que resultaram em distribuição assimétrica dos erros de previsão. Os sites mql4 e mql5 anteriormente forneceram indicadores extrapoladores. Vamos tomar um desses - arextrapolatorofprice. mq5 e definir seus valores de parâmetro como mostrado na Figura 3 para comparar seus resultados com os resultados obtidos usando o indicador que desenvolvemos. Figura 3. Configurações do indicador arextrapolatorofprice. mq5 A operação destes dois indicadores foi comparada visualmente em diferentes prazos para o EURUSD e o USDCHF. Na superfície, parece que a direção da previsão por ambos os indicadores coincide na maioria dos casos. No entanto, em observações mais longas, pode-se encontrar divergências sérias. Dito isto, arextrapolatorofprice. mq5 sempre produzirá uma linha de previsão mais quebrada. Um exemplo de operação simultânea dos indicadores ForecastES. mq5 e arextrapolatorofprice. mq5 é mostrado na Figura 4. Figura 4. Comparação dos resultados da previsão A previsão produzida pelo indicador arextrapolatorofprice. mq5 é exibida na Figura 4 como uma linha sólida laranja-vermelho. Conclusão Resumo dos resultados referentes a este e ao artigo anterior: Modelos de suavização exponencial utilizados na previsão de séries temporais foram propostos Soluções de programação para a implementação dos modelos foram propostos Uma rápida compreensão das questões relacionadas à seleção dos valores iniciais ótimos e parâmetros do modelo foi Dado Uma implementação de programação do algoritmo para encontrar o mínimo de uma função de várias variáveis ​​usando o método Powells foi fornecido Soluções de programação para a otimização de parâmetros do modelo de previsão usando a seqüência de entrada foram propostos Alguns exemplos simples de atualização do algoritmo de previsão foram demonstrados Um método para Estimando intervalos de confiança de previsão usando bootstrapping e quantiles foi resumido brevemente O indicador de previsão ForecastES. mq5 foi desenvolvido contendo todos os métodos e algoritmos descritos nos artigos Alguns links para os artigos, revistas e livros foram dados relativos a este assunto. Em relação ao indicador resultante ForecastES. mq5, deve-se notar que o algoritmo de otimização empregando o método de Powells pode, em certos casos, deixar de determinar o mínimo da função objetivo com uma certa precisão. Neste caso, o número máximo permitido de iterações será atingido e uma mensagem relevante aparecerá no log. Esta situação, no entanto, não é processada de qualquer forma no código do indicador que é bastante aceitável para a demonstração dos algoritmos definidos no artigo. No entanto, quando se trata de aplicações graves, esses casos devem ser monitorados e processados ​​de uma forma ou de outra. Para desenvolver e melhorar ainda mais o indicador de previsão, poderíamos sugerir a utilização de vários modelos de previsão diferentes simultaneamente em cada passo com vista a uma selecção adicional de um deles utilizando p. O critério de informação Akaikes. Ou, no caso de utilizar vários modelos de natureza similar, para calcular o valor médio ponderado dos seus resultados de previsão. Os coeficientes de ponderação, neste caso, podem ser selecionados dependendo do coeficiente de erro de previsão de cada modelo. O tema das séries temporais de previsão é tão largo que, infelizmente, esses artigos mal arranharam a superfície de algumas das questões pertinentes. Espera-se que estas publicações ajudem a chamar a atenção dos leitores para as questões de previsão e futuras obras nesta área. ReferênciasMetaTrader 5 - Estatística e análise Previsão de séries temporais usando suavização exponencial Introdução Existe atualmente um grande número de vários métodos de previsão bem conhecidos que se baseiam apenas na análise de valores passados ​​de uma seqüência de tempo, isto é, métodos que empregam princípios normalmente usados ​​em técnicas análise. O principal instrumento destes métodos é o esquema de extrapolação em que as propriedades da sequência identificadas a um determinado intervalo de tempo ultrapassam os seus limites. Ao mesmo tempo, assume-se que as propriedades da sequência no futuro serão as mesmas do passado e do presente. Um esquema de extrapolação mais complexo que envolve um estudo da dinâmica de mudanças nas características da seqüência com devida consideração por tais dinâmicas dentro do intervalo de previsão é menos freqüentemente usado na previsão. Os métodos de previsão mais conhecidos baseados na extrapolação são talvez os que utilizam o modelo de média móvel (ARIMA) autoregressive integrado. A popularidade destes métodos é principalmente devido a obras de Box e Jenkins que propuseram e desenvolveram um modelo ARIMA integrado. Há, naturalmente, outros modelos e métodos de previsão para além dos modelos introduzidos pela Box e Jenkins. Este artigo abrangerá brevemente modelos mais simples - exponencial suavização modelos propostos por Holt e Brown bem antes da aparição de obras de Box e Jenkins. Apesar das ferramentas matemáticas mais simples e claras, a previsão utilizando modelos de suavização exponencial conduz frequentemente a resultados comparáveis ​​com os resultados obtidos utilizando o modelo ARIMA. Isso não é surpreendente, pois os modelos exponenciais de suavização são um caso especial do modelo ARIMA. Em outras palavras, cada modelo exponencial de suavização em estudo neste artigo tem um correspondente modelo equivalente ARIMA. Estes modelos equivalentes não serão considerados no artigo e são mencionados apenas para informação. Sabe-se que a previsão em cada caso particular requer uma abordagem individual e envolve normalmente uma série de procedimentos. Análise de seqüência de tempo para valores faltantes e outliers. Ajuste destes valores. Identificação da tendência e seu tipo. Determinação da periodicidade da sequência. Verifique a estacionaridade da seqüência. Análise de pré-processamento de sequências (tomando os logaritmos, diferenciando, etc.). Seleção do modelo. Determinação do parâmetro do modelo. Previsão com base no modelo selecionado. Modelo de avaliação da precisão das previsões. Análise de erros do modelo selecionado. Determinação da adequação do modelo selecionado e, se necessário, substituição do modelo e retorno aos itens anteriores. Esta não é, de longe, a lista completa de acções necessárias para uma previsão eficaz. Deve-se enfatizar que a determinação do parâmetro do modelo ea obtenção dos resultados da previsão são apenas uma pequena parte do processo geral de previsão. Mas parece ser impossível cobrir toda a gama de problemas de uma forma ou de outra relacionada com a previsão num artigo. Portanto, este artigo tratará somente de modelos de suavização exponencial e usará citações de moedas não pré-processadas como seqüências de teste. As questões de acompanhamento certamente não podem ser evitadas no artigo, mas elas só serão abordadas na medida em que forem necessárias para a revisão dos modelos. 1. Estacionaridade A noção de extrapolação propriamente dita implica que o desenvolvimento futuro do processo em estudo será o mesmo que no passado e no presente. Em outras palavras, trata-se de estacionaridade do processo. Os processos estacionários são muito atrativos do ponto de vista da previsão, mas infelizmente não existem na natureza, pois qualquer processo real está sujeito a mudanças no curso de seu desenvolvimento. Os processos reais podem ter expectativa, variância e distribuição marcadamente diferentes ao longo do tempo, mas os processos cujas características mudam muito lentamente podem provavelmente ser atribuídos a processos estacionários. Muito lentamente neste caso significa que as mudanças nas características do processo dentro do intervalo de observação finito parecem ser tão insignificantes que tais mudanças podem ser negligenciadas. É claro que quanto mais curto o intervalo de observação disponível (amostra curta), maior a probabilidade de tomar a decisão errada no que diz respeito à estacionariedade do processo como um todo. Por outro lado, se estivermos mais interessados ​​no estado do processo em um momento posterior planejando fazer uma previsão de curto prazo, a redução no tamanho da amostra pode, em alguns casos, levar ao aumento da precisão dessa previsão. Se o processo estiver sujeito a alterações, os parâmetros de seqüência determinados dentro do intervalo de observação serão diferentes fora de seus limites. Assim, quanto maior o intervalo de previsão, maior o efeito da variabilidade das características da sequência no erro de previsão. Devido a este facto, temos de limitar-nos a uma previsão de curto prazo apenas uma redução significativa no intervalo de previsão permite esperar que as características de seqüência lentamente mudando não resultará em erros de previsão consideráveis. Além disso, a variabilidade dos parâmetros de seqüência leva ao fato de que o valor obtido ao estimar pelo intervalo de observação é calculado como média, pois os parâmetros não permaneceram constantes dentro do intervalo. Os valores dos parâmetros obtidos, portanto, não estarão relacionados com o último instante deste intervalo, mas refletirão uma certa média deles. Infelizmente, é impossível eliminar completamente este fenômeno desagradável, mas pode ser diminuído se o comprimento do intervalo de observação envolvido na estimação do parâmetro do modelo (intervalo de estudo) for reduzido na medida do possível. Ao mesmo tempo, o intervalo de estudo não pode ser encurtado indefinidamente porque se extremamente reduzido, certamente irá diminuir a precisão da seqüência parâmetro estimativa. Deve procurar-se um compromisso entre o efeito de erros associados à variabilidade das características da sequência e o aumento de erros devido à extrema redução no intervalo de estudo. Tudo isso se aplica plenamente à previsão utilizando modelos exponenciais de suavização, uma vez que se baseiam no pressuposto de estacionariedade de processos, como os modelos ARIMA. No entanto, por uma questão de simplicidade, vamos aqui assumir convencionalmente que os parâmetros de todas as sequências consideradas variam dentro do intervalo de observação mas de uma forma tão lenta que estas alterações podem ser negligenciadas. Assim, o artigo abordará questões relacionadas com a previsão a curto prazo de sequências com características de mudança lenta, com base em modelos de suavização exponencial. A previsão de curto prazo deve, neste caso, significar uma previsão para um, dois ou mais intervalos de tempo à frente, em vez de prever para um período de menos de um ano, como é normalmente entendido em economia. 2. Sequências de Teste Ao escrever este artigo, foram utilizadas as cotações EURRUR, EURUSD, USDJPY e XAUUSD anteriormente guardadas para M1, M5, M30 e H1. Cada um dos arquivos salvos contém 1100 valores abertos. O valor mais antigo está localizado no início do arquivo eo mais recente no final. O último valor salvo no arquivo corresponde à hora em que o arquivo foi criado. Arquivos contendo sequências de teste foram criados usando o script HistoryToCSV. mq5. Arquivos de dados e script com o qual eles foram criados estão localizados no final do artigo no arquivo Files. zip. Como já mencionado, as citações salvas são usadas neste artigo sem ser pré-processado apesar dos problemas óbvios que eu gostaria de chamar a sua atenção. Por exemplo, as cotações EURRURH1 durante o dia contêm de 12 a 13 barras, as cotações XAUUSD às sextas-feiras contêm uma barra menos do que em outros dias. Estes exemplos demonstram que as citações são produzidas com intervalos de amostragem irregulares, isto é totalmente inaceitável para algoritmos concebidos para trabalhar com sequências de tempo correctas que sugerem ter um intervalo de quantificação uniforme. Mesmo se os valores de cotação ausentes forem reproduzidos usando extrapolação, a questão relativa à falta de cotações nos fins de semana permanece aberta. Podemos supor que os eventos que ocorrem no mundo nos fins de semana têm o mesmo impacto sobre a economia mundial do que nos eventos do dia da semana. Revoluções, atos da natureza, escândalos de alto perfil, mudanças governamentais e outros eventos mais ou menos grandes desse tipo podem ocorrer a qualquer momento. Se tal evento acontecesse no sábado, dificilmente teria uma menor influência nos mercados mundiais do que ocorreu num dia da semana. É talvez esses eventos que levam a lacunas em citações tão freqüentemente observadas no final da semana de trabalho. Aparentemente, o mundo continua seguindo suas próprias regras, mesmo quando o FOREX não opera. Ainda não está claro se os valores nas citações correspondentes aos fins-de-semana que se destinam a uma análise técnica devem ser reproduzidos e que benefício poderia dar. Obviamente, essas questões estão além do escopo deste artigo, mas a primeira vista uma seqüência sem lacunas parece ser mais apropriada para análise, pelo menos em termos de detecção de componentes cíclicas (sazonais). A importância da preparação preliminar dos dados para uma análise mais aprofundada dificilmente pode ser superestimada no nosso caso é uma questão independente importante, uma vez que as cotações, tal como aparecem no Terminal, não são geralmente adequadas para uma análise técnica. Para além das questões acima relacionadas com a lacuna, há uma série de outros problemas. Ao formar as cotações, por exemplo, é atribuído um ponto de tempo fixo valores abertos e fechados que não pertencem a ele, estes valores correspondem ao tempo de formação de carraça em vez de um momento fixo de um gráfico de tempo seleccionado, enquanto que é vulgarmente conhecido que carrapatos São por vezes muito raros. Another example can be seen in complete disregard of the sampling theorem, as nobody can guarantee that the sampling rate even within a minute interval satisfies the above theorem (not to mention other, bigger intervals). Furthermore, one should bear in mind the presence of a variable spread which in some cases may be superimposed on quote values. Let us however leave these issues out of the scope of this article and get back to the primary subject. 3. Exponential Smoothing Let us first have a look at the simplest model , X(t) (simulated) process under study, L(t) variable process level, r(t) zero mean random variable. As can be seen, this model comprises the sum of two components we are particularly interested in the process level L(t) and will try to single it out. It is well-known that the averaging of a random sequence may result in decreased variance, i. e. reduced range of its deviation from the mean. We can therefore assume that if the process described by our simple model is exposed to averaging (smoothing), we may not be able to get rid of a random component r(t) completely but we can at least considerably weaken it thus singling out the target level L(t) . For this purpose, we will use a simple exponential smoothing (SES). In this well known formula, the degree of smoothing is defined by alpha coefficient which can be set from 0 to 1. If alpha is set to zero, new incoming values of the input sequence X will have no effect whatsoever on the smoothing result. Smoothing result for any time point will be a constant value. Consequently, in extreme cases like this, the nuisance random component will be fully suppressed yet the process level under consideration will be smoothed out to a straight horizontal line. If the alpha coefficient is set to one, the input sequence will not be affected by smoothing at all. The level under consideration L(t) will not be distorted in this case and the random component will not be suppressed either. It is intuitively clear that when selecting the alpha value, one has to simultaneously satisfy the conflicting requirements. On the one hand, the alpha value shall be near zero in order to effectively suppress the random component r(t) . On the other, it is advisable to set the alpha value close to unity not to distort the L(t) component we are so interested in. In order to obtain the optimal alpha value, we need to identify a criterion according to which such value can be optimized. Upon determining such criterion, remember that this article deals with forecasting and not just smoothing of sequences. In this case regarding the simple exponential smoothing model, it is customary to consider value obtained at a given time as a forecast for any number of steps ahead. Hence, the forecast of the sequence value at the time t will be a one-step-ahead forecast made at the previous step In this case, one can use a one-step-ahead forecast error as a criterion for optimization of the alpha coefficient value Thus, by minimizing the sum of squares of these errors over the entire sample, we can determine the optimal value of the alpha coefficient for a given sequence. The best alpha value will of course be the one at which the sum of squares of the errors would be minimal. Figure 1 shows a plot of the sum of squares of one-step-ahead forecast errors versus alpha coefficient value for a fragment of test sequence USDJPY M1. Figure 1. Simple exponential smoothing The minimum on the resulting plot is barely discernible and is located close to the alpha value of approximately 0.8. But such picture is not always the case with regard to the simple exponential smoothing. When trying to obtain the optimal alpha value for test sequence fragments used in the article, we will more often than not get a plot continuously falling to unity. Such high values of the smoothing coefficient suggest that this simple model is not quite adequate for the description of our test sequences (quotes). It is either that the process level L(t) changes too fast or there is a trend present in the process. Let us complicate our model a little by adding another component , It is known that linear regression coefficients can be determined by double smoothening of a sequence: For coefficients a1 and a2 obtained in this manner, the m-step-ahead forecast at the time t will be equal to It should be noted that the same alpha coefficient is used in the above formulas for the first and repeated smoothing. This model is called the additive one-parameter model of linear growth. Let us demonstrate the difference between the simple model and the model of linear growth. Suppose that for a long time the process under study represented a constant component, i. e. it appeared on the chart as a straight horizontal line but at some point a linear trend started to emerge. A forecast for this process made using the above mentioned models is shown in Figure 2. Figure 2. Model comparison As can be seen, the simple exponential smoothing model is appreciably behind the linearly varying input sequence and the forecast made using this model is moving yet further away. We can see a very a different pattern when the linear growth model is used. When the trend emerges, this model is as if trying to come up with the linearly varying sequence and its forecast is closer to the direction of varying input values. If the smoothing coefficient in the given example was higher, the linear growth model would be able to reach the input signal over the given time and its forecast would nearly coincide with the input sequence. Despite the fact that the linear growth model in the steady state gives good results in the presence of a linear trend, it is easy to see that it takes a certain time for it to catch up with the trend. Therefore there will always be a gap between the model and input sequence if the direction of a trend frequently changes. Besides, if the trend grows nonlinearly but instead follows the square law, the linear growth model will not be able to reach it. But despite these drawbacks, this model is more beneficial than the simple exponential smoothing model in the presence of a linear trend. As already mentioned, we used a one-parameter model of linear growth. In order to find the optimal value of the alpha parameter for a fragment of test sequence USDJPY M1, let us build a plot of the sum of squares of one-step-ahead forecast errors versus alpha coefficient value. This plot built on the basis of the same sequence fragment as the one in Figure 1, is displayed in Figure 3. Figure 3. Linear growth model As compared with the result in Figure 1, the optimal value of the alpha coefficient has in this case decreased to approximately 0.4. The first and second smoothing have the same coefficients in this model, although theoretically their values can be different. The linear growth model with two different smoothing coefficients will be reviewed further. Both exponential smoothing models we considered have their analogs in MetaTrader 5 where they exist in the form of indicators. These are well-known EMA and DEMA which are not designed for forecasting but for smoothing of sequence values. It should be noted that when using DEMA indicator, a value corresponding to the a1 coefficient is displayed instead of the one-step forecast value. The a2 coefficient (see the above formulas for the linear growth model) is in this case not calculated nor used. In addition, the smoothing coefficient is calculated in terms of the equivalent period n For example, alpha equal to 0.8 will correspond to n being approximately equal to 2 and if alpha is 0.4, n is equal to 4. 4. Initial Values As already mentioned, a smoothing coefficient value shall in one way or another be obtained upon application of exponential smoothing. But this appears to be insufficient. Since in exponential smoothing the current value is calculated on the basis of the previous one, there is a situation where such value does not yet exist at the time zero. In other words, initial value of S or S1 and S2 in the linear growth model shall in some way be calculated at the time zero. The problem of obtaining initial values is not always easy to solve. If (as in the case of using quotes in MetaTrader 5) we have a very long history available, the exponential smoothing curve will, had the initial values been inaccurately determined, have time to stabilize by a current point, having corrected our initial error. This will require about 10 to 200 (and sometimes even more) periods depending on the smoothing coefficient value. In this case it would be enough to roughly estimate the initial values and start the exponential smoothing process 200-300 periods before the target time period. It gets more difficult, though, when the available sample only contains e. g. 100 values. There are various recommendations in literature regarding the choice of initial values. For example, the initial value in the simple exponential smoothing can be equated to the first element in a sequence or calculated as the mean of three to four initial elements in a sequence with a view to smoothing random outliers. The initial values S1 and S2 in the linear growth model can be determined based on the assumption that the initial level of the forecasting curve shall be equal to the first element in a sequence and the slope of the linear trend shall be zero. One can find yet more recommendations in different sources regarding the choice of initial values but none of them can ensure the absence of noticeable errors at early stages of the smoothing algorithm. It is particularly noticeable with the use of low value smoothing coefficients when a great number of periods is required in order to attain a steady state. Therefore in order to minimize the impact of problems associated with the choice of initial values (especially for short sequences), we sometimes use a method which involves a search for such values that will result in the minimum forecast error. It is a matter of calculating a forecast error for the initial values varying at small increments over the entire sequence. The most appropriate variant can be selected after calculating the error within the range of all possible combinations of initial values. This method is however very laborious requiring a lot of calculations and is almost never used in its direct form. The problem described has to do with optimization or search for a minimum multi-variable function value. Such problems can be solved using various algorithms developed to considerably reduce the scope of calculations required. We will get back to the issues of optimization of smoothing parameters and initial values in forecasting a bit later. 5. Forecast Accuracy Assessment Forecasting procedure and selection of the model initial values or parameters give rise to the problem of estimating the forecast accuracy. Assessment of accuracy is also important when comparing two different models or determining the consistency of the obtained forecast. There is a great number of well-known estimates for the forecast accuracy assessment but the calculation of any of them requires the knowledge of the forecast error at every step. As already mentioned, a one-step-ahead forecast error at the time t is equal to Probably the most common forecast accuracy estimate is the mean squared error (MSE): where n is the number of elements in a sequence. Extreme sensitivity to occasional single errors of large value is sometimes pointed out as a disadvantage of MSE. It derives from the fact that the error value when calculating MSE is squared. As an alternative, it is advisable to use in this case the mean absolute error (MAE). The squared error here is replaced by the absolute value of the error. It is assumed that the estimates obtained using MAE are more stable. Both estimates are quite appropriate for e. g. assessment of forecast accuracy of the same sequence using different model parameters or different models but they appear to be of little use for comparison of the forecast results received in different sequences. Besides, the values of these estimates do not expressly suggest the quality of the forecast result. For example, we cannot say whether the obtained MAE of 0,03 or any other value is good or bad. To be able to compare the forecast accuracy of different sequences, we can use relative estimates RelMSE and RelMAE: The obtained estimates of forecast accuracy are here divided by the respective estimates obtained using the test method of forecasting. As a test method, it is suitable to use the so-called naive method suggesting that the future value of the process will be equal to the current value. If the mean of forecast errors equals the value of errors obtained using the naive method, the relative estimate value will be equal to one. If the relative estimate value is less than one, it means that, on the average, the forecast error value is less than in the naive method. In other words, the accuracy of forecast results ranks over the accuracy of the naive method. And vice versa, if the relative estimate value is more than one, the accuracy of the forecast results is, on the average, poorer than in the naive method of forecasting. These estimates are also suitable for assessment of the forecast accuracy for two or more steps ahead. A one-step forecast error in calculations just needs to be replaced with the value of forecast errors for the appropriate number of steps ahead. As an example, the below table contains one-step ahead forecast errors estimated using RelMAE in one-parameter model of linear growth. The errors were calculated using the last 200 values of each test sequence. Table 1. One-step-ahead forecast errors estimated using RelMAE RelMAE estimate allows to compare the effectiveness of a selected method when forecasting different sequences. As the results in Table 1 suggest, our forecast was never more accurate than the naive method - all RelMAE values are more than one. 6. Additive Models There was a model earlier in the article that comprised the sum of the process level, linear trend and a random variable. We will expand the list of the models reviewed in this article by adding another model which in addition to the above components includes a cyclic, seasonal component. Exponential smoothing models comprising all components as a sum are called the additive models. Apart from these models there are multiplicative models where one, more or all components are comprised as a product. Let us proceed to reviewing the group of additive models. The one-step-ahead forecast error has repeatedly been mentioned earlier in the article. This error has to be calculated in nearly any application related to forecasting based on exponential smoothing. Knowing the value of the forecast error, the formulas for the exponential smoothing models introduced above can be presented in a somewhat different form (error-correcting form). The form of the model representation we are going to use in our case contains an error in its expressions that is partially or fully added to the previously obtained values. Such representation is called the additive error model. Exponential smoothing models can also be expressed in a multiplicative error form which will however not be used in this article. Let us have a look at additive exponential smoothing models. Simple exponential smoothing: Additive linear growth model: In contrast to the earlier introduced one-parameter linear growth model, two different smoothing parameters are used here. Linear growth model with damping: The meaning of such damping is that the trend slope will recede at every subsequent forecasting step depending on the value of the damping coefficient. This effect is demonstrated in Figure 4. Figure 4. Damping coefficient effect As can be seen in the figure, when making a forecast, a decreasing value of the damping coefficient will cause the trend to be losing its strength faster, thus the linear growth will get more and more damped. By adding a seasonal component as a sum to each of these three models we will get three more models. Simple model with additive seasonality: Linear growth model with additive seasonality: Linear growth model with damping and additive seasonality: There are also ARIMA models equivalent to the models with seasonality but they will be left out here as they will hardly have any practical importance whatsoever. Notations used in the formulas provided are as follows: It is easy to see that the formulas for the last model provided include all six variants under consideration. If in the formulas for the linear growth model with damping and additive seasonality we take , the seasonality will be disregarded in forecasting. Further, where , a linear growth model will be produced and where , we will get a linear growth model with damping. The simple exponential smoothing model will correspond to . When employing the models that involve seasonality, the presence of cyclicity and period of the cycle should first be determined using any available method in order to further use this data for initialization of values of seasonal indices. We didnt manage to detect a considerable stable cyclicity in the fragments of test sequences used in our case where the forecast is made over short time intervals. Therefore in this article we will not give relevant examples and expand on the characteristics associated with seasonality. In order to determine the probability prediction intervals with regard to the models under consideration, we will use analytical derivations found in the literature 3. The mean of the sum of squares of one-step-ahead forecast errors calculated over the entire sample of size n will be used as the estimated variance of such errors. Then the following expression will be true for determination of the estimated variance in a forecast for 2 and more steps ahead for the models under consideration: Having calculated the estimated variance of the forecast for every step m, we can find the limits of the 95 prediction interval: We will agree to name such prediction interval the forecast confidence interval. Let us implement the expressions provided for the exponential smoothing models in a class written in MQL5. 7. Implementation of the AdditiveES Class The implementation of the class involved the use of the expressions for the linear growth model with damping and additive seasonality. As mentioned earlier, other models can be derived from it by an appropriate selection of parameters. Let us briefly review methods of AdditiveES class. double s - sets the initial value of the smoothed level double t - sets the initial value of the smoothed trend double alpha1 - sets the smoothing parameter for the level of the sequence double gamma0 - sets the smoothing parameter for the trend double phi1 - sets the damping parameter double delta0 - sets the smoothing parameter for seasonal indices int nses1 - sets the number of periods in the seasonal cycle. It returns a one-step-ahead forecast calculated on the basis of the initial values set. The Init method shall be called in the first place. This is required for setting the smoothing parameters and initial values. It should be noted that the Init method does not provide for initialization of seasonal indices at arbitrary values when calling this method, seasonal indices will always be set to zero. Int m - seasonal index number double is - sets the value of the seasonal index number m. The IniIs(. ) method is called when the initial values of seasonal indices need to be other than zero. Seasonal indices should be initialized right after calling the Init(. ) method. double y new value of the input sequence It returns a one-step-ahead forecast calculated on the basis of the new value of the sequence This method is designed for calculating a one-step-ahead forecast every time a new value of the input sequence is entered. It should only be called after the class initialization by the Init and, where necessary, IniIs methods. int m forecasting horizon of 1,2,3, period It returns the m-step-ahead forecast value. This method calculates only the forecast value without affecting the state of the smoothing process. It is usually called after calling the NewY method. int m forecasting horizon of 1,2,3, period It returns the coefficient value for calculating the forecast variance. This coefficient value shows the increase in the variance of a m-step-ahead forecast compared to the variance of the one-step-ahead forecast. GetS, GetT, GetF, GetIs methods These methods provide access to the protected variables of the class. GetS, GetT and GetF return values of the smoothed level, smoothed trend and a one-step-ahead forecast, respectively. GetIs method provides access to seasonal indices and requires the indication of the index number m as an input argument. The most complex model out of all we have reviewed is the linear growth model with damping and additive seasonality based on which the AdditiveES class is created. This brings up a very reasonable question - what would the remaining, simpler models be needed. Despite the fact, that more complex models should seemingly have a clear advantage over simpler ones, it is actually not always the case. Simpler models that have less parameters will in the vast majority of cases result in lesser variance of forecast errors, i. e. their operation will be more steady. This fact is employed in creating forecasting algorithms based on simultaneous parallel operation of all available models, from the simplest to the most complex ones. Once the sequence have been fully processed, a forecasting model that demonstrated the lowest error, given the number of its parameters (i. e. its complexity), is selected. There is a number of criteria developed for this purpose, e. g. Akaikes Information Criterion (AIC). It will result in selection of a model which is expected to produce the most stable forecast. To demonstrate the use of the AdditiveES class, a simple indicator was created all smoothing parameters of which are set manually. The source code of the indicator AdditiveESTest. mq5 is set forth below. A call or a repeated initialization of the indicator sets the exponential smoothing initial values There are no initial settings for seasonal indices in this indicator, their initial values are therefore always equal to zero. Upon such initialization, the influence of seasonality on the forecast result will gradually increase from zero to a certain steady value, with the introduction of new incoming values. The number of cycles required to reach a steady-state operating condition depends on the value of the smoothing coefficient for seasonal indices: the smaller the smoothing coefficient value, the more time it will require. The operation result of the AdditiveESTest. mq5 indicator with default settings is shown in Figure 5. Figure 5. The AdditiveESTest. mq5 indicator Apart from the forecast, the indicator displays an additional line corresponding to the one-step forecast for the past values of the sequence and limits of the 95 forecast confidence interval. The confidence interval is based on the estimated variance of the one-step-ahead error. To reduce the effect of inaccuracy of the selected initial values, the estimated variance is not calculated over the entire length nHist but only with regard to the last bars the number of which is specified in the input parameter nTest. Files. zip archive at the end of the article includes AdditiveES. mqh and AdditiveESTest. mq5 files. When compiling the indicator, it is necessary that the include AdditiveES. mqh file is located in the same directory as AdditiveESTest. mq5. While the problem of selecting the initial values was to some extent solved when creating the AdditiveESTest. mq5 indicator, the problem of selecting the optimal values of smoothing parameters has remained open. 8. Selection of the Optimal Parameter Values The simple exponential smoothing model has a single smoothing parameter and its optimal value can be found using the simple enumeration method. After calculating the forecast error values over the entire sequence, the parameter value is changed at a small increment and a full calculation is made again. This procedure is repeated until all possible parameter values have been enumerated. Now we only need to select the parameter value which resulted in the smallest error value. In order to find an optimal value of the smoothing coefficient in the range of 0.1 to 0.9 at 0.05 increments, the full calculation of the forecast error value will need to be made seventeen times. As can be seen, the number of calculations required is not so big. But the linear growth model with damping involves the optimization of three smoothing parameters and in this case it will take 4913 calculation runs in order to enumerate all their combinations in the same range at the same 0.05 increments. The number of full runs required for enumeration of all possible parameter values rapidly increases with the increase in the number of parameters, decrease in the increment and expansion of the enumeration range. Should it further be necessary to optimize the initial values of the models in addition to the smoothing parameters, it will be quite difficult to do using the simple enumeration method. Problems associated with finding the minimum of a function of several variables are well studied and there is quite a lot of algorithms of this kind. Description and comparison of various methods for finding the minimum of a function can be found in the literature 7. All these methods are primarily aimed at reducing the number of calls of the objective function, i. e. reducing the computational efforts in the process of finding the minimum. Different sources often contain a reference to the so-called quasi-Newton methods of optimization. Most likely this has to do with their high efficiency but the implementation of a simpler method should also be sufficient to demonstrate an approach to the optimization of forecasting. Let us opt for Powells method. Powells method does not require calculation of derivatives of the objective function and belongs to search methods. This method, like any other method, may be programmatically implemented in various ways. The search should be completed when a certain accuracy of the objective function value or the argument value is attained. Besides, a certain implementation may include the possibility of using limitations on the permissible range of function parameter changes. In our case, the algorithm for finding an unconstrained minimum using Powells method is implemented in PowellsMethod. class. The algorithm stops searching once a given accuracy of the objective function value is attained. In the implementation of this method, an algorithm found in the literature 8 was used as a prototype. Below is the source code of the PowellsMethod class. The Optimize method is the main method of the class. double ampp - array that at the input contains the initial values of parameters the optimal values of which shall be found the obtained optimal values of these parameters are at the output of the array. int n0 - number of arguments in array p. Where n0, the number of parameters is considered to be equal to the size of array p. It returns the number of iterations required for operation of the algorithm, or -1 if the maximum permissible number thereof has been reached . When searching for optimal parameter values, an iterative approximation to the minimum of the objective function occurs. The Optimize method returns the number of iterations required to reach the function minimum with a given accuracy. The objective function is called several times at every iteration, i. e. the number of calls of the objective function may be significantly (ten and even hundred times) bigger than the number of iterations returned by the Optimize method. Other methods of the class. Int n - maximum permissible number of iterations in Powells method. The default value is 200. It sets the maximum permissible number of iterations once this number is reached, the search will be over regardless of whether the minimum of the objective function with a given accuracy was found. And a relevant message will be added to the log. double er - accuracy. Should this value of deviation from the minimum value of the objective function be reached, Powells method stops searching. The default value is 1e-6. Int n - maximum permissible number of iterations for an auxiliary Brents method. The default value is 200. It sets the maximum permissible number of iterations. Once it is reached, the auxiliary Brents method will stop searching and a relevant message will be added to the log. double er accuracy. This value defines accuracy in the search of the minimum for the auxiliary Brents method. The default value is 1e-4. It returns the minimum value of the objective function obtained. It returns the number of iterations required for operation of the algorithm. Virtual function func(const double ampp) const double ampp address of the array containing the optimized parameters. The size of the array corresponds to the number of function parameters. It returns the function value corresponding to the parameters passed to it. The virtual function func() shall in every particular case be redefined in a class derived from the PowellsMethod class. The func() function is the objective function the arguments of which corresponding to the minimum value returned by the function will be found when applying the search algorithm. This implementation of Powells method employs Brents univariate parabolic interpolation method for determining the direction of search with regard to each parameter. The accuracy and maximum permissible number of iterations for these methods can be set separately by calling SetItMaxPowell, SetFtolPowell, SetItMaxBrent and SetFtolBrent. So the default characteristics of the algorithm can be changed in this manner. This may appear useful when the default accuracy set to a certain objective function turns out to be too high and the algorithm requires too many iterations in the search process. The change in the value of the required accuracy can optimize the search with regard to different categories of objective functions. Despite the seeming complexity of the algorithm that employs Powells method, it is quite simple in use. Let us review an example. Assume, we have a function and we need to find the values of parameters and at which the function will have the smallest value. Let us write a script demonstrating a solution to this problem. When writing this script, we first create the func() function as a member of the PMTest class which calculates the value of the given test function using the passed values of parameters p0 and p1. Then in the body of the OnStart() function, the initial values are assigned to the required parameters. The search will start from these values. Further, a copy of the PMTest class is created and the search for the required values of p0 and p1 starts by calling the Optimize method the methods of the parent PowellsMethod class will call the redefined func() function. Upon completion of the search, the number of iterations, function value at the minimum point and the obtained parameter values p00.5 and p16 will be added to the log. PowellsMethod. mqh and a test case PMTest. mq5 are located at the end of the article in Files. zip archive. In order to compile PMTest. mq5, it should be located in the same directory as PowellsMethod. mqh. 9. Optimization of the Model Parameter Values The previous section of the article dealt with implementation of the method for finding the function minimum and gave a simple example of its use. We will now proceed to the issues related to optimization of the exponential smoothing model parameters. For a start, let us simplify the earlier introduced AdditiveES class to the maximum by excluding from it all elements associated with the seasonal component, as the models that take into consideration seasonality are not going to be further considered in this article anyway. This will allow to make the source code of the class much easier to comprehend and reduce the number of calculations. In addition, we will also exclude all calculations related to forecasting and computations of the forecast confidence intervals for an easy demonstration of an approach to the optimization of parameters of the linear growth model with damping under consideration. The OptimizeES class derives from the PowellsMethod class and includes redefining of the virtual function func(). As mentioned earlier, the parameters whose calculated value will be minimized in the course of optimization shall be passed at the input of this function. In accordance with the maximum likelihood method, the func() function calculates the logarithm of the sum of squares of one-step-ahead forecast errors. The errors are calculated in a loop with regard to NCalc recent values of the sequence. To preserve the stability of the model, we should impose limitations on the range of changes in its parameters. This range for Alpha and Gamma parameters will be from 0.05 to 0.95, and for Phi parameter - from 0.05 to 1.0. But for optimization in our case, we use a method for finding an unconstrained minimum which does not imply the use of limitations on the arguments of the objective function. We will try to turn the problem of finding the minimum of the multi-variable function with limitations into a problem of finding an unconstrained minimum, to be able to take into consideration all limitations imposed on the parameters without changing the search algorithm. For this purpose, the so-called penalty function method will be used. This method can easily be demonstrated for a one-dimensional case. Suppose that we have a function of a single argument (whose domain is from 2.0 to 3.0) and an algorithm which in the search process can assign any values to this function parameter. In this case, we can do as follows: if the search algorithm has passed an argument which exceeds the maximum permissible value, e. g. 3.5, the function can be calculated for the argument equal to 3.0 and the obtained result is further multiplied by a coefficient proportional to the excess of the maximum value, for example k1(3.5-3)200. If similar operations are performed with regard to argument values that turned out to be below the minimum permissible value, the resulting objective function is guaranteed to increase outside the permissible range of changes in its argument. Such artificial increase in the resulting value of the objective function allows to keep the search algorithm unaware of the fact that the argument passed to the function was in any way limited and guarantee that the minimum of the resulting function will be within the set limits of the argument. Such approach is easily applied to a function of several variables. The main method of the OptimizeES class is the Calc method. A call of this method is responsible for reading data from a file, search for optimal parameter values of a model and estimation of the forecast accuracy using RelMAE for the obtained parameter values. The number of processed values of the sequence read from a file is in this case set in the variable NCalc. Below is the example of the OptimizationTest. mq5 script that uses the OptimizeES class. Following the execution of this script, the obtained result will be as shown below. Figure 6. OptimizationTest. mq5 script result Although we can now find optimal parameter values and initial values of the model, there is yet one parameter which cannot be optimized using simple tools - the number of sequence values used in optimization. In optimization with regard to a sequence of great length, we will obtain the optimal parameter values that, on the average, ensure a minimum error over the entire length of the sequence. However if the nature of the sequence varied within this interval, the obtained values for some of its fragments will no longer be optimal. On the other hand, if the sequence length is dramatically decreased, there is no guarantee that the optimal parameters obtained for such a short interval will be optimal over a longer time lag. OptimizeES. mqh and OptimizationTest. mq5 are located at the end of the article in Files. zip archive. When compiling, it is necessary that OptimizeES. mqh and PowellsMethod. mqh are located in the same directory as the compiled OptimizationTest. mq5. In the given example, USDJPYM11100.TXT file is used that contains the test sequence and that should be located in the directory MQL5FilesDataset. Table 2 shows the estimates of the forecast accuracy obtained using RelMAE by means of this script. Forecasting was done with regard to eight test sequences mentioned earlier in the article using the last 100, 200 and 400 values of each of these sequences. Table 2. Forecast errors estimated using RelMAE As can be seen, the forecast error estimates are close to unity but in the majority of cases the forecast for the given sequences in this model is more accurate than in the naive method. 10. The IndicatorES. mq5 Indicator The AdditiveESTest. mq5 indicator based on the AdditiveES. mqh class was mentioned earlier upon review of the class. All smoothing parameters in this indicator were set manually. Now after considering the method allowing to optimize the model parameters, we can create a similar indicator where the optimal parameter values and initial values will be determined automatically and only the processed sample length will need to be set manually. That said, we will exclude all calculations related to seasonality. The source code of the CIndiatorES class used in creating the indicator is set forth below. This class contains CalcPar and GetPar methods the first one is designed for calculation of the optimal parameter values of the model, the second one is intended for accessing those values. Besides, the CIndicatorES class comprises the redefining of the virtual function func(). The source code of the IndicatorES. mq5 indicator: With every new bar, the indicator finds the optimal values of the model parameters, makes calculations in the model for a given number of bars NHist, builds a forecast and defines the forecast confidence limits. The only parameter of the indicator is the length of the processed sequence the minimum value of which is limited to 24 bars. All calculations in the indicator are made on the basis of the open values. The forecasting horizon is 12 bars. The code of the IndicatorES. mq5 indicator and CIndicatorES. mqh file are located at the end of the article in Files. zip archive. Figure 7. Operation result of the IndicatorES. mq5 indicator An example of the operation result of the IndicatorES. mq5 indicator is shown in Figure 7. In the course of operation of the indicator, the 95 forecast confidence interval will take values corresponding to the obtained optimal parameter values of the model. The bigger the smoothing parameter values, the faster the increase in the confidence interval upon the increasing forecasting horizon. With a simple improvement, the IndicatorES. mq5 indicator can be used not only for forecasting currency quotes but also for forecasting values of various indicators or preprocessed data. Conclusion The main objective of the article was to familiarize the reader with additive exponential smoothing models used in forecasting. While demonstrating their practical use, some accompanying issues were also dealt with. However the materials provided in the article can be considered merely an introduction to the large range of problems and solutions associated with forecasting. I would like to draw your attention to the fact that the classes, functions, scripts and indicators provided were created in the process of writing the article and are primarily designed to serve as examples to the materials of the article. Therefore no serious testing for stability and errors was performed. Besides, the indicators set forth in the article should be considered to be only a demonstration of the implementation of the methods involved. The forecast accuracy of the IndicatorES. mq5 indicator introduced in the article can most likely be somewhat improved by using the modifications of the applied model which would be more adequate in terms of peculiarities of the quotes under consideration. The indicator can also be amplified by other models. But these issues fall beyond the scope of this article. In conclusion, it should be noted that exponential smoothing models can in certain cases produce forecasts of the same accuracy as the forecasts obtained by applying more complex models thus proving once again that even the most complex model is not always the best. ReferencesMoving Average Smoothing Example This example illustrates how to use XLMiners Moving Average Smoothing technique to uncover trends in a time series that contains seasonality. On the XLMiner ribbon, from the Applying Your Model tab, select Help - Examples . then Forecasting/Data Mining Examples . and open the example data set, Airpass. xlsx . This data set contains the monthly totals of international airline passengers from 1949-1960. After the example data set opens, click a cell in the data set, then on the XLMiner ribbon, from the Time Series tab, select Partition to open the Time Series Partition Data dialog. Select Month as the Time Variable, and Passengers as the Variables in the Partition Data . Click OK to partition the data into Training and Validation Sets. (Partitioning is optional. Smoothing techniques may be run on full unpartitioned data sets.) Click the DataPartitionTS worksheet, then on the XLMiner ribbon, from the Time Series tab, select Smoothing - Moving Average to open the Moving Average Smoothing dialog. Month has already been selected as the Time variable. Select Passengers as the Selected variable. Since this data set is expected to include some seasonality (i. e. airline passenger numbers increase during the holidays and summer months), the value for the Interval parameter - weight should be the length of one seasonal cycle (i. e. 12 months). As a result, enter 12 for Interval, and select Produce forecast on validation. Click OK to apply the smoothing technique to the partitioned data set. Two worksheets, MASmoothingOutput and MASmoothingStored . are inserted immediately to the right of the DataPartitionTS worksheet. For more information on the MASmoothingStored worksheet, see the Applying Your Model - Scoring New Data section. Click the MASmoothingOutput worksheet. The Time Plot of Actual Vs. Forecast (Training Data) and (Validation Data) charts show that the Moving Average Smoothing technique does not result in a good fit, as the model does not effectively capture the seasonality in the data set. The summer months -- where the number of airline passengers are typically high -- appear to be under forecasted, and the months where the number of airline passengers are low, the model results in a forecast that is too high. A moving average forecast should never be used when the data set includes seasonality. An alternative would be to perform a regression on the model and then apply this technique to the residuals. The next example does not include seasonality. On the XLMiner ribbon, from the Applying Your Model tab, select Help - Examples . then select Forecasting/Data Mining Examples . and open the example data set Income. xlsx . This data set contains the average income of tax payers by state. First, partition the data set into Training and Validation Sets using Year as the Time Variable, and CA as the Variables in the Partition Data. Click OK to accept the partitioning defaults and create theTraining and Validation Sets. The worksheet DataPartitionTS is inserted immediately to the right of the Income worksheet. Click the DataPartitionTS worksheet, then on the XLMiner ribbon, from the Time Series tab, select Smoothing - Moving Average to open the Moving Average Smoothing dialog. Year has automatically been selected as the Time variable. Select CA as the Selected variable, and under Output Options, select Produce forecast. Click OK to run the Moving Average Smoothing technique. Two worksheets, MASmoothingOutput and MASmoothingStored . are inserted to the right of the DataPartitionTS worksheet. For more information on the MASmoothingStored worksheet, see the Applying Your Model - Scoring New Data section. The results of the Moving Average Smoothing technique on this data set indicate a much better fit.

No comments:

Post a Comment