Friday 16 June 2017

Quantitative Trading Strategies Excel


Um leitor comentários sobre a negociação usando Excel VBA e Factor Modelo Comentários reflexivos de um leitor John S. do Reino Unido sobre a sua experiência com a tecnologia de negociação e modelos: Tenho vindo a desenvolver os meus próprios sistemas automáticos de negociação automática usando Excel VBA e com base em regras que tenho Desenvolvido ao longo dos anos como um investidor privado ativo comerciante usando análise de dados técnicos e fundamentais. Um dos principais méritos na adoção de uma abordagem de sistema de negociação automática que me ajudou é evitar a tentação de interferência manual e, assim, melhorar a rentabilidade, mantendo a consistência. Eu encontrei o desafio de desenvolver um sistema bem sucedido muito rewarding de uma perspectiva pessoal como eu reconheço que há muitos que tentaram e falharam. No entanto, um problema que eu encontrei é o meu desejo em curso para modificar regularmente e melhorar o sistema que eu encontrei pode tornar-se contraproducente, pois há um perigo real de que o desenvolvimento do sistema se torna um fim em si mesmo eu simplesmente não consigo parar de mexer assim que eu Vir acima com uma nova idéia ou recurso Uma vantagem de usar o Excel VBA que eu encontrei é que é inerentemente flexível, pois facilita o processamento de dados que podem ser importantes, especialmente quando se utiliza dados fundamentais como parte do sistema. A este respeito eu reconheço que cada comerciante está tentando construir em uma borda que faça o sistema mais rentável. Tenho notado que muitos comerciantes parecem apenas foco no preço, tentando procurar uma vantagem, olhando para indicadores especiais ou combinação de indicadores, etc Combinando análise de dados de preços com uma abordagem de modelo de fator é um desafio que é idealmente Excel VBA como ele pode Ser facilmente utilizados para processar dados fundamentais e macroeconômicos em uma forma que pode ser integrada com a análise de dados de preços. Reconheço do seu livro que o Matlab é mais poderoso do que o Excel VBA e pode ser tão flexível na integração de dados fundamentais e macroeconômicos, mas eu só queria chamar a sua atenção para os benefícios que eu encontrei usando Excel VBA que pode se adequar aqueles que como eu são mais Confortável em usar o Excel VBA e estão relutantes em mudar. Outros recursos que podem ser explorados que eu encontrei útil quando back testing estão produzindo automaticamente gráficos de preços que incorporam pontos de entrada e saída, que fornece segurança visual que o sistema está funcionando como pretendido, bem como gerar relatórios automáticos Word gravação chave de saída para referência futura. Eu sinto muito se eu soar muito como um anúncio para Microsoft 7 comentários: Eu acho que as principais razões por trás de uma popularidade do ExcelVBA em um quant e o mundo comercial quant são: 1. Muitas pessoas já usá-lo - então todo mundo pensa thats o Caminho a percorrer 2. Simplicidade de VBA (não sei se se correlaciona com a sua flexibilidade) - que torna possível a utilização eficaz por qualquer pessoa - se é um comerciante, quant ou um desenvolvedor de mesa. 3. O VBA eo Excel podem ser facilmente estendidos (para melhorar o desempenho, integrar um software de terceiros ou apenas para fins de utilização modularizere), movendo a lógica do modelo real para C, COM ou como para o posterior (forma fácil de integrar o analytics quant Escrito em com Excel e VBA) - um pode ter um olhar para a minha solução: excel4net Eu definitivamente acho que o fator bandwagon está em jogo, estamos muitas vezes como ovelhas, e não vejo nenhuma razão pela qual a estratégia de investimento ou sistemas seriam diferentes. Um pouco de sorte não vai interferir no forex No entanto, um problema que eu encontrei é o meu desejo em curso para modificar regularmente e melhorar o sistema que eu encontrei pode tornar-se contraproducente, pois há um perigo real de que o desenvolvimento do sistema se torna um fim em si Ponto interessante. Eu acho que a melhor maneira de lidar com isso é aceitar (ou recusar) o tipo de relação WinLoss seu método de negociação produz. O que eu quero dizer é que se você comércio tendência de balcão e, psicologicamente, você só se sentir confortável com um alto nível de comércios vencedores, você terá dificuldade em lidar com um sistema que gera quantas vitórias ou perdas. Nessas circunstâncias, talvez você (e o sistema) fiquem em melhores condições estabelecendo critérios mais rígidos e sacrificando algumas configurações - mas não demasiadas - para conseguir um nível mais alto de negócios vencedores (mesmo que, no processo, você também Pode reduzir sua Média Média Perda Perda média). Mas eu concordo: a sua questão complicada que queimar evento os comerciantes mais experientes. No entanto, um problema que eu encontrei é o meu desejo em curso para modificar regularmente e melhorar o sistema que eu encontrei pode tornar-se contraproducente, pois há um perigo real de que o desenvolvimento do sistema se torna um fim em si mesmo Eu fiquei muito surpreso com o seu post. No mundo dos analistas quantitativos (design e implementação de modelos de derivativos etc. para bancos de investimento de primeira linha, eu passei 6 anos fazendo isso) Excel VBA é acreditado para ser a linguagem de programação menos flexível e sustentável que temos para lidar com sistemas escritos usando estes Línguas estão prestes a ser aposentado. Eu entendo que agora você ainda está feliz com isso, mas pensei que você poderia querer estudar as alternativas. Com um preço de entrada relativamente modesto, você pode obter desempenho e sustentabilidade que surpreendê-lo. VBA questões que vêm à mente são: mau desempenho, má gestão da memória (isso pode tornar o desempenho ainda pior), você não pode usar o sistema de controle de versão que lhe permitiria acompanhar mudanças (quem-o-por-quando) e facilitaria a colaboração (Ver, por exemplo, svnbook. red-beannightlyensvn. intro. whatis. htmlsvn. intro. righttool e tortoisesvn. tigris. org deve haver algumas ferramentas de controle de versão da Microsoft). Com base na minha experiência, a partir de algum código de volume VBA tornar-se incontrolável, uma das razões para isso ser que você não pode usar o controle de versão. Falta de flexibilidade (em comparação com as alternativas eu vou ser ausência de classes (métodos de estrutura de classe que pode acessar e modificar o conteúdo da estrutura) ausência virtual de mecanismos de abstração (Variant é muito propenso a erros). Você pode precisar deles se você quiser Usar o mesmo algoritmo para um estoque e para uma curva de rendimento (mesma ação, objetos diferentes).Outras linguagens são amigáveis ​​ao SVN (veja a terceira bala), Excel-friendly, mas Matlab é bastante caro (1K - 10K, dependendo de quais pacotes você precisa e em sua localização), muito mais agradável e mais amigável, equipe de suporte está pronto. Dica de desempenho Matlab: vectorize seu código (operar com vetores Por exemplo, vetor onde o elemento i seria um preço de estoque X na data de observação da data i dias ou matriz onde o elemento ij seria um rendimento da moeda Y na data i para a maturidade j). Outra maneira de s Peed up Matlab é comprar um pacote que pode converter código de código Matlab em código C, que pode ser compilado em uma DLL que você pode usar no Excel. Tal DLL funcionaria muito mais rápido (pode ser cem vezes mais rápido, depende de sua tarefa). Python é um freeware, bastante austero, leva um pouco de tempo para entrar nele, mas valeria a pena. É mais flexível, mais de uma linguagem de programação adequada. Outros idiomas que você pode querer considerar são C, VB e stand-alone VB (todos pela Microsoft, todos com preços razoáveis). Eu iria posicioná-los entre C (veja abaixo) e Excel VBA C seria o mais poderoso, VB seria o mais simples para você usar - é quase idêntico ao VBA. Mais uma vez, há um trade-off entre performanceflexibility e straight-forwardnesssimilarity para Excel VBA. Código C escrito à mão é o melhor do ponto de vista do desempenho, esta é uma linguagem bastante versátil, mas leva muito mais tempo para aprendê-lo. Espero que você iria encontrá-lo interessante. Olá Dr. Ernie Chan Eu li o seu livro sobre Quantitative trading. Diz-se que MATLAB é uma boa ferramenta para desenvolver estratégias complexas. Mas não há API bem aprovado para isso. Há um recentemente encontrado MATLAB2IB. Mas é bom o suficiente e bem testado Diz-se em seu livro que ExcelVBA é lento em comparação com C. Estou interessado em desenvolver um sistema automatizado de negociação. Devo usar este novo MATLAB2IB e continuar a desenvolver estratégias em Matlab Eu sou bom em Matlab e eu tenho usado extensivamente durante o meu doutorado e outros trabalhos. Eu não usei C muito e eu achei mais difícil em comparação com MATLAB. Dada uma escolha, eu sempre vou fazer codificação em MATLAB. Mas é necessário desenvolver estratégias em C, se eu quiser desenvolver um sistema de negociação automática Oi Vinay, eu tenho usado matlab2ibapi por vários meses, e achei que ele é bastante útil e confiável para automatizar minhas estratégias. Na verdade, vou estar publicando um artigo ilustrando como usá-lo. ErnieMany popular estratégias de negociação quantitativa são públicos por um bom tempo. Agora, se você gosta de utilizar tal estratégia com dinheiro real, você deve certificar-se de que sua estratégia executa bem. Para estratégias simples, o MS Excel é perfeito para esta tarefa. Mas, uma vez que gostaríamos de usar uma otimização e uma visualização específica mais tarde, usamos Theta Suite e Matlab. Isso também permite a análise de estratégias mais complexas, se você gosta. Configurando uma estratégia de negociação quantitativa: sinal do MACD 8211 Um dos indicadores técnicos mais populares é o Moving Average ConvergenceDivergence (MACD), que essencialmente a diferença entre duas médias móveis. A literatura diz, o cruzamento zero de uma linha MACD daria uma boa indicação para a compra de estoque de venda. Às vezes, eles acrescentam algum sinal de gatilho e alegação, isso seria ainda melhor. Vamos ver se isso é verdade. Mais precisamente MACD negociação é geralmente definida como resp. Em um loop ao longo do tempo, parece que EMA12 e EMA26 são duas médias exponenciais diferentes com constantes 8220constl128221 e 82208221constl268221. O EMA é definido como: O sistema de comércio adequado com um período de sinal de 8220constl 98221 parece Testar a estratégia com dados históricos reais Esta parte é muito importante. Eu não posso enfatizar este fato muito: em um post posterior, vamos falar sobre back-testing muito mais. A atribuição destes dados a um processo ThetaML permite a estimativa do desempenho da estratégia de negociação baseada no MACD. Aqui está um gráfico dos preços das ações da IBM de 2000-01-01 a 2011-12-31: Matlab parcela de preço das ações da IBM Backtesting a estratégia de negociação MACD Podemos executar os modelos ThetaML acima usando Theta Suite Orchestrator e conectá-lo com o histórico IBM no Matlab no Configurador. Então, no Explorador de Resultados, obtemos o desempenho da estratégia de negociação MACD-sinal correspondente sem venda curta Plote de desempenho da estratégia de negociação MACD e com venda a descoberto, parece Performance de MACD estratégia de negociação com venda a descoberto Note que durante a maioria dos anos , A estratégia MACD sinal não funciona melhor do que o próprio subjacente. Levando em conta os custos de transação, isso parece ainda pior. Curiosamente, o ano 2000 apresentou um grande desempenho da estratégia MACD, mas todos os anos posteriores não funcionou tão bem. Conclusão É fácil verificar se uma estratégia teria se comportado bem usando dados históricos. ThetaML e Matlab são excelentes ferramentas para esta tarefa. A estratégia de negociação baseada no MACD que analisamos não é significativamente melhor do que manter o próprio subjacente. Outros parâmetros da estratégia de negociação podem levar a melhores resultados, para que possamos realizar uma otimização. Vamos ver que na próxima semana. Novembro 30, 2016, 12:34 pm Alguns meses atrás, um leitor me apontar esta nova maneira de conectar R e Excel. Eu não sei por quanto tempo isto tem sido em torno, mas nunca me deparei com ele e nunca vi qualquer postagem no blog ou artigo sobre ele. Então eu decidi escrever um post como a ferramenta é realmente vale a pena e antes que alguém pergunta, I8217m não relacionados com a empresa de qualquer forma. BERT significa Basic Excel R Toolkit. It8217s livre (licenciado sob o GPL v2) e foi desenvolvido por Structured Data LLC. No momento da redação, a versão atual do BERT é 1.07. Mais informações podem ser encontradas aqui. De uma perspectiva mais técnica, o BERT foi projetado para suportar a execução de funções R a partir de células da planilha do Excel. Em termos de Excel, it8217s para escrever User-Defined Functions (UDFs) em R. Neste post I8217m não vai mostrar-lhe como R e Excel interagem via BERT. Existem muito bons tutoriais aqui. Aqui e aqui. Em vez disso eu quero mostrar-lhe como eu usei BERT para construir um 8220control tower8221 para o meu comércio. Meus sinais de negociação são gerados usando uma longa lista de arquivos R, mas eu preciso da flexibilidade do Excel para exibir resultados de forma rápida e eficiente. Como mostrado acima BERT pode fazer isso para mim, mas eu também quero adaptar a aplicação às minhas necessidades. Ao combinar o poder de XML, VBA, R e BERT eu posso criar uma boa aparência ainda poderosa aplicação sob a forma de um arquivo do Excel com o mínimo de código VBA. Finalmente, tenho um único arquivo Excel reunindo todas as tarefas necessárias para gerenciar meu portfólio: atualização de banco de dados, geração de sinal, envio de pedidos etc8230 Minha abordagem pode ser dividida nas 3 etapas abaixo: Use XML para criar menus e botões definidos pelo usuário em um Excel Arquivo. Os menus e botões acima são essencialmente chamadas para funções VBA. Essas funções VBA são wrapup em torno de funções R definidas usando BERT. Com essa abordagem, posso manter uma clara distinção entre o núcleo do meu código mantido em R, SQL e Python e tudo usado para exibir e formatar os resultados mantidos em Excel, VBA amp. XML. Nas próximas seções eu apresento o pré-requisito para desenvolver tal abordagem e um guia passo a passo que explica como o BERT poderia ser usado para simplesmente passar dados de R para o Excel com o mínimo de código VBA. 1 8211 Baixe e instale o BERT a partir deste link. Depois que a instalação for concluída você deve ter um novo menu Add-Ins no Excel com os botões, como mostrado abaixo. Foi assim que o BERT se materializou no Excel. 2 8211 Baixe e instale o editor de UI personalizado. O Custom UI Editor permite criar menus e botões definidos pelo usuário na fita Excel. Um procedimento passo a passo está disponível aqui. Guia passo a passo 1 8211 Código R: A função abaixo R é um código muito simples para fins de ilustração. Calcula e retorna os resíduos de uma regressão linear. Isso é o que queremos recuperar no Excel. Salve isso em um arquivo chamado myRCode. R (qualquer outro nome é muito bem) em um diretório de sua escolha. 2 8211 funções. R no BERT. No Excel, selecione Add-Ins - gt Home Directory e abra o arquivo chamado functions. R. Neste arquivo cole o seguinte código. Certifique-se de inserir o caminho correto. Este é apenas sourcing em BERT o arquivo R que você criou acima. Em seguida, salve e feche o arquivo functions. R. Se você quiser fazer qualquer alteração no arquivo R criado na etapa 1, você terá que recarregá-la usando o botão BERT 8220Reload Startup File8221 no menu Add-Ins do Excel 3 8211 No Excel: Crie e salve um arquivo chamado myFile. xslm (Qualquer outro nome é bom). Este é um arquivo habilitado para macros que você salva no diretório de sua escolha. Depois que o arquivo é salvo, feche-o. 4 8211 Abra o arquivo criado acima no editor de UI personalizado: Depois que o arquivo estiver aberto, cole o código abaixo. Você deve ter algo parecido com isso no editor XML: Essencialmente, esse pedaço de código XML cria um menu adicional (RTrader), um novo grupo (Meu Grupo) e um botão definido pelo usuário (Novo Botão) na fita Excel. Depois de feito, abra myFile. xslm no Excel e feche o Editor de UI personalizado. Você deve ver algo como isto. 5 8211 Editor de VBA aberto. Em myFile. xlsm insira um novo módulo. Cole o código abaixo no módulo recém-criado. Isso apaga resultados anteriores na planilha antes de lidar com novos. 6 8211 Clique em Novo Botão. Agora volte para a planilha e no menu do RTrader clique no botão 8220New Button8221. Você deve ver algo como o abaixo aparecendo. O guia acima é uma versão muito básica do que pode ser alcançado usando BERT, mas mostra como combinar o poder de várias ferramentas específicas para construir seu próprio aplicativo personalizado. De minha perspectiva, o interesse de tal abordagem é a capacidade de colar juntos R e Excel, obviamente, mas também para incluir via XML (e lote) pedaços de código de Python, SQL e muito mais. Isso é exatamente o que eu precisava. Finalmente, gostaria de saber se alguém tem alguma experiência com o BERT. Ao testar estratégias de negociação, uma abordagem comum é dividir o conjunto inicial de dados em dados de amostra: a parte dos dados projetada para calibrar O modelo e fora dos dados de amostra: a parte dos dados utilizados para validar a calibração e garantir que o desempenho criado na amostra será refletida no mundo real. Como regra geral, cerca de 70 dos dados iniciais podem ser utilizados para calibração (i. e. na amostra) e 30 para validação (isto é, fora da amostra). Em seguida, uma comparação dos dados de entrada e saída de dados ajuda a decidir se o modelo é suficientemente robusto. Este post pretende ir um passo mais longe e fornece um método estatístico para decidir se os dados fora da amostra está em consonância com o que foi criado na amostra. No gráfico abaixo a área azul representa o desempenho fora da amostra para uma das minhas estratégias. Uma inspeção visual simples revela um bom ajuste entre o dentro e fora do desempenho da amostra, mas que grau de confiança eu tenho nesta Nesta fase não muito e este é o problema. O que é verdadeiramente necessário é uma medida de semelhança entre os conjuntos de dados de entrada e saída. Em termos estatísticos, isto poderia ser traduzido como a probabilidade de que os valores de desempenho dentro e fora da amostra provenham da mesma distribuição. Existe um teste estatístico não-paramétrico que faz exatamente isso: o teste de Kruskall-Wallis. Uma boa definição deste teste pode ser encontrada no R-Tutor 8220A coleção de amostras de dados são independentes se vierem de populações não relacionadas e as amostras não afetam uns aos outros. Utilizando o teste de Kruskal-Wallis. Podemos decidir se as distribuições da população são idênticas sem supor que elas sigam a distribuição normal.8221 O benefício adicional deste teste não está assumindo uma distribuição normal. Existem outros testes da mesma natureza que poderiam caber nessa estrutura. O teste de Mann-Whitney-Wilcoxon ou os testes de Kolmogorov-Smirnov seriam perfeitamente adequados ao quadro descreve aqui no entanto isso está além do escopo deste artigo para discutir os prós e contras de cada um desses testes. Uma boa descrição junto com exemplos de R pode ser encontrada aqui. Aqui o código usado para gerar o gráfico acima e a análise: No exemplo acima, o período de amostra é mais longo do que o período fora da amostra, portanto, eu criei aleatoriamente 1000 subconjuntos dos dados da amostra, cada um deles com o mesmo comprimento que o out Dos dados da amostra. Em seguida, eu testei cada um no subconjunto de amostra contra a saída de dados de amostra e eu gravei os valores de p. Este processo não cria um único valor de p para o teste de Kruskall-Wallis, mas uma distribuição que torna a análise mais robusta. Neste exemplo, a média dos valores de p está bem acima de zero (0,478) indicando que a hipótese nula deve ser aceita: existem fortes evidências de que os dados de entrada e saída da amostra vêm da mesma distribuição. Como de costume o que é apresentado neste post é um exemplo de brinquedo que apenas arranhões a superfície do problema e deve ser adaptado às necessidades individuais. No entanto, penso que propõe uma estrutura estatística interessante e racional para avaliar os resultados da amostra. Este post é inspirado nos seguintes dois artigos: Vigier Alexandre, Chmil Swann (2007), Efeitos de Várias Funções de Otimização no Desempenho de Amostra de Estratégias de Negociação Geneticamente Evoluídas, Previsão de Mercados Financeiros Conferência Vigier Alexandre, Chmil Swann (2010), An Processo de otimização para melhorar inout da consistência da amostra, um caso de mercado de ações, JP Morgan Cazenove Equity Quantitative Conference, Londres Outubro de 2010 13 de dezembro de 2015, 2:03 pm Fazendo investigação quantitativa implica um monte de dados crunching e um precisa de dados limpos e confiáveis ​​para Alcançar este objectivo. O que é realmente necessário é dados limpos que é facilmente acessível (mesmo sem uma conexão à Internet). A maneira mais eficiente de fazer isso para mim foi manter um conjunto de arquivos csv. Obviamente, este processo pode ser tratado de muitas maneiras, mas eu encontrei tempo extra muito eficiente e simples para manter um diretório onde eu armazenar e atualizar arquivos csv. Eu tenho um arquivo csv por instrumento e cada arquivo é nomeado após o instrumento que ele contém. A razão que eu faço assim é dupla: Primeiro, eu don8217t quero baixar (preço) dados do Yahoo, Google etc8230 cada vez que eu quero testar uma nova idéia, mas mais importante uma vez que eu identifiquei e corrigiu um problema, eu don8217t quero ter que Fazê-lo novamente na próxima vez que eu preciso do mesmo instrumento. Simples ainda muito eficiente até agora. O processo é resumido no gráfico abaixo. Em tudo o que segue, eu suponho que os dados vêm do Yahoo. O código terá de ser alterado para os dados do Google, Quandl etc8230 Além disso, eu apresento o processo de atualização dos dados diários de preços. A configuração será diferente para dados de freqüência mais alta e outro tipo de conjunto de dados (ou seja, diferente dos preços). 1 8211 Download de dados iniciais (listOfInstruments. R amp historicalData. R) O arquivo listOfInstruments. R é um arquivo que contém apenas a lista de todos os instrumentos. Se um instrumento não for parte de minha lista (ou seja, nenhum arquivo csv na minha pasta de dados) ou se você fizer isso pela primeira vez você tem que baixar o conjunto de dados históricos iniciais. O exemplo abaixo carrega um conjunto de preços diários de ETFs do Yahoo Finance de volta a janeiro de 2000 e armazena os dados em um arquivo csv. 2 8211 Atualizar dados existentes (updateData. R) O código a seguir é iniciado a partir de arquivos existentes na pasta dedicada e atualiza todos eles um após o outro. Eu costumo executar este processo todos os dias, exceto quando I8217m de férias. Para adicionar um novo instrumento, basta executar o passo 1 acima para este instrumento sozinho. 3 8211 Criar um arquivo em lotes (updateDailyPrices. bat) Outra parte importante do trabalho é a criação de um arquivo em lotes que automatiza o processo de atualização acima (I8217m, um usuário do Windows). Isso evita abrir RRStudio e executar o código de lá. O código abaixo é colocado em um arquivo. bat (o caminho deve ser alterado com a configuração do reader8217s). Observe que eu adicionei um arquivo de saída (updateLog. txt) para rastrear a execução. O processo acima é extremamente simples porque ele só descreve como atualizar dados de preços diários. Eu tenho usado isso por um tempo e tem funcionado muito bem para mim até agora. Para dados mais avançados e / ou freqüências mais altas, as coisas podem ficar muito mais complicadas. Como de costume todos os comentários bem-vindos 23 de março de 2015, 8:55 pm Quando se trata de gerenciar um portfólio de ações versus um benchmark o problema é muito diferente de definir uma estratégia de retorno absoluto. No primeiro um tem que segurar mais estoques do que no mais atrasado onde nenhum estoque em tudo pode ser prendido se não há uma oportunidade boa bastante. A razão para isso é o erro de rastreamento. Isso é definido como o desvio padrão do retorno da carteira menos o retorno do índice de referência. Os estoques menos são mantidos contra um benchmark quanto maior o erro de rastreamento (por exemplo, maior risco). A análise que se segue é amplamente inspirada pelo livro 8220Active Portfolio Management8221 de Grinold amp Kahn. Esta é a bíblia para qualquer pessoa interessada em executar um portfólio contra um benchmark. Eu incentivo fortemente qualquer um com um interesse no tópico para ler o livro do começo ao fim. É muito bem escrito e estabelece as bases da gestão sistemática de carteira ativa (eu não tenho afiliação ao editor ou aos autores). 1 8211 Análise Fatorial Aqui estamos tentando classificar com a maior precisão possível as ações do universo de investimento em uma base de retorno para a frente. Muitas pessoas inventaram muitas ferramentas e inúmeras variantes dessas ferramentas foram desenvolvidas para conseguir isso. Neste post me concentro em duas métricas simples e amplamente utilizadas: Coeficiente de Informação (IC) e Quantiles Return (QR). 1.1 8211 Coeficiente de Informação O horizonte para o retorno a termo tem de ser definido pelo analista e é função do volume de negócios da estratégia e da desintegração alfa (este tem sido objecto de extensa investigação). Obviamente, os CI devem ser tão elevados quanto possível em termos absolutos. Para o leitor afiado, no livro de Grinold amp Kahn uma fórmula que liga a relação de informação (IR) e IC é dada: com amplitude sendo o número de apostas independentes (comércios). Esta fórmula é conhecida como a lei fundamental da gestão activa. O problema é que muitas vezes, definir amplitude com precisão não é tão fácil quanto parece. 1.2 8211 Retorno de Quantiles Para obter uma estimativa mais precisa do poder de previsão de fator, é necessário ir um passo adiante e agrupar os estoques por quantil de valores de fator e então analisar o retorno médio de retorno (ou qualquer outra métrica de tendência central) de cada um desses Quantiles. A utilidade desta ferramenta é simples. Um fator pode ter um IC bom, mas seu poder preditivo pode ser limitado a um pequeno número de ações. Isso não é bom como um gestor de carteira terá de escolher estoques dentro de todo o universo, a fim de atender a sua restrição de erro de rastreamento. Os bons quantiles de retorno são caracterizados por uma relação monótona entre os quantiles individuais e retornos futuros. Todas as ações no índice SampP500 (no momento da escrita). Obviamente, existe um viés de sobrevivência: a lista de ações no índice mudou significativamente entre o início e o final do período de amostragem, porém é bastante boa apenas para fins ilustrativos. O código abaixo carrega os preços das ações individuais no SampP500 entre janeiro de 2005 e hoje (demora um pouco) e transforma os preços brutos em retorno nos últimos 12 meses e no último mês. O primeiro é o nosso fator, este último será usado como a medida de retorno para a frente. Abaixo está o código para calcular o Coeficiente de Informação e Quantiles Retorno. Note que eu usei quintis neste exemplo, mas qualquer outro método de agrupamento (terciles, deciles etc8230) pode ser usado. Ele realmente depende do tamanho da amostra, o que você deseja capturar e wether você quer ter uma visão ampla ou se concentrar em caudas de distribuição. Para estimar retornos dentro de cada quintil, a mediana tem sido usada como estimador de tendência central. Esta medida é muito menos sensível aos valores atípicos do que a média aritmética. E finalmente o código para produzir o Quantiles Retorno gráfico. 3 8211 Como explorar as informações acima No gráfico acima, Q1 é o mais baixo após 12 meses de retorno e Q5 mais alto. Há um aumento quase monotônico no retorno dos quantiles entre Q1 e Q5, o que indica claramente que os estoques que caem em Q5 superam os que caem em Q1 em cerca de 1 por mês. Isso é muito significativo e poderoso para um fator tão simples (não é realmente uma surpresa though8230). Portanto, há maiores chances de vencer o índice por sobreponderar as ações caem no Q5 e subponderar aqueles que caem no primeiro trimestre em relação ao benchmark. Um IC de 0,0206 pode não significar muito em si, mas é significativamente diferente de 0 e indica um bom poder preditivo dos últimos 12 meses de retorno global. Testes de significância formal podem ser avaliados, mas isso está além do escopo deste artigo. 4 8211 Limitações práticas A estrutura acima é excelente para avaliar a qualidade dos fatores de investimento, porém há uma série de limitações práticas que devem ser abordadas para a implementação da vida real: Rebalancing. Na descrição acima, 8282 assumiu que no final de cada mês a carteira é totalmente rebalanceada. Isso significa que todas as ações que caem no primeiro trimestre estão abaixo do peso e todas as ações que caem no Q5 estão acima do peso em relação ao benchmark. Isso nem sempre é possível por razões práticas: alguns estoques podem ser excluídos do universo de investimento, existem restrições sobre o peso da indústria ou do setor, existem restrições sobre o volume de negócios etc 8230 custos de transação. Isso não tem sido levado em conta na análise acima e este é um freio grave para a implementação da vida real. Considerações de volume de negócios são geralmente implementadas na vida real em uma forma de penalidade sobre a qualidade do fator. Coeficiente de transferência. Esta é uma extensão da lei fundamental da gestão ativa e relaxa a suposição do modelo de Grinolds de que os gerentes não enfrentam restrições que os impedem de traduzir seus insights de investimentos diretamente em apostas em carteira. E, finalmente, I8217m espantado com o que pode ser alcançado em menos de 80 linhas de código com R8230 Como de costume todos os comentários bem-vindos 14 de março de 2014, 1:07 pm A pergunta que se deve sempre perguntou himherself quando usando indicadores técnicos é o que seria um objetivo Critérios para selecionar os parâmetros dos indicadores (por exemplo, por que usar um RSI de 14 dias em vez de 15 ou 20 dias). Algoritmos genéticos (GA) são ferramentas bem adaptadas para responder a essa pergunta. Neste post I8217ll mostrar-lhe como configurar o problema em R. Antes de prosseguir o lembrete habitual: O que eu apresento neste post é apenas um exemplo de brinquedo e não um convite para investir. Não é uma estratégia acabada, mas uma idéia de pesquisa que precisa ser mais pesquisada, desenvolvida e adaptada às necessidades individuais. O que são algoritmos genéticos A melhor descrição de GA que eu encontrei vem de Cybernatic Trading um livro de Murray A. Ruggiero. 8220 Algoritmos genéticos foram inventados por John Holland em meados de 1970 para resolver problemas de otimização dura. Este método utiliza a seleção natural, sobrevivência do fittest8221. O processo geral segue as etapas abaixo: Codificar o problema em cromossomos Usando a codificação, desenvolver uma função de aptidão para uso na avaliação de cada valor do cromossomo8217s na resolução de um determinado problema Inicializar uma população de cromossomos Avaliar cada cromossomo na população Criar novos cromossomos por acasalamento de dois Cromossomos. Isso é feito muting e recombinando dois pais para formar duas crianças (os pais são selecionados aleatoriamente, mas tendenciosa por sua aptidão) Avaliar o novo cromossomo Excluir um membro da população que é menos apto do que o novo cromossomo e inserir o novo cromossomo na população . Se o critério de paragem é atingido (número máximo de gerações, os critérios de aptidão são bons o suficiente), em seguida, retornar o melhor cromossomo ou vá para a etapa 4 A partir de uma perspectiva de negociação GA são muito úteis porque são bons em lidar com problemas altamente não-lineares. No entanto, eles apresentam algumas características desagradáveis ​​que vale a pena mencionar: Over fitting: Este é o principal problema e it8217s até o analista para configurar o problema de uma forma que minimize esse risco. Tempo de computação. Se o problema não é definido corretamente, pode ser muito longo para chegar a uma solução decente ea complexidade aumenta exponencialmente com o número de variáveis. Daí a necessidade de selecionar cuidadosamente os parâmetros. Há vários pacotes de R que tratam de GA, eu escolhi usar o mais comum: rgenoud Os preços de fechamento diários para a maioria de ETFs líquidos de finanças de Yahoo que vão para trás a janeiro 2000. O em período da amostra vai de janeiro 2000 a dezembro 2010. O Fora de sample period starts on January 2011. The logic is as following: the fitness function is optimised over the in sample period to obtain a set of optimal parameters for the selected technical indicators. The performance of those indicators is then evaluated in the out of sample period. But before doing so the technical indicators have to be selected. The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: moving averages cross over and RSI. This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes . The other key element is the fitness function . We might want to use something like: maximum return or Sharpe ratio or minimum average Drawdown. In what follows, I chose to maximise the Sharpe ratio. The R implementation is a set of 3 functions: fitnessFunction . defines the fitness function (e. g. maximum Sharpe ratio) to be used within the GA engine tradingStatistics . summary of trading statistics for the in and out of sample periods for comparison purposes genoud . the GA engine from the rgenoud package The genoud function is rather complex but I8217m not going to explain what each parameter means as I want to keep this post short (and the documentation is really good). In the table below I present for each instrument the optimal parameters (RSI look-back period, RSI threshold, Short Term Moving Average, and Long Term Moving Average) along with the in and out of sample trading statistics. Before commenting the above results, I want to explain a few important points. To match the logic defined above, I bounded the parameters to make sure the look-back period for the long term moving average is always longer that the shorter moving average. I also constrained the optimiser to choose only the solutions with more than 50 trades in the in sample period (e. g, statistical significance). Overall the out of sample results are far from impressive. The returns are low even if the number of trades is small to make the outcome really significant. However there8217s a significant loss of efficiency between in and out of sample period for Japan (EWJ) which very likely means over fitting. This post is intended to give the reader the tools to properly use GA in a quantitative trading framework. Once again, It8217s just an example that needs to be further refined. A few potential improvement to explore would be: fitness function . maximising the Sharpe ratio is very simplistic. A 8220smarter8221 function would certainly improve the out of sample trading statistics pattern . we try to capture a very straightforward pattern. A more in depth pattern research is definitely needed. optimisation . there are many ways to improve the way the optimisation is conducted. This would improve both the computation speed and the rationality of the results. The code used in this post is available on a Gist repository . As usual any comments welcome February 28, 2014, 3:52 pm There is an enormous body of literature both academic and empirical about market forecasting. Most of the time it mixes two market features: Magnitude and Direction. In this article I want to focus on identifying the market direction only. The goal I set myself, is to identify market conditions when the odds are significantly biased toward an up or a down market. This post gives an example of how CART (Classification And Regression Trees) can be used in this context. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. Its not a finished strategy either but a research idea that needs to be further researched, developed and tailored to individual needs. 1 8211 What is CART and why using it From statistics, CART are a set of techniques for classification and prediction. The technique is aimed at producing rules that predict the value of an outcome (target) variable from known values of predictor (explanatory) variables. There are many different implementations but they are all sharing a general characteristic and thats what Im interested in. From Wikipedia, Algorithms for constructing decision trees usually work top-down, by choosing a variable at each step that best splits the set of items. Different algorithms use different metrics for measuring 8220best8221. These generally measure the homogeneity of the target variable within the subsets. These metrics are applied to each candidate subset, and the resulting values are combined (e. g. averaged) to provide a measure of the quality of the split. CART methodology exhibits some characteristics that are very well suited for market analysis: Non parametric . CART can handle any type of statistical distributions Non linear . CART can handle a large spectrum of dependency between variables (e. g. not limited to linear relationships) Robust to outliers There are various R packages dealing with Recursive Partitioning, I use here rpart for trees estimation and rpart. plot for trees drawing. 2 8211 Data amp Experiment Design Daily OHLC prices for most liquid ETFs from January 2000 to December 2013 extracted from Google finance. The in sample period goes from January 2000 to December 2010 the rest of the dataset is the out of sample period. Before running any type of analysis the dataset has to be prepared for the task. The target variable is the ETF weekly forward return defined as a two states of the world outcome (UP or DOWN). If weekly forward return gt 0 then the market in the UP state, DOWN state otherwise The explanatory variables are a set of technical indicators derived from the initial daily OHLC dataset. Each indicator represents a well-documented market behavior. In order to reduce the noise in the data and to try to identify robust relationships, each independent variable is considered to have a binary outcome. Volatility (VAR1) . High volatility is usually associated with a down market and low volatility with an up market. Volatility is defined as the 20 days raw ATR (Average True Range) spread to its moving average (MA). If raw ATR gt MA then VAR1 1, else VAR1 -1. Short term momentum (VAR2) . The equity market exhibits short term momentum behavior captured here by a 5 days simple moving averages (SMA). If Price gt SMA then VAR2 1 else VAR2 -1 Long term momentum (VAR3) . The equity market exhibits long term momentum behavior captured here by a 50 days simple moving averages (LMA). If Price gt LMA then VAR3 1 else VAR3 -1 Short term reversal (VAR4) . This is captured by the CRTDR which stands for Close Relative To Daily Range and calculated as following: . If CRTDR gt 0.5, then VAR4 1 else VAR4 -1 Autocorrelation regime (VAR5) . The equity market tends to go through periods of negative and positive autocorrelation regimes. If returns autocorrelation over the last 5 days gt 0 then VAR5 1 else VAR5 -1 I put below a tree example with some explanations In the tree above, the path to reach node 4 is: VAR3 gt0 (Long Term Momentum gt 0) and VAR4 gt 0 (CRTDR gt 0). The red rectangle indicates this is a DOWN leaf (e. g. terminal node) with a probability of 58 (1 8211 0.42). In market terms this means that if Long Term Momentum is Up and CRTDR is gt 0.5 then the probability of a positive return next week is 42 based on the in sample sample data. 18 indicates the proportion of the data set that falls into that terminal node (e. g. leaf). There are many ways to use the above approach, I chose to estimate and combine all possible trees. From the in sample data, I collect all leaves from all possible trees and I gather them into a matrix. This is the 8220rules matrix8221 giving the probability of next week beeing UP or DOWN. I apply the rules in the above matrix to the out of sample data (Jan 2011 8211 Dec 2013) and I compare the results to the real outcome. The problem with this approach is that a single point (week) can fall into several rules and even belong to UP and DOWN rules simultaneously. Therefore I apply a voting scheme . For a given week I sum up all the rules that apply to that week giving a 1 for an UP rule and -1 for a DOWN rule. If the sum is greater than 0 the week is classified as UP, if the sum is negative it8217s a DOWN week and if the sum is equal to 0 there will be no position taken that week (return 0) The above methodology is applied to a set of very liquid ETFs. I plot below the out of sample equity curves along with the buy and hold strategy over the same period. Initial results seem encouraging even if the quality of the outcome varies greatly by instrument. However there is a huge room for improvement. I put below some directions for further analysis Path optimality . The algorithm used here for defining the trees is optimal at each split but it doesn8217t guarantee the optimality of the path. Adding a metric to measure the optimality of the path would certainly improve the above results. Other variables . I chose the explanatory variables solely based on experience. It8217s very likely that this choice is neither good nor optimal. Backtest methodology . I used a simple In and Out of sample methodology. In a more formal backtest I would rather use a rolling or expanding window of in and out sample sub-periods (e. g. walk forward analysis) As usual, any comments welcomeCategory Archives: Trading Strategies 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 dont 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 don8217t 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. Algorithmic Trading Strategies All the algorithmic trading strategies that are being used today can be classified broadly into the following categories: MomentumTrend 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 thats why this is the best use of algorithmic trading strategies, as an automated machine can track such changes instantly. For instance, if Apple8217s 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: Lets 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 amp 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 amp 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 QuantInstis 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 dont 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 markets 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 theyre usually static, i. e. they dont 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 stylepatterns to create a new of evolved traders. This process repeats multiple times and a digital trader that can fully operate on its own is created. This process repeats multiple times and a digital trader that can fully operate on its own is created. This process repeats multiple times and a digital trader that can fully operate on its 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 QuantInstis 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 its 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 buysell signals in your strategy. For pair trading check for mean reversion calculate the z-score for the spread of the pair and generate buysell signals when you expect it to revert to mean. Decide on the Stop Loss and Profit Taking conditions. Stop Loss 8211 A stop-loss order limits an investors 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 8211 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 8211 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. With great strategy, comes greater scrutiny, A Great Thinker once quoted. Fine, I just ripped off Ben Parkers 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 strategys performance and risk. Some important metricsratios 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 8211 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 . Thats 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 . This article is the final project submitted by the author as a part of his coursework in Executive Programme in Algorithmic Trading (EPAT) at QuantInsti. Do check our Projects page and have a look at what our students are building. Marco has spent his career as a trader and portfolio manager, with a particular focus in equity and derivatives markets. He specializes in quantitative finance and algorithmic trading and currently serves as head of the Quantitative Trading Desk and Vice-president of Argentina Valores S. A. Marco is also Co-Founder and CEO of Quanticko Trading SA, a firm devoted to the development of high frequency trading strategies and trading software. Marco holds a BS in Economics and an MSc in Finance from the University of San Andrs. Introduction One of my favorite classes during EPAT was the one on statistical arbitrage. so the pair trading strategy seemed a nice idea for me. My strategy triggers new orders when the pair ratio of the prices of the stocks diverge from the mean. But in order to work, we first have to test for the pair to be cointegrated. If the pair ratio is cointegrated, the ratio is mean-reverting and the greater the dispersion from its mean, the higher the probability of a reversal, which makes the trade more attractive. I chose the following pair of stocks: The idea is the following: If we find two stocks that are correlated (they correspond to the same sector), and the pair ratio diverges from a certain threshold, we short the stock that is expensive and buy the one that is cheap. Once they converge to the mean, we close the positions and profit from the reversal. In this post we see how to compute historical volatility in python, and the different measures of risk-adjusted return based on it. We have also provided the python codes for these measures which might be of help to the readers. Introduction Volatility measures the dispersion of returns for a given security. Volatility can be measured by the standard deviation of returns for a security over a chosen period of time. Historic volatility is derived from time series of past price data, whereas, an implied volatility is derived using the market price of a traded derivative instrument like an options contract. Sentiment Analysis. also known as opinion mining, is the process of computationally identifying and categorizing opinions expressed in a piece of text, especially in order to determine whether the writers attitude towards a particular topic, product, etc. is positive, negative, or neutral. The analysis finds significant prominence in social media, stock markets, law, policy making, sociology and even customer service. Machines are faster at responding to events than humans and can process much vaster amount of information without any fatigue. In more volatile markets, people tend to react less strongly to positive news and react more strongly to negative news. Of course, there are situations where sentiment analysis, or sometimes also called News Analytics, works well for a position, while in other cases it fails. The following slide show is a summary of favourable and profitable outcomes of sentiment analysis in trading. Next Steps: Now that you have understood a little about how sentiment analysis works, you would also want to know the pitfalls. For this and other such questions, we have an upcoming webinar on 8220Quantitative Strategies using Sentiment Analysis8221 by Rajib Ranjan Borah. The webinar will give a brief overview of how sentiment analysis works and some historical perspective along with suggestions on how to develop trading strategies. Register for the webinar on this link. Python has emerged as one of the most popular language to code in Algorithmic Trading, owing to its ease of installation, free usage, easy structure, and availability of variety of modules. Globally, Algo Traders and researchers in Quant are extensively using Python for prototyping, backtesting, building their proprietary risk and order management system as well as in optimisation of testing modules. This blog post highlights some of the key steps involved in Algorithmic Trading using Python as the programming language. The screenshots are taken from the webinar of Dr. Yves Hilpisch. in collaboration with QuantInsti. Dr. Hilpisch is world-renowned authority in the world of Python and is the founder of Python Quants GmbH, with several books on the subject under his belt. He also serves as a faculty at QuantInsti, one of Asias pioneer education training firm in Algorithmic Trading. All examples shown are based on the platform and API of oanda. Background information about Python and the libraries used can be found in the OReilly book Hilpisch, Yves (2014): Python for Finance Analyze Big Financial Data. The post is divided in two parts. The current post highlights the basics of connecting with the Oanda platform using python and backtesting the trading strategies. The next post will cover working with streaming data as well as automated trading in real-time. High Frequency Trading (HFT) involves the concept of 8220Order Types8221, which signals a trader to enter or exit a position. According to Reuters, Order types can reach an estimated 2,000 variations as a fully electronic market and more than 50 trading venues have multiplied the possibilities of how, when and with whom to trade. Clearly, the rules of the game are redefined by the Order Types and their correct implementation in the marketplace. Amidst a long list, we touch upon some of the popular ones, frequently used by HFT practitioners. The following Infographic shows 4 HFT Order Types, and examples when a buy or sell order is placed. Introduction Traders in the derivative market often exercise one of the following: Call option or Put Option . Call option is a financial contract between a buyer and seller, whereby the buyer has the right, but not the obligation, to buy an agreed quantity of a financial instrument from the seller of the option at a certain time for a certain price (the strike price). The Put Option serves the opposite. In a Covered Call , the seller of the call options owns the corresponding amount of the underlying instrument. A Covered Call is an income generating option strategy which involves two legs: Buying a stock Selling an Out of the money (OTM) call option If the call is sold simultaneously along with the stock purchase, the strategy is referred to as a buy-write strategy. In a Covered Call, the trader holds a neutral to a bullish outlook. Covered Call is a net debit transaction because you pay for the stock and receive a small premium for the call option sold. The idea of this blog post is to elaborate on the covered call strategy by an example and to plot its payoff using Python. The post also highlights 8220Calendar Call8221 as it is a modification of the Covered Call strategy. To measure the performance of a trading strategy, annualized returns are often a common metric. However comparing two strategies based on annualised returns may not always be a logical way due to several reasons. Some strategies might be directional, some market neutral and some might be leveraged which makes annualized return alone a futile measure of performance measurement. Also, even if two strategies have comparable annual returns, the risk is still an important aspect that needs to be measured. A strategy with high annual returns is not necessarily very attractive if it has a high-risk component we generally prefer better risk-adjusted returns over just better returns. Sharpe Ratio takes care of risk assessment and the problem related to the comparison of strategies. Sharpe ratio is a measure for calculating the risk-adjusted return. It is the ratio of the excess expected return of an investment (over risk-free rate) per unit of volatility or standard deviation. (morehellip)

No comments:

Post a Comment