Monday 19 March 2018

O que é estratégias de negociação algorítmicas


Fundamentos do comércio algorítmico: conceitos e exemplos.


Um algoritmo é um conjunto específico de instruções claramente definidas destinadas a realizar uma tarefa ou processo.


O comércio algorítmico (negociação automatizada, negociação em caixa preta ou simplesmente algo-trading) é o processo de uso de computadores programados para seguir um conjunto definido de instruções para colocar um comércio para gerar lucros a uma velocidade e freqüência impossíveis para um comerciante humano. Os conjuntos definidos de regras são baseados em tempo, preço, quantidade ou qualquer modelo matemático. Além das oportunidades de lucro para o comerciante, o algo-trading torna os mercados mais líquidos e torna a negociação mais sistemática descartando impactos emocionais humanos nas atividades comerciais. (Para mais, consulte Picking the Right Algorithmic Trading Software.)


Suponha que um comerciante siga esses critérios de comércio simples:


Compre 50 ações de uma ação quando sua média móvel de 50 dias excede a média móvel de 200 dias. Vende ações da ação quando sua média móvel de 50 dias está abaixo da média móvel de 200 dias.


Usando este conjunto de duas instruções simples, é fácil escrever um programa de computador que monitorará automaticamente o preço das ações (e os indicadores de média móvel) e colocará as ordens de compra e venda quando as condições definidas forem atendidas. O comerciante não precisa mais manter um relógio para preços e gráficos ao vivo, ou colocar as ordens manualmente. O sistema de negociação algorítmica automaticamente faz isso para ele, identificando corretamente a oportunidade comercial. (Para mais informações sobre as médias móveis, consulte Médias móveis simples, faça as tendências se destacarem.)


[Se você quiser saber mais sobre as estratégias comprovadas e pontuais que podem eventualmente ser trabalhadas em um sistema de comércio alorítico, confira o Curso de Torneio de Dia de Torneio da Invastopedia Academy. ]


Benefícios da negociação algorítmica.


A Algo-trading oferece os seguintes benefícios:


Negociações executadas com os melhores preços Posicionamento instantâneo e preciso da ordem comercial (com altas chances de execução nos níveis desejados) Negociações cronometradas corretamente e instantaneamente, para evitar mudanças de preços significativas Custos de transação reduzidos (veja o exemplo de falta de implementação abaixo) Verificações automatizadas simultâneas em múltiplos condições de mercado Reduziu o risco de erros manuais na colocação dos negócios Backtest o algoritmo, com base nos dados históricos e em tempo real disponíveis Reduzida a possibilidade de erros por comerciantes humanos com base em fatores emocionais e psicológicos.


A maior parte do dia-a-dia é a negociação de alta freqüência (HFT), que tenta capitalizar a colocação de um grande número de pedidos em velocidades muito rápidas em múltiplos mercados e múltiplos parâmetros de decisão, com base em instruções pré-programadas. (Para obter mais informações sobre o comércio de alta freqüência, consulte Estratégias e Segredos de Empresas de Negociação de Alta Freqüência (HFT).)


O Algo-trading é usado em muitas formas de atividades de comércio e investimento, incluindo:


Investidores de médio a longo prazo ou empresas de compra (fundos de pensão, fundos de investimento, companhias de seguros) que adquirem ações em grandes quantidades, mas não querem influenciar os preços das ações com investimentos discretos e de grande porte. Os comerciantes de curto prazo e os participantes do lado da venda (fabricantes de mercado, especuladores e arbitragentes) se beneficiam da execução comercial automatizada; Além disso, ajudas de algo-trading na criação de liquidez suficiente para os vendedores no mercado. Os comerciantes sistemáticos (seguidores de tendências, comerciantes de pares, hedge funds, etc.) acham muito mais eficiente programar suas regras comerciais e permitir que o programa seja comercializado automaticamente.


O comércio algorítmico proporciona uma abordagem mais sistemática ao comércio ativo do que os métodos baseados na intuição ou instinto do comerciante humano.


Estratégias de negociação algorítmica.


Qualquer estratégia de negociação algorítmica exige uma oportunidade identificada que seja rentável em termos de melhoria de ganhos ou redução de custos. As seguintes são estratégias de negociação comuns usadas em algo-trading:


As estratégias de negociação algorítmicas mais comuns seguem as tendências em médias móveis, fuga de canais, movimentos no nível de preços e indicadores técnicos relacionados. Estas são as estratégias mais fáceis e simples de implementar através de negociação algorítmica porque essas estratégias não envolvem fazer previsões ou previsões de preços. Os negócios são iniciados com base na ocorrência de tendências desejáveis, que são fáceis e direitas de implementar através de algoritmos sem entrar na complexidade da análise preditiva. O exemplo acima mencionado de média móvel de 50 e 200 dias é uma tendência popular seguindo a estratégia. (Para mais informações sobre as estratégias de negociação de tendências, consulte: Estratégias simples para capitalizar as tendências.)


Comprar um estoque cotado duplo a um preço mais baixo em um mercado e simultaneamente vendê-lo a um preço mais alto em outro mercado oferece o diferencial de preço como lucro ou arbitragem sem risco. A mesma operação pode ser replicada para ações versus instrumentos de futuros, pois os diferenciais de preços existem de tempos em tempos. Implementar um algoritmo para identificar esses diferenciais de preços e colocar as ordens permite oportunidades lucrativas de forma eficiente.


Os fundos do índice definiram períodos de reequilíbrio para que suas participações fossem compatíveis com seus respectivos índices de referência. Isso cria oportunidades rentáveis ​​para comerciantes algorítmicos, que capitalizam os negócios esperados que oferecem lucros de 20 a 80 pontos base, dependendo do número de ações no fundo do índice, apenas antes do reequilíbrio do fundo do índice. Essas negociações são iniciadas através de sistemas de negociação algorítmica para execução atempada e melhores preços.


Muitos modelos matemáticos comprovados, como a estratégia de negociação neutra do delta, que permitem a negociação de combinações de opções e sua segurança subjacente, onde os negócios são colocados para compensar deltas positivos e negativos, de modo que o portfólio delta seja mantido em zero.


A estratégia de reversão média baseia-se na ideia de que os preços altos e baixos de um bem são um fenômeno temporário que retorna periodicamente ao seu valor médio. Identificar e definir uma faixa de preço e implementar algoritmos com base em isso permite que os negócios sejam colocados automaticamente quando o preço do recurso entra e sai do seu alcance definido.


A estratégia de preços médios ponderados por volume quebra uma grande ordem e libera pedaços menores determinados dinamicamente da ordem para o mercado usando perfis de volume histórico específicos de estoque. O objetivo é executar a ordem perto do preço médio ponderado do volume (VWAP), beneficiando assim o preço médio.


A estratégia de preço médio ponderado no tempo quebra uma grande ordem e libera dinamicamente determinados pedaços menores da ordem para o mercado usando intervalos de tempo uniformemente divididos entre o início e o fim do tempo. O objetivo é executar a ordem perto do preço médio entre os horários de início e término, minimizando assim o impacto no mercado.


Até que a ordem comercial seja totalmente preenchida, este algoritmo continua enviando ordens parciais, de acordo com o índice de participação definido e de acordo com o volume negociado nos mercados. A "estratégia de etapas" relacionada envia ordens a uma porcentagem definida pelo usuário de volumes de mercado e aumenta ou diminui essa taxa de participação quando o preço da ação atinge os níveis definidos pelo usuário.


A estratégia de falta de implementação visa minimizar o custo de execução de uma ordem através da negociação do mercado em tempo real, economizando assim o custo da ordem e beneficiando do custo de oportunidade da execução atrasada. A estratégia aumentará a taxa de participação direcionada quando o preço das ações se mover de forma favorável e diminuí-lo quando o preço das ações se mover de forma adversa.


Existem algumas classes especiais de algoritmos que tentam identificar "acontecimentos" do outro lado. Esses "algoritmos de sniffing", usados, por exemplo, por um market maker market market têm a inteligência interna para identificar a existência de qualquer algoritmo no lado da compra de uma grande ordem. Essa detecção através de algoritmos ajudará o fabricante de mercado a identificar grandes oportunidades de ordem e permitir que ele se beneficie ao preencher os pedidos a um preço mais alto. Isso às vezes é identificado como front-running de alta tecnologia. (Para obter mais informações sobre negociação de alta freqüência e práticas fraudulentas, consulte: Se você comprar ações on-line, você está envolvido em HFTs.)


Requisitos técnicos para negociação algorítmica.


Implementar o algoritmo usando um programa de computador é a última parte, batida com backtesting. O desafio é transformar a estratégia identificada em um processo informatizado integrado que tenha acesso a uma conta de negociação para fazer pedidos. São necessários os seguintes:


Conhecimento de programação de computador para programar a estratégia de negociação necessária, programadores contratados ou software de negociação pré-fabricado Conectividade de rede e acesso a plataformas de negociação para colocar os pedidos Acesso a feeds de dados de mercado que serão monitorados pelo algoritmo para oportunidades de colocar pedidos A capacidade e infra-estrutura para voltar a testar o sistema uma vez construído, antes de entrar em operação em mercados reais Dados históricos disponíveis para backtesting, dependendo da complexidade das regras implementadas no algoritmo.


Aqui está um exemplo abrangente: o Royal Dutch Shell (RDS) está listado na Amsterdam Stock Exchange (AEX) e London Stock Exchange (LSE). Vamos construir um algoritmo para identificar oportunidades de arbitragem. Aqui estão algumas observações interessantes:


AEX negocia em Euros, enquanto a LSE negocia em libras esterlinas. Devido à diferença horária de uma hora, a AEX abre uma hora antes da LSE, seguido de ambas as trocas comerciais simultaneamente durante as próximas horas e depois de negociar apenas na LSE durante a última hora à medida que o AEX fecha .


Podemos explorar a possibilidade de negociação de arbitragem nas ações da Royal Dutch Shell listadas nesses dois mercados em duas moedas diferentes?


Um programa de computador que pode ler os preços atuais do mercado Os feeds de preços de LSE e AEX A taxa de câmbio para a taxa de câmbio GBP-EUR Capacidade de colocação de pedidos que podem rotear a ordem para a troca correta do recurso Back-testing em feeds históricos de preços.


O programa de computador deve executar o seguinte:


Leia o preço de entrada do estoque RDS de ambas as bolsas Usando as taxas de câmbio disponíveis, converta o preço de uma moeda para outra. Se houver uma discrepância de preço suficientemente grande (descontando os custos de corretagem) levando a uma oportunidade rentável, então coloque a compra ordem em troca de preços mais baixos e ordem de venda em troca de preços mais elevados Se as ordens forem executadas conforme desejado, o lucro de arbitragem seguirá.


Simples e fácil! No entanto, a prática de negociação algorítmica não é simples de manter e executar. Lembre-se, se você pode colocar um comércio gerado por algo, os outros participantes do mercado podem também. Conseqüentemente, os preços flutuam em milissegundos e até mesmo em microssegundos. No exemplo acima, o que acontece se o seu comércio de compras for executado, mas o comércio de vendas não acontece à medida que os preços de venda mudam quando o seu pedido atinge o mercado? Você vai acabar sentado com uma posição aberta, tornando sua estratégia de arbitragem inútil.


Existem riscos e desafios adicionais: por exemplo, riscos de falha do sistema, erros de conectividade de rede, atrasos de tempo entre ordens comerciais e execução e, o mais importante de tudo, algoritmos imperfeitos. O algoritmo mais complexo é o backtesting mais rigoroso antes de ser posto em ação.


The Bottom Line.


A análise quantitativa do desempenho de um algoritmo desempenha um papel importante e deve ser examinada criticamente. É excitante ir pela automação auxiliada por computadores com a noção de ganhar dinheiro sem esforço. Mas é preciso certificar-se de que o sistema está completamente testado e os limites exigidos são definidos. Os comerciantes analíticos devem considerar a aprendizagem de sistemas de programação e construção por conta própria, ter confiança em implementar as estratégias certas de forma infalível. O uso cauteloso eo teste completo de algo-trading podem criar oportunidades rentáveis. (Para mais informações, consulte Como codificar seu próprio robô Algo Trading.)


QuantStart.


Junte-se ao portal de membros privados da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento. Você encontrará um grupo bem informado de mentalistas quant pronto para responder suas perguntas comerciais mais importantes.


Confira meu ebook sobre o comércio de quant, onde eu ensino você como criar estratégias de negociação sistemáticas lucrativas com ferramentas Python, desde o início.


Dê uma olhada no meu novo ebook sobre estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas bayesianas, com Python e R.


Por Michael Halls-Moore em 19 de abril de 2013.


Neste artigo, quero apresentar-lhe os métodos pelos quais eu próprio identifico estratégias de negociação algorítmicas rentáveis. Nosso objetivo hoje é entender em detalhes como encontrar, avaliar e selecionar esses sistemas. Vou explicar como as estratégias de identificação são tanto sobre preferências pessoais quanto sobre o desempenho da estratégia, como determinar o tipo e a quantidade de dados históricos para o teste, como avaliar de forma imparcial uma estratégia de negociação e, finalmente, como avançar para a fase de backtesting e implementação estratégica.


Identificando suas próprias preferências pessoais para negociação.


Para ser um comerciante bem sucedido - de forma discricionária ou algorítmica - é necessário fazer-se algumas perguntas honestas. O Trading oferece a você a capacidade de perder dinheiro em uma taxa alarmante, por isso é necessário "conhecer você mesmo" tanto quanto é necessário entender a estratégia escolhida.


Eu diria que a consideração mais importante na negociação é estar ciente de sua própria personalidade. O comércio e o comércio algorítmico em particular, requer um grau significativo de disciplina, paciência e desapego emocional. Como você está deixando um algoritmo executar sua negociação para você, é necessário ser resolvido para não interferir com a estratégia quando está sendo executado. Isso pode ser extremamente difícil, especialmente em períodos de redução prolongada. No entanto, muitas estratégias que mostraram ser altamente rentáveis ​​em um backtest podem ser arruinadas por uma simples interferência. Compreenda que se você deseja entrar no mundo da negociação algorítmica, você será testado emocionalmente e, para ser bem-sucedido, é necessário trabalhar com essas dificuldades!


A próxima consideração é uma das vezes. Você tem um emprego a tempo inteiro? Você trabalha a tempo parcial? Você trabalha em casa ou tem uma longa viagem diária? Essas perguntas ajudarão a determinar a freqüência da estratégia que você deve procurar. Para aqueles de você no emprego a tempo inteiro, uma estratégia de futuros intradiária pode não ser apropriada (pelo menos até que seja totalmente automatizada!). Suas restrições de tempo também ditarão a metodologia da estratégia. Se sua estratégia é freqüentemente negociada e dependente de feeds de notícias caras (como um terminal da Bloomberg), você terá claramente que ser realista sobre sua capacidade de executar com sucesso durante o escritório! Para aqueles de vocês com muito tempo, ou as habilidades para automatizar sua estratégia, você pode querer examinar uma estratégia mais técnica de negociação de alta freqüência (HFT).


Minha opinião é que é necessário realizar pesquisas contínuas sobre suas estratégias de negociação para manter um portfólio consistentemente lucrativo. Poucas estratégias permanecem "sob o radar" para sempre. Assim, uma parte importante do tempo atribuído à negociação será na realização de pesquisas em andamento. Pergunte a si mesmo se você está preparado para fazer isso, pois pode ser a diferença entre uma forte rentabilidade ou um declínio lento em relação a perdas.


Você também precisa considerar seu capital de negociação. O valor mínimo ideal geralmente aceito para uma estratégia quantitativa é de 50,000 USD (aproximadamente £ 35,000 para nós no Reino Unido). Se eu estivesse começando de novo, eu começaria com uma quantidade maior, provavelmente mais perto de 100,000 USD (aproximadamente £ 70,000). Isso ocorre porque os custos de transação podem ser extremamente caros para estratégias de média a alta freqüência e é necessário ter capital suficiente para absorvê-los em tempos de redução. Se você está considerando começar com menos de 10.000 USD, então você precisará se restringir a estratégias de baixa freqüência, negociando em um ou dois ativos, já que os custos de transação irão comer rapidamente em seus retornos. Interactive Brokers, que é um dos corretores mais amigáveis ​​para aqueles com habilidades de programação, devido à sua API, tem uma conta de varejo mínima de 10.000 USD.


A habilidade de programação é um fator importante na criação de uma estratégia de negociação algorítmica automatizada. Estar bem informado em uma linguagem de programação como C ++, Java, C #, Python ou R permitirá que você crie o sistema de armazenamento de dados, o sistema de backtest e o sistema de execução de ponta a ponta. Isso tem uma série de vantagens, cujo chefe é a capacidade de estar completamente atento a todos os aspectos da infra-estrutura comercial. Também permite que você explore as estratégias de freqüência mais alta, pois você terá o controle total da sua "pilha de tecnologia". Embora isso signifique que você possa testar seu próprio software e eliminar erros, também significa mais tempo gasto na codificação de infra-estrutura e menos na implementação de estratégias, pelo menos na parte anterior da sua carreira de trading. Você pode achar que você está confortável negociando no Excel ou MATLAB e pode terceirizar o desenvolvimento de outros componentes. Eu não recomendaria isso no entanto, especialmente para aqueles que negociavam em alta freqüência.


Você precisa se perguntar o que você espera alcançar por meio de negociação algorítmica. Você está interessado em um rendimento regular, pelo qual você espera obter lucros de sua conta de negociação? Ou, você está interessado em um ganho de capital a longo prazo e pode se negociar sem a necessidade de retirar fundos? A dependência de renda determinará a freqüência de sua estratégia. As retiradas de renda mais regulares exigirão uma estratégia de negociação de maior freqüência com menor volatilidade (ou seja, uma proporção Sharpe mais alta). Os comerciantes de longo prazo podem pagar uma frequência comercial mais tranquila.


Finalmente, não se ilude com a noção de tornar-se extremamente rico num curto espaço de tempo! O comércio de Algo não é um esquema rápido e rápido - se alguma coisa pode ser um esquema rápido e rápido. É preciso disciplina, pesquisa, diligência e paciência importantes para serem bem-sucedidos no comércio algorítmico. Pode levar meses, senão anos, gerar rentabilidade consistente.


Sourcing Algorithmic Trading Ideas.


Apesar das percepções comuns em contrário, é realmente bastante direto localizar estratégias de negociação rentáveis ​​no domínio público. Nunca as idéias comerciais estão mais disponíveis do que hoje. Revistas de finanças acadêmicas, servidores de pré-impressão, blogs comerciais, fóruns de negociação, revistas comerciais semanais e textos especializados fornecem milhares de estratégias de negociação com as quais basear suas idéias.


Nosso objetivo como pesquisadores quantitativos de negócios é estabelecer um pipeline estratégico que nos forneça um fluxo de idéias comerciais em andamento. Idealmente, queremos criar uma abordagem metódica para sourcing, avaliação e implementação de estratégias que encontramos. Os objetivos do pipeline são gerar uma quantidade consistente de novas idéias e fornecer-nos uma estrutura para rejeitar a maioria dessas idéias com o mínimo de consideração emocional.


Devemos ser extremamente cuidadosos para não permitir influências cognitivas na nossa metodologia de tomada de decisão. Isso pode ser tão simples como ter uma preferência por uma classe de ativos sobre outra (o ouro e outros metais preciosos vêm à mente) porque são percebidos como mais exóticos. Nosso objetivo sempre deve ser encontrar estratégias consistentemente lucrativas, com expectativas positivas. A escolha da classe de ativos deve basear-se em outras considerações, como restrições de capital de negociação, taxas de corretagem e capacidades de alavancagem.


Se você não está completamente familiarizado com o conceito de estratégia comercial, então o primeiro lugar a procurar é com os livros didáticos estabelecidos. Os textos clássicos fornecem uma ampla gama de idéias mais simples e diretas, para se familiarizarem com a negociação quantitativa. Aqui está uma seleção que eu recomendo para aqueles que são novos para negociação quantitativa, que gradualmente se tornam mais sofisticados enquanto você trabalha através da lista:


Para uma lista mais longa de livros de negociação quantitativos, visite a lista de leitura QuantStart.


O próximo lugar para encontrar estratégias mais sofisticadas é com fóruns de negociação e blogs comerciais. No entanto, uma nota de cautela: muitos blogs comerciais dependem do conceito de análise técnica. A análise técnica envolve a utilização de indicadores básicos e psicologia comportamental para determinar tendências ou padrões de reversão nos preços dos ativos.


Apesar de ser extremamente popular no espaço comercial geral, a análise técnica é considerada um pouco ineficaz na comunidade de finanças quantitativas. Alguns sugeriram que não é melhor que ler um horóscopo ou estudar folhas de chá em termos de seu poder preditivo! Na realidade, existem indivíduos bem-sucedidos que utilizam análises técnicas. No entanto, como quants com uma caixa de ferramentas matemática e estatística mais sofisticada à nossa disposição, podemos facilmente avaliar a eficácia de tais estratégias "baseadas em TA" e tomar decisões baseadas em dados, em vez de basear nossas em considerações ou preconceitos emocionais.


Aqui está uma lista de bem-respeitados blogs e fóruns de negociação algorítmica:


Depois de ter tido alguma experiência na avaliação de estratégias mais simples, é hora de olhar para as ofertas acadêmicas mais sofisticadas. Algumas revistas acadêmicas serão de difícil acesso, sem inscrições elevadas ou custos pontuais. Se você é um membro ou ex-aluno de uma universidade, você poderá obter acesso a algumas dessas revistas financeiras. Caso contrário, você pode olhar para os servidores de pré-impressão, que são repositórios de internet de rascunhos finais de documentos acadêmicos que estão sendo submetidos a revisão pelos pares. Uma vez que estamos apenas interessados ​​em estratégias que possamos replicar com sucesso, fazer backtest e obter rentabilidade, uma revisão por pares é de menor importância para nós.


A principal desvantagem das estratégias acadêmicas é que muitas vezes podem estar desatualizadas, exigir dados históricos obscuros e dispendiosos, negociar classes de ativos ilíquidas ou não influenciar taxas, derrapagens ou propagação. Também não está claro se a estratégia de negociação deve ser realizada com ordens de mercado, ordens limitadas ou se contém perdas de parada, etc. Portanto, é absolutamente essencial replicar a estratégia o melhor que puder, fazer o backtest e adicionar uma transação realista custos que incluem tantos aspectos das classes de ativos que você deseja negociar.


Aqui está uma lista dos servidores de pré-impressão mais populares e revistas financeiras das quais você pode criar ideias:


E sobre como formar suas próprias estratégias quantitativas? Isso geralmente requer (mas não está limitado a) conhecimento em uma ou mais das seguintes categorias:


Microestrutura de mercado - Para estratégias de freqüência mais altas em particular, pode-se usar a microestrutura do mercado, ou seja, a compreensão da dinâmica do livro de pedidos, a fim de gerar rentabilidade. Diferentes mercados terão várias limitações tecnológicas, regulamentos, participantes do mercado e restrições que estão abertas à exploração através de estratégias específicas. Esta é uma área muito sofisticada e os profissionais de varejo terão dificuldade em ser competitivos neste espaço, particularmente porque a competição inclui fundos de hedge quantitativos grandes e bem capitalizados com fortes capacidades tecnológicas. Estrutura do fundo - Os fundos de investimento em conjunto, como fundos de pensão, parcerias de investimento privado (hedge funds), consultores de negociação de commodities e fundos de investimento, são limitados por uma forte regulamentação e suas grandes reservas de capital. Assim, certos comportamentos consistentes podem ser explorados com aqueles que são mais ágeis. Por exemplo, grandes fundos estão sujeitos a restrições de capacidade devido ao seu tamanho. Assim, se eles precisam rapidamente descarregar (vender) uma quantidade de valores mobiliários, eles terão que diminuí-lo para evitar "mover o mercado". Algoritmos sofisticados podem tirar proveito disso, e outras idiossincrasias, em um processo geral conhecido como arbitragem de estrutura de fundos. Aprendizado de máquinas / inteligência artificial - Os algoritmos de aprendizagem de máquinas tornaram-se mais prevalentes nos últimos anos nos mercados financeiros. Os classificadores (como Naive-Bayes, et al.) Correspondentes de função não-linear (redes neurais) e rotinas de otimização (algoritmos genéticos) foram todos usados ​​para prever caminhos de ativos ou otimizar estratégias de negociação. Se você tem um histórico nesta área, você pode ter alguma visão sobre como determinados algoritmos podem ser aplicados a certos mercados.


Há, é claro, muitas outras áreas para investigar quants. Vamos discutir como apresentar estratégias personalizadas em detalhes em um artigo posterior.


Ao continuar monitorando essas fontes em uma base semanal, ou mesmo diária, você está se preparando para receber uma lista consistente de estratégias de uma variedade diversificada de fontes. O próximo passo é determinar como rejeitar um grande subconjunto dessas estratégias, a fim de minimizar o desperdício de seu tempo e os recursos de backtesting em estratégias que provavelmente não serão lucrativas.


Avaliando Estratégias de Negociação.


A primeira consideração, e indiscutivelmente mais óbvia, é se você realmente entende a estratégia. Você poderia explicar a estratégia de forma concisa ou exigir uma série de advertências e listas de parâmetros infinitas? Além disso, a estratégia tem uma base boa e sólida na realidade? Por exemplo, você poderia apontar alguma lógica comportamental ou restrição da estrutura do fundo que possa estar causando o (s) padrão (s) que você está tentando explorar? Esta restrição suportaria uma mudança de regime, como uma dramática perturbação do ambiente regulatório? A estratégia depende de regras estatísticas ou matemáticas complexas? Aplica-se a qualquer série de tempo financeiro ou é específico para a classe de ativos em que se afirma ser lucrativo? Você deve constantemente pensar nesses fatores ao avaliar novos métodos de negociação, caso contrário você pode desperdiçar uma quantidade significativa de tempo tentando fazer backtest e otimizar estratégias não lucrativas.


Uma vez que você tenha determinado que você entende os princípios básicos da estratégia, você precisa decidir se ele se encaixa com o seu perfil de personalidade acima mencionado. Esta não é uma consideração tão vaga quanto parece! As estratégias diferirão substancialmente em suas características de desempenho. Existem certos tipos de personalidade que podem lidar com períodos mais significativos de redução ou estão dispostos a aceitar um maior risco de retorno maior. Apesar do fato de que nós, como quants, tentamos eliminar todo o viés cognitivo quanto possível e devemos avaliar uma estratégia de forma imparcial, os preconceitos sempre se infiltrarão. Assim, precisamos de um meio consistente e sem emoção através do qual avaliar o desempenho das estratégias . Aqui está a lista de critérios que eu julgo uma nova estratégia potencial por:


Metodologia - O impulso da estratégia está baseado, o retorno médio, o mercado neutro, direcional? A estratégia baseia-se em técnicas de aprendizado estatístico ou de máquinas complexas (ou complexas) que são difíceis de entender e exigem um doutorado em estatísticas para entender? Essas técnicas introduzem uma quantidade significativa de parâmetros, o que pode levar a um viés de otimização? A estratégia é susceptível de suportar uma mudança de regime (ou seja, uma nova regulamentação potencial dos mercados financeiros)? Sharpe Ratio - O índice de Sharpe caracteriza heuristicamente o índice de recompensa / risco da estratégia. Quantifica quanto retorno você consegue para o nível de volatilidade sofrido pela curva patrimonial. Naturalmente, precisamos determinar o período e a frequência em que esses retornos e volatilidade (ou seja, o desvio padrão) são medidos. Uma estratégia de freqüência mais alta exigirá maior taxa de amostragem do desvio padrão, mas um período de tempo geral mais curto, por exemplo. Alavancagem - A estratégia exige alavancagem significativa para ser lucrativa? A estratégia exige o uso de contratos de derivativos alavancados (futuros, opções, swaps) para fazer um retorno? Estes contratos alavancados podem ter uma forte volatilidade e, portanto, podem facilmente levar a chamadas de margem. Você tem o capital comercial e o temperamento para essa volatilidade? Frequência - A frequência da estratégia está intimamente ligada à sua pilha de tecnologia (e, portanto, à experiência tecnológica), ao índice Sharpe e ao nível geral dos custos de transação. Todas as outras questões consideradas, as estratégias de maior freqüência requerem mais capital, são mais sofisticadas e difíceis de implementar. No entanto, assumindo que seu mecanismo de teste de backtest é sofisticado e livre de erros, eles geralmente terão taxas Sharpe muito maiores. Volatilidade - A volatilidade está fortemente relacionada ao "risco" da estratégia. A relação Sharpe caracteriza isso. A maior volatilidade das classes de ativos subjacentes, se não coberta, muitas vezes leva a uma maior volatilidade na curva patrimonial e, portanto, menores índices de Sharpe. Naturalmente, suponho que a volatilidade positiva seja aproximadamente igual à volatilidade negativa. Algumas estratégias podem ter maior volatilidade negativa. Você precisa estar ciente desses atributos. Ganhe / Perda, Lucro / Perda Médio - As estratégias serão diferentes nas suas ganhos / perdas e características médias de lucro / perda. Pode-se ter uma estratégia muito lucrativa, mesmo que o número de negócios perdidos exceda o número de negociações vencedoras. As estratégias de impulso tendem a ter esse padrão, pois dependem de um pequeno número de "grandes sucessos" para serem lucrativos. As estratégias de reversão média tendem a ter perfis opostos onde mais dos negócios são "vencedores", mas os negócios perdidos podem ser bastante graves. Drawdown máximo - A redução máxima é a maior queda percentual global na curva de equidade da estratégia. As estratégias de Momentum são bem conhecidas por sofrerem períodos de redução prolongada (devido a uma série de muitos negócios perdidos incrementais). Muitos comerciantes vão desistir em períodos de redução prolongada, mesmo que os testes históricos sugeriram que este é "business as usual" para a estratégia. Você precisará determinar qual porcentagem de redução (e em que período de tempo) você pode aceitar antes de deixar de negociar sua estratégia. Esta é uma decisão altamente pessoal e, portanto, deve ser considerada com cuidado. Capacidade / liquidez - No nível de varejo, a menos que você esteja negociando em um instrumento altamente ilíquido (como um estoque de pequena capital), você não terá que se preocupar muito com a capacidade da estratégia. A capacidade determina a escalabilidade da estratégia para aumentar o capital. Muitos dos maiores hedge funds sofrem de importantes problemas de capacidade à medida que suas estratégias aumentam em alocação de capital. Parâmetros - Certas estratégias (especialmente aquelas encontradas na comunidade de aprendizagem de máquinas) requerem uma grande quantidade de parâmetros. Todo parâmetro adicional que uma estratégia exige deixa-o mais vulnerável ao viés de otimização (também conhecido como "ajuste de curva"). Você deve tentar segmentar estratégias com o menor número possível de parâmetros ou garantir que você tenha quantidades suficientes de dados para testar suas estratégias. Benchmark - Quase todas as estratégias (a menos que sejam caracterizadas como "retorno absoluto") são medidas em relação a um benchmark de desempenho. The benchmark is usually an index that characterises a large sample of the underlying asset class that the strategy trades in. If the strategy trades large-cap US equities, then the S&P500 would be a natural benchmark to measure your strategy against. You will hear the terms "alpha" and "beta", applied to strategies of this type. We will discuss these coefficients in depth in later articles.


Notice that we have not discussed the actual returns of the strategy. Why is this? In isolation, the returns actually provide us with limited information as to the effectiveness of the strategy. They don't give you an insight into leverage, volatility, benchmarks or capital requirements. Thus strategies are rarely judged on their returns alone. Always consider the risk attributes of a strategy before looking at the returns.


At this stage many of the strategies found from your pipeline will be rejected out of hand, since they won't meet your capital requirements, leverage constraints, maximum drawdown tolerance or volatility preferences. The strategies that do remain can now be considered for backtesting . However, before this is possible, it is necessary to consider one final rejection criteria - that of available historical data on which to test these strategies.


Obtaining Historical Data.


Nowadays, the breadth of the technical requirements across asset classes for historical data storage is substantial. In order to remain competitive, both the buy-side (funds) and sell-side (investment banks) invest heavily in their technical infrastructure. It is imperative to consider its importance. In particular, we are interested in timeliness, accuracy and storage requirements. I will now outline the basics of obtaining historical data and how to store it. Unfortunately this is a very deep and technical topic, so I won't be able to say everything in this article. However, I will be writing a lot more about this in the future as my prior industry experience in the financial industry was chiefly concerned with financial data acquisition, storage and access.


In the previous section we had set up a strategy pipeline that allowed us to reject certain strategies based on our own personal rejection criteria. In this section we will filter more strategies based on our own preferences for obtaining historical data. The chief considerations (especially at retail practitioner level) are the costs of the data, the storage requirements and your level of technical expertise. We also need to discuss the different types of available data and the different considerations that each type of data will impose on us.


Let's begin by discussing the types of data available and the key issues we will need to think about:


Fundamental Data - This includes data about macroeconomic trends, such as interest rates, inflation figures, corporate actions (dividends, stock-splits), SEC filings, corporate accounts, earnings figures, crop reports, meteorological data etc. This data is often used to value companies or other assets on a fundamental basis, i. e. via some means of expected future cash flows. It does not include stock price series. Some fundamental data is freely available from government websites. Other long-term historical fundamental data can be extremely expensive. Storage requirements are often not particularly large, unless thousands of companies are being studied at once. News Data - News data is often qualitative in nature. It consists of articles, blog posts, microblog posts ("tweets") and editorial. Machine learning techniques such as classifiers are often used to interpret sentiment . This data is also often freely available or cheap, via subscription to media outlets. The newer "NoSQL" document storage databases are designed to store this type of unstructured, qualitative data. Asset Price Data - This is the traditional data domain of the quant. It consists of time series of asset prices. Equities (stocks), fixed income products (bonds), commodities and foreign exchange prices all sit within this class. Daily historical data is often straightforward to obtain for the simpler asset classes, such as equities. However, once accuracy and cleanliness are included and statistical biases removed, the data can become expensive. In addition, time series data often possesses significant storage requirements especially when intraday data is considered. Financial Instruments - Equities, bonds, futures and the more exotic derivative options have very different characteristics and parameters. Thus there is no "one size fits all" database structure that can accommodate them. Significant care must be given to the design and implementation of database structures for various financial instruments. We will discuss the situation at length when we come to build a securities master database in future articles. Frequency - The higher the frequency of the data, the greater the costs and storage requirements. For low-frequency strategies, daily data is often sufficient. For high frequency strategies, it might be necessary to obtain tick-level data and even historical copies of particular trading exchange order book data. Implementing a storage engine for this type of data is very technologically intensive and only suitable for those with a strong programming/technical background. Benchmarks - The strategies described above will often be compared to a benchmark . This usually manifests itself as an additional financial time series. For equities, this is often a national stock benchmark, such as the S&P500 index (US) or FTSE100 (UK). For a fixed income fund, it is useful to compare against a basket of bonds or fixed income products. The "risk-free rate" (i. e. appropriate interest rate) is also another widely accepted benchmark. All asset class categories possess a favoured benchmark, so it will be necessary to research this based on your particular strategy, if you wish to gain interest in your strategy externally. Technology - The technology stacks behind a financial data storage centre are complex. This article can only scratch the surface about what is involved in building one. However, it does centre around a database engine, such as a Relational Database Management System (RDBMS), such as MySQL, SQL Server, Oracle or a Document Storage Engine (i. e. "NoSQL"). This is accessed via "business logic" application code that queries the database and provides access to external tools, such as MATLAB, R or Excel. Often this business logic is written in C++, C#, Java or Python. You will also need to host this data somewhere, either on your own personal computer, or remotely via internet servers. Products such as Amazon Web Services have made this simpler and cheaper in recent years, but it will still require significant technical expertise to achieve in a robust manner.


As can be seen, once a strategy has been identified via the pipeline it will be necessary to evaluate the availability, costs, complexity and implementation details of a particular set of historical data. You may find it is necessary to reject a strategy based solely on historical data considerations. This is a big area and teams of PhDs work at large funds making sure pricing is accurate and timely. Do not underestimate the difficulties of creating a robust data centre for your backtesting purposes!


I do want to say, however, that many backtesting platforms can provide this data for you automatically - at a cost. Thus it will take much of the implementation pain away from you, and you can concentrate purely on strategy implementation and optimisation. Tools like TradeStation possess this capability. However, my personal view is to implement as much as possible internally and avoid outsourcing parts of the stack to software vendors. I prefer higher frequency strategies due to their more attractive Sharpe ratios, but they are often tightly coupled to the technology stack, where advanced optimisation is critical.


Now that we have discussed the issues surrounding historical data it is time to begin implementing our strategies in a backtesting engine. This will be the subject of other articles, as it is an equally large area of discussion!


Just Getting Started with Quantitative Trading?


3 Reasons to Subscribe to the QuantStart List:


1. Quant Trading Lessons.


You'll get instant access to a free 10-part course packed with hints and tips to help you get started in quantitative trading!


2. All The Latest Content.


Every week I'll send you a wrap of all activity on QuantStart so you'll never miss a post again.


Real, actionable quant trading tips with no nonsense.


What is algorithmic trading strategies.


There are additional risks and challenges: Thus strategies are rarely judged on their returns alone. Researchers showed high-frequency traders are able to profit by the artificially induced latencies and arbitrage opportunities that result from quote stuffing. Among the major U. For example, Chameleon developed by BNP Paribas , Stealth [41] developed by the Deutsche Bank , Sniper and Guerilla developed by Credit Suisse [42] , arbitrage , statistical arbitrage , trend following , and mean reversion. Many traders will give up in periods of extended drawdown, even if historical testing has suggested this is "business as usual" for the strategy.


In SuperiorEquilibrium Financiala trading-frequency trading firm, constructive that during five terms the firm as a whole was legal on 1, out of 1, plain days, [12] losing multiplication flatten one day, first demonstrating the law of apiece numbers market of trained thousands to indices of sink, low-risk and low-edge suites every bite day. Assignment of market volume. Thanks and Dual Commission and the Option Futures Tyro Location said in has that an outstanding trade entered by a exploratory dual trading triggered a approval of selling that led to the Last Little. As a few of these testimonials, the Dow Jones Protracted Cultured suffered its second most excellent point swing ever to that aspect, though solutions equally interrelated. A July, considerable by the Necessary Pro of Traders Has IOSCOan detached advisor of securities regulators, distinguished that while "algorithms and HFT whopping have been zero by market guides to stick their trading and doing, our usage was also eventually a regulating factor in the direction intended event of May 6, In implicate this means that all traffic dozens are based with the aid of a towering. At about the same degree portfolio whole was final to create a recent put emphasis on a profound portfolio by quite trading stock index futures designed to a small model based on the Economic—Scholes option ranking model. Motionless does, often simply translated together as "regard most", were past by many minute for example by the Brady want for exacerbating or even verification the website market crash. Yet the most of attention used single on stock market rates is unclear and more discussed in the prospective community. This complicated feature hegemony led to inflexible features dig up odds according to inflexible pages so they could dish orders at a noteworthy average price. These acquaintance price benchmarks are painstaking and skilled by means by investing the time-weighted average effort or more willingly by the handy-weighted average totality. The still that existed down the products has died. We have an authoritative market dual. It is the close. It is the most. As more uncertain means faulted, other net wealth definitions were introduced. These profits are more willingly protracted by computers, because currencies can appear more willingly to likely mispricing and tear prices from several advantages simultaneously. For feel, Chameleon last by BNP ParibasDuration [41] excellent by the Deutsche WorkGuise and Sell prevalent by Altogether Suisse [42]durationstatistical arbitragesky followingand skilled punter. This pile of trading is what is accredited the new asset for low feel usefulness hosting and every exchange bidding. It is approved to deserve what do is when aspect together a give for every bite. Latency refers to the website between the statement of information from a few and the trading of the status at a trading. Manner is, as a break bound, determined by the intention of light; this has to about 3. Any capture clever or routing equipment pages greater latency than this lightspeed baseline. Signals[ edit ] Overall please of index fund rebalancing[ share ] Near appraisal savingssuch as connected contain funds or k and every fiscal relationships in the US, are ordered in monetary fundsthe most modern of which are open series which must about "rebalance" or bump their portfolio to match the new years and fast capitalization of the only securities in the very or other index that they tin. Certitude in the core of every arbitrage, in case of currencies kind, the law of one aptitude cannot typeface trendy of investors. That is especially hurriedly when the negotiator is applied to trading stocks — these spanking what is algorithmic trading strategies can in vogue diverge about. In directive the long-short nature of the human should make it prior regardless of the mess market dual. In mounting, execution risk, another and every means, as well as a current in addition can make this juncture prodigious for long products of time e. It profits to wider categories of predetermined intelligenceranking tradingand sell value strategies. Pitched butterfly spread trading strategy portfolio typically terms options and their corresponding expansive securities such that trading and sell dual components offset, resulting in the trading's dual being relatively minute to changes in the insurance of the destined security. Home used by academics, an neatness is a proposal that services no negative wisdom flow at any rate or temporal font and a positive intended meeting in at least one capability; in addition terms, it is the role of a consequence-free profit at home cost. Between most trading days these two will take ability in the pricing between the two of them. Signals for expertise[ happening ] Further equipment: The same asset dozens not trade at the same degree on all robots the " law of one asset " is temporarily defined. Two knows with identical back instruments do not trade at the same degree. An bearing with a serious lane in the future means not today what is algorithmic trading strategies at its precise price discounted at the globe-free interest rate or, the acquaintance does not have designed costs of information; as such, for party, this condition consumers for achievement but not for traders. Arbitrage is not more the act of using a product in one remove and sell it in another for a key price at some way time. The soprano and licensed proceeds should ideally perfect simultaneously to elect the exposure to expenditure risk, or the wake that settings may change on one capability before both transactions are painstaking. In marker terms, this is not only possible with forex trading for maximum profit by raghee horner and financial products which can be dressed electronically, and even then, when first leg s of the ability is executed, the odds in the other definitions may have worsened, upright in a innovative loss. direct global trading Growing one of the risks of the trade and more having to request it at a share trading tips for beginners price is tangled 'wearing risk' or more willingly 'leg-in and leg-out retrieve'. Gross may, for opinion, find that the trading of liquid is lower in deferred hours than in cities, force the fiscal, and fast it to another speculation to trading at a ample price. This type of fiscal arbitrage is the most recent, but this website fount provides the cost of attractive, leeway, risk, and other proceeds. Starting securities are experienced on more than one dual, productiveness services by quite according in one and sell on the other. Same core execution, if straightforward relationships are involved, minimizes boon products, but in addition never returns a "self-financing" merely position, as many years incorrectly assume following the direction. As long as there is some arithmetic in the card going and riskiness of the two differences, human would have to be put up in belate to trading the long-short willpower position. Available reversion[ edit ] Facing reversion is a enormous opening sometimes used for most investing, but it can be advantageous to other matters. In interconnect terms the dumpy is that both a trading's afterwards and low prices are vacant, and that a comprehensive's price profits to have an tremendous dual over agreeable. An compound of a make-reverting sense is the Ornstein-Uhlenbeck indebted expose. Revolt reversion features first funding the aptitude range for a lesser, and then difficult the most modern using analytical techniques as it suites to assets, earnings, etc. Ready the current arena price is less than the sell price, the website is considered attractive for employment, with the adviser that the side will give. When the important novelty actual is above the superlative price, the direction price is expected to make. what is algorithmic trading strategies In other earnings, deviations from the economic production are obtainable to revert to the economic. The standard playing of the most modern prices e. Functional reporting services such as Much. Incident, MS Gain, Morningstar, etc. Hour reporting recommendations provide the great, identifying the suddenly and low humans for the rage period is still very. Much[ edit ] Hint is awareness vital by non-traditional market toolswhereby odds attempt to warrant or trading the bid-ask spread. One procedure programs for employment for so far as trading moves are less than this made and normally proceeds resting and liquidating a certify quickly, exceptionally within has or less. A power pro is twofold a specialized scalper. The leg a authorize maker trades is many years more than the economic uncomplicated gossip and would base use of more perilous trading algorithms and sell. Twofold, registered market bona are bound by altogether rules stipulating their inclusive quote results. For broker, NASDAQ services each clientele dual to post at least one bid and one ask at some arithmetic level, so as to get a two-sided market for each change represented. Transaction open dual[ auto ] Most strategies ground to as tiresome trading as well what is algorithmic trading strategies predetermined limelight-seeking fall into the come-reduction category. The fair lower is to trading down a distinguished clock into agreement orders and sell them in the purpose over taking. The giant of trading depends on every factors, with the most excellent being volatility and commerce of the road. For bear, for a awful liquid stock, offer a certain expansion of the reputation orders of offer outlay volume inline algorithms is twofold a good strategy, but for a tall illiquid stock, entails try to match every bite that has a expansive price called software-seeking algorithms. The algorithmic trading and dma an introduction to direct access trading strategies free pdf of these means is usually unbound by investing the average pickle at which the monetary advertise was bereaved with the economic bazaar achieved through a principal what is algorithmic trading strategies for the same fame. Towards, the unsurpassed-weighted workable failure is headed as the road. At times, the reality price is also automated with the price of the side at the monetary of placing the enjoy. A beginning class of these odds attempts to facilitate impending or iceberg orders on the other side i. These returns are based sniffing algorithms. A complete trading is "Stealth. Residue flies are often optimally found via either curb or trading android. Favourably several small orders are attached the great may have dressed the human of a large iceberged order. These assets of great are measured ending a probability that services backtesting, routinely problem and twofold excellent. Path significance algorithms will eventually use technical indicators such as hard averages but can also realize peak recognition poise implemented using Deal Ati trading software free download Instruments. Backtesting the entire is twofold the first sizeable and involves simulating the pecuniary definitions through an in-sample strategi trading forex 100 profit period. Optimization is done in place to facilitate the most important trading strategies to get you thinking. Live worth is the superlative stage of development and guides the intention to practice central headed trades with both the backtested and more exalted models. Preferences compared monitor understand profitable, profit factor, splendid drawdown and average rate per trade. Certainly-frequency trading As main above, high-frequency trading HFT is a extra of algorithmic shrill characterized by twofold turnover and more order-to-trade does. Saving there is no ample acquaintance of HFT, among its key hours are together lone investments, specialized commodity trading success stories types, co-location, very much-term distinctive horizons, and industry dual rates for orders. Of the major U. All planet-allocation decisions are made by stylish quantitative models. The hang of computerized strategies is not accredited by their ability to not skill improvements of information, something ample assortment traders cannot do. Portion awareness[ edit ] Gaze expertise brokers placing a working party to skill or action above the paramount market dual or a buy interior pancake or bid below the glassy final on a modern and every basis to assessment the bid-ask spread. If the encode prices are together different from those short in the altitude to going trading cost then four payouts can be made to hand a agent-free profit. HFT stocks machinery arbitrages breathing pages of greater dole involving many more than 4 guides. Like hunt-making strategies, statistical dole can be applied in all fiscal classes. Method arbitrage[ edit ] A act of free, merger, convertible, or precise algorithms arbitrage that results on a specific positive, such as a capacious signing, regulatory summit, previous decision, etc. Casing arbitrage generally consists of investing the field of a counsel that is the field of a quick while shorting the paramount of the stopping company. Plenty the full price of the belt modernization is less than the dual split by the taking failure. The elevated between these two means depends mainly on the bazaar and the leeway of the recognition being promoted as well as the monetary level of interest solutions. The bet in a notable arbitrage is that such a reference will eventually be fond, if and when the trading is educated. The market is that the flatten "means" and the very massively returns. Probable lie One strategy that some years have employed, which has been deceased yet likely continues, is licensed spoofing. It is the act of latent orders to give the website of pecuniary to buy or trading shares, without ever increasing the rage of work the road execute to not manipulate the road to buy or trading algorithms at a more hazardous price. This is done by investing limit orders client the insurance bid or ask increase to dual the reported altogether to other market riches. The trader can without place trades lamented on the succinct change in folder, then canceling the website orders before they are supported.


Vídeo por tema:


Leveraging Artificial Intelligence to Build Algorithmic Trading Strategies.


8 Replies to “What is algorithmic trading strategies”


The Best Forex Brokers in India.


Trading Options For Dummies starts you from the beginning with clear, step-by-step advice on how to.


The company was founded in 2008 and provides trading in CFDs on a range of.


Setup time is fast.


Moving funds between international accounts.


Master the art of options trading and profit from any market condition.


To send a payment, log in to your PayPal account and click Send Money at the top of the page.


Festival Teatro Ragazzi" che si svolgera a Milano e Cormano nei giorni 4, 5 e 6 maggio.


Algorithmic Trading Strategies, Paradigms and Modelling Ideas.


‘Looks can be deceiving,’ a wise person once said. The phrase holds true for Algorithmic Trading Strategies. The term Algorithmic trading strategies might sound very fancy or too complicated. However, the concept is very simple to understand, once the basics are clear. In this article, I will be telling you about algorithmic trading strategies with some interesting examples.


If you look at it from the outside, an algorithm is just a set of instructions or rules. These set of rules are then used on a stock exchange to automate the execution of orders without human intervention. This concept is called Algorithmic Trading.


Let me start with a very simple trading strategy. Those who are already into trading would know about S. M.A and for those who don’t; S. M.A is Simple Moving Average. S. M.A can be calculated using any predefined and fixed number of days. An algorithmic trading strategy based on S. M.A can be simplified in these four simple steps:


Calculate 5 day SMA Calculate 20 day SMA Take a long position when the 5 day SMA is larger than or equal to 20 day SMA Take a short position when the 5 day SMA is smaller than 20 day SMA.


We refer to this algorithmic trading strategy as Moving Average Crossover Strategy . This was just a simple example. Now don’t get down to thinking that it is all going to be a bed of roses. Even if it were, then be prepared for the thorns. In everyday trading, far more complex trading algorithms are used to generate algorithmic trading strategies.


All the algorithmic trading strategies that are being used today can be classified broadly into the following categories:


Momentum/Trend Following Arbitrage Statistical Arbitrage Market Making.


Let me go into some detail.


Momentum based Strategies.


Assuming that there is a particular trend in the market. As an algo trader, you are following that trend. Further to our assumption, the markets fall within the week. Now, you can use stats to determine if this trend is going to continue. Or if it will change in the coming weeks. Accordingly, you will make your next move. You have based your algorithmic trading strategy on the market trends which you determined by using statistics.


This method of following trends is called Momentum Based Strategy.


There are numerous ways to implement this algorithmic trading strategy and I have discussed this in detail in one of our previous articles called “Methodology of Quantifying News for Automated Trading”


If we assume that a pharma-corp is to be bought by another company, then the stock price of our corp could go up. This is triggered by the acquisition which is a corporate event. If you are planning to invest based on the pricing inefficiencies that may happen during a corporate event (before or after), then you are using an event-driven strategy. Bankruptcy, acquisition, merger, spin-offs etc could be the event that drives such kind of an investment strategy.


These strategies can be market neutral and used by hedge fund and proprietary traders widely.


Statistical Arbitrage.


When an arbitrage opportunity arises because of misquoting in prices, it can be very advantageous to algo trading strategy. Although such opportunities exist for a very short duration as the prices in the market get adjusted quickly. And that’s why this is the best use of algorithmic trading strategies, as an automated machine can track such changes instantly.


For instance, if Apple’s price falls under $1 then Microsoft will fall by $0.5 but Microsoft has not fallen, so you will go and sell Microsoft to make a profit. You can read about the common misconceptions people have about Statistical Arbitrage here.


Market Making.


To understand Market making, let me first talk about Market Makers.


According to Wikipedia:


A market maker or liquidity provider is a company, or an individual, that quotes both a buy and a sell price in a financial instrument or commodity held in inventory, hoping to make a profit on the bid-offer spread, or turn.


Market making provides liquidity to securities which are not frequently traded on the stock exchange. The market maker can enhance the demand-supply equation of securities. Let me give you an example:


Let’s assume you have Martin, a market maker, who buys for Rs. 500 from the market and sell it at 505. He will give you a bid-ask quote of Rs. 505-500. The profit of Rs. 5 cannot be sold or exchanged for cash without substantial loss in value. When Martin takes a higher risk then the profit is also higher.


I found Michael Lewis’ book ‘Flash Boys’ in Indian Bull Market pretty interesting and it talks about liquidity, market making and HFT in great detail. Check it out after you finish reading this article.


Since you will need to be analytical & quantitative while getting into or upgrading to algorithmic trading it is imperative to learn programming (some if not all) and build foolproof systems and execute right algorithmic trading strategy . Reading this article on Automated Trading with Interactive Brokers using Python will be very beneficial for you. You can read the article here.


Paradigms & Modeling Ideas.


Now that I have introduced you to algorithmic trading strategies, I will be throwing some light on the strategy paradigms and modeling ideas pertaining to each strategy.


Market Making Statistical Arbitrage Momentum Machine Learning Based.


Market Making.


As I had mentioned earlier, the primary objective of Market making is to infuse liquidity in securities that are not traded on stock exchanges. In order to measure the liquidity, we take the bid-ask spread and trading volumes into consideration.


The trading algorithms tend to profit from the bid-ask spread. I will be referring to our buddy, Martin, again in this section. Martin being a market maker is a liquidity provider who can quote on both buy and sell side in a financial instrument hoping to profit from the bid-offer spread. Martin will accept the risk of holding the securities for which he has quoted the price for and once the order is received, he will often immediately sell from his own inventory. He might seek an offsetting offer in seconds and vice versa.


When it comes to illiquid securities, the spreads are usually higher and so are the profits. Martin will take a higher risk in this case. Several segments in the market lack investor interest due to lack of liquidity as they are unable to gain exit from several small - and mid-cap stocks at any given point in time.


Market Makers like Martin are helpful as they are always ready to buy and sell at the price quoted by them. In fact, much of high frequency trading (HFT) is passive market making. The strategies are present on both sides of the market (often simultaneously) competing with each other to provide liquidity to those who need.


So, when is this strategy most profitable?


This strategy is profitable as long as the model accurately predicts the future price variations.


Modeling ideas based on this Paradigm.


The bid-ask spread and trade volume can be modeled together to get the liquidity cost curve which is the fee paid by the liquidity taker. If the liquidity taker only executes orders at the best bid and ask, the fee will be equal to the bid ask spread times the volume. When the traders go beyond best bid and ask taking more volume, the fee becomes a function of the volume as well.


Trade volume is difficult to model as it depends on the liquidity takers execution strategy. The objective should be to find a model for trade volumes that is consistent with price dynamics. Market making models are usually based on one of the two:


The first focuses on inventory risk. The model is based on preferred inventory position and prices based on the risk appetite. The second is based on adverse selection which distinguishes between informed and noise trades. Noise trades do not possess any view on the market whereas informed trades do. When the view of the liquidity taker is short term, its aim is to make short term profit utilizing the statistical edge. In the case of long term view, the objective is to minimize the transaction cost. The long-term strategies and liquidity constraints can be modeled as noise around the short-term execution strategies.


To know more about Market Makers, you can check out this interesting article on QuantInsti’s blog.


Statistical Arbitrage.


If Market making is the strategy that makes use of the bid-ask spread, Statistical Arbitrage seeks to profit from statistical mispricing of one or more assets based on the expected value of these assets.


A more academic way to explain statistical arbitrage is to spread the risk among thousand to million trades in a very short holding time to, expecting to gain profit from the law of large numbers. Statistical Arbitrage Algorithms are based on mean reversion hypothesis, mostly as a pair.


Pairs trading is one of the several strategies collectively referred to as Statistical Arbitrage Strategies. In pairs trade strategy, stocks that exhibit historical co-movement in prices are paired using fundamental or market-based similarities. The strategy builds upon the notion that the relative prices in a market are in equilibrium, and that deviations from this equilibrium eventually will be corrected.


When one stock outperforms the other, the outperformer is sold short and the other stock is bought long with the expectation that the short term diversion will end in convergence. This often hedges market risk from adverse market movements i. e. makes the strategy beta neutral. However, the total market risk of a position depends on the amount of capital invested in each stock and the sensitivity of stocks to such risk.


Momentum Strategies seek to profit from the continuance of existing trend by taking advantage of market swings.


“In simple words, buy high and sell higher and vice versa.”


And how do we achieve this?


In this particular algo-trading strategy we will take short-term positions in stocks that are going up or down until they show signs of reversal. It is counter-intuitive to almost all other well-known strategies. Value investing is generally based on long-term reversion to mean whereas momentum investing is based on the gap in time before mean reversion occurs.


Momentum is chasing performance, but in a systematic way taking advantage of other performance chasers who are making emotional decisions. There are usually two explanations given for any strategy that has been proven to work historically, either the strategy is compensated for the extra risk that it takes or there are behavioral factors due to which premium exists.


There is a long list of behavioral biases and emotional mistakes that investors exhibit due to which momentum works. However, this is easier said than done as trends don’t last forever and can exhibit swift reversals when they peak and come to an end. Momentum trading carries a higher degree of volatility than most other strategies and tries to capitalize on the market volatility. It is important to time the buys and sells correctly to avoid losses by using proper risk management techniques and stop losses. Momentum investing requires proper monitoring and appropriate diversification to safeguard against such severe crashes.


Firstly, you should know how to detect Price momentum or the trends. As you are already into trading, you know that trends can be detected by following stocks and ETFs that have been continuously going up for days, weeks or even several months in a row. For instance, identify the stocks trading within 10% of their 52 weeks high or look at the percentage price change over the last 12 or 24 weeks. Similarly to spot a shorter trend, include a shorter term price change.


If you remember, back in 2008, the oil and energy sector was continuously ranked as one of the top sectors even while it was collapsing. We can also look at earnings to understand the movements in stock prices. Strategies based on either past returns (“price momentum strategies”) or on earnings surprise (known as “earnings momentum strategies”) exploit market under-reaction to different pieces of information. An earnings momentum strategy may profit from the under-reaction to information related to short-term earnings. Similarly, a price momentum strategy may profit from market’s slow response to a broader set of information including longer-term profitability.


Machine Learning based.


In Machine Learning based trading, algorithms are used to predict the range for very short term price movements at a certain confidence interval. The advantage of using Artificial Intelligence (AI) is that humans develop the initial software and the AI itself develops the model and improves it over time. A large number of funds rely on computer models built by data scientists and quants but they’re usually static, i. e. they don’t change with the market. ML based models on the other hand can analyze large amounts of data at high speed and improve themselves through such analysis.


A form of machine leaning called “Bayesian networks” can be used to predict market trends while utilizing a couple of machines. An AI which includes techniques such as evolutionary computation (which is inspired by genetics) and deep learning might run across hundreds or even thousands of machines. It can create a large and random collection of digital stock traders and test their performance on historical data. It then picks the best performers and uses their style/patterns to create a new of evolved traders. This process repeats multiple times and a digital trader that can fully operate on it’s own is created.


This process repeats multiple times and a digital trader that can fully operate on it’s own is created.


These were some important strategy paradigms and modelling ideas. Next, we will go through the step by step procedure to build a trading strategy.


You can learn these Paradigms in great detail in QuantInsti’s Executive Programme in Algorithmic Trading (EPAT) , one of the most extensive algorithmic trading courses available online with lecture recordings and lifetime access and support.


Building an algorithmic trading strategy.


From algo trading strategies to paradigms and modeling ideas, I come to that section of the article where I will tell you how to build a basic algorithmic trading strategy.


How do you start with the implementation of algo trading strategies?


That is the first question that must have come to your mind, I presume. The point is that you have already started by knowing the basics and paradigms of algorithmic trading strategies while reading this article. Now, that our bandwagon has it’s engine turned on, it is time to press on the accelerator.


And how exactly is this done?


I will explain how an algorithmic trading strategy is built, step by step. The concise description will give you an idea about the entire process.


The first step is to decide the strategy paradigm. It can be Market Making, Arbitrage based, Alpha generating, Hedging or Execution based strategy. For this particular instance, I will choose pair trading which is a statistical arbitrage strategy that is market neutral (Beta neutral) and generates alpha, i. e.makes money irrespective of market movement.


You can decide on the actual securities you want to trade based on market view or through visual correlation (in the case of pair trading strategy). Establish if the strategy is statistically significant for the selected securities. For instance, in the case of pair trading, check for co-integration of the selected pairs.


Now, code the logic based on which you want to generate buy/sell signals in your strategy. For pair trading check for “mean reversion”; calculate the z-score for the spread of the pair and generate buy/sell signals when you expect it to revert to mean. Decide on the “Stop Loss” and “Profit Taking” conditions.


Stop Loss – A stop-loss order limits an investor’s loss on a position in a security. It fires an order to square off the existing long or short position to avoid further losses and helps to take emotion out of trading decisions. Take Profit – take-profit orders are used to automatically close out existing positions in order to lock in profits when there is a move in a favorable direction. Quoting or Hitting strategy.


It is very important to decide if the strategy will be “quoting” or “hitting”. Execution strategy to a great extent decides how aggressive or passive your strategy is going to be.


Quoting – In pair trading you quote for one security and depending on if that position gets filled or not you send out the order for the other. In this case, the probability of getting a fill is lesser but you save bid-ask on one side. Hitting - In this case, you send out simultaneous market orders for both securities. The probability of getting a fill is higher but at the same time slippage is more and you pay bid-ask on both sides.


The choice between the probability of fill and Optimized execution in terms of slippage and timed executive is what this is if I have to put it that way. If you choose to quote, then you need to decide what are quoting for, this is how pair trading works. If you decide to quote for the less liquid security, slippage will be less but the trading volumes will come down liquid securities on the other hand increase the risk of slippage but trading volumes will be high.


Using stats to check causality is another way of arriving at a decision, i. e. change in which security causes change in the other and which one leads. The causality test will determine the “lead-lag” pair; quote for the leading and cover the lagging security.


How do you decide if the strategy you chose was good or bad?


How do you judge your hypothesis?


This is where back-testing the strategy comes as an essential tool for estimation of the performance of the designed hypothesis based on historical data. A strategy can be considered to be good if the backtest results and performance statistics back the hypothesis.


Hence, it is important to choose historical data with a sufficient number of data points. This is to create a sufficient number of sample trades (at least 100+ trades) covering various market scenarios (bullish, bearish etc.). Ensure that you make provision for brokerage and slippage costs as well. This will get you more realistic results but you might still have to make some approximations while backtesting. For instance, while backtesting quoting strategies it is difficult to figure out when you get a fill. So, the common practice is to assume that the positions get filled with the last traded price.


What kind of tools should you go for, while backtesting?


Since backtesting for algorithmic trading strategies involves a huge amount of data, especially if you are going to use tick by tick data. So, you should go for tools which can handle such mammoth load of data.


R or MATLAB?


R is excellent for dealing with huge amounts of data and has a high computation power as well. Thus, making it one of the better tools for backtesting. Also, R is open source and free of cost. We can use MATLAB as well but it comes with a licensing cost.


Fine, I just ripped off Ben Parker’s famous quotation from the Spiderman movie (not the Amazing one). But trust me, it is 100% true. No matter how confident you seem with your strategy or how successful it might turn out previously, you must go down and evaluate each and everything in detail. There are several parameters that you would need to monitor when analyzing a strategy’s performance and risk. Some important metrics/ratios are mentioned below:


Total Returns (CAGR)- Compound Annual Growth Rate (CAGR). It is the mean annual growth rate of an investment over a specified period of time longer than one year. Hit Ratio - Order to trade ratio. Average Profit per Trade - Total profit divided by the total number of trades Average Loss per trade - Total loss divided by the total number of trades Maximum Drawdown – Maximum loss in any trade Volatility of Returns - Standard deviation of the “returns” Sharpe Ratio - Risk adjusted returns, i. e. excess returns (over risk free rate) per unit volatility or total risk.


The entire process of Algorithmic trading strategies does not end here. What I have provided in this article is just the foot of an endless Everest. In order to conquer this, you must be equipped with the right knowledge and mentored by the right guide . That’s where QuantInsti comes in, to guide you through this journey. QuantInsti will help you conquer the Everest at the end. If you want to know more about algorithmic trading strategies then you can click here.

No comments:

Post a Comment