Sunday, 21 May 2017

Quantitativo Negociação Estratégias Blog



Estratégias de Quant - São eles para você As estratégias de investimento quantitativas evoluíram em ferramentas muito complexas com o advento de computadores modernos, mas as raizes das estratégias vão para trás sobre 70 anos. Eles são geralmente executados por equipes altamente educadas e usar modelos proprietários para aumentar sua capacidade de bater o mercado. Há mesmo off-the-shelf programas que são plug-and-play para aqueles que procuram simplicidade. Quant modelos sempre funcionam bem quando volta testado, mas suas aplicações reais e taxa de sucesso são discutíveis. Enquanto eles parecem funcionar bem em mercados de touro. Quando os mercados se esgotam, estratégias quantirais estão sujeitas aos mesmos riscos que qualquer outra estratégia. A História Um dos fundadores do estudo da teoria quantitativa aplicada às finanças foi Robert Merton. Você só pode imaginar o quão difícil e demorado o processo foi antes do uso de computadores. Outras teorias em finanças também evoluíram a partir de alguns dos primeiros estudos quantitativos, incluindo a base da diversificação de portfólio baseada na moderna teoria da carteira. A utilização de financiamento e cálculos quantitativos levou a muitas outras ferramentas comuns, incluindo uma das mais famosas fórmulas de precificação Black-Scholes, que não só ajuda os investidores a optarem por preços e a desenvolver estratégias, como também ajuda a manter os mercados checados com liquidez. Quando aplicado diretamente ao gerenciamento de portfólio. O objetivo é como qualquer outra estratégia de investimento. Para adicionar valor, alfa ou excesso retorna. Quants, como os desenvolvedores são chamados, compõem modelos matemáticos complexos para detectar oportunidades de investimento. Existem tantos modelos lá fora como quants que desenvolvê-los, e todos afirmam ser o melhor. Uma das estratégias de investimento mais vantajosas é que o modelo, e, em última instância, o computador, faz a decisão real de compra, não um ser humano. Isso tende a remover qualquer resposta emocional que uma pessoa pode experimentar ao comprar ou vender investimentos. As estratégias de Quant são agora aceitas na comunidade de investimento e geridas por fundos mútuos, hedge funds e investidores institucionais. Eles normalmente vão pelo nome alfa geradores. Ou alfa gens. Atrás da cortina Assim como em O Mágico de Oz, alguém está por trás da cortina que conduz o processo. Como com qualquer modelo, seu somente tão bom quanto o ser humano que desenvolve o programa. Embora não exista um requisito específico para se tornar um quant, a maioria das empresas que executam modelos quant combinam as habilidades de analistas de investimento, estatísticos e programadores que codificam o processo para os computadores. Devido à natureza complexa dos modelos matemáticos e estatísticos, é comum ver credenciais como pós-graduação e doutorado em finanças, economia, matemática e engenharia. Historicamente, esses membros da equipe trabalhavam nos back offices. Mas como os modelos de quant tornou-se mais comum, o back office está se movendo para o front office. Benefícios de estratégias Quant Enquanto a taxa de sucesso global é discutível, a razão de algumas estratégias quant trabalho é que eles são baseados na disciplina. Se o modelo estiver certo, a disciplina mantém a estratégia trabalhando com computadores de velocidade relâmpago para explorar ineficiências nos mercados com base em dados quantitativos. Os modelos em si podem ser baseados em tão pouco como algumas razões como PE. Dívida para capital próprio e crescimento de lucros, ou usar milhares de insumos trabalhando juntos ao mesmo tempo. Estratégias bem sucedidas podem pegar em tendências em seus estágios iniciais como os computadores constantemente executar cenários para localizar ineficiências antes que outros fazem. Os modelos são capazes de analisar um grupo muito grande de investimentos simultaneamente, onde o analista tradicional pode estar olhando apenas alguns de cada vez. O processo de triagem pode classificar o universo por níveis de grau como 1-5 ou A-F dependendo do modelo. Isso torna o processo de negociação real muito simples, investindo nos investimentos altamente cotados e vendendo os mais baixos. Modelos Quant também abrem variações de estratégias como longo, curto e longshort. Fundos quant bem sucedidos mantêm um olho afiado no controle de risco devido à natureza de seus modelos. A maioria das estratégias começa com um universo ou benchmark e usa ponderações setoriais e industriais em seus modelos. Isso permite que os fundos controlem a diversificação até certo ponto sem comprometer o próprio modelo. Os fundos Quant funcionam normalmente em uma base de custo mais baixo porque eles não precisam de tantos analistas tradicionais e gerentes de portfólio para executá-los. Desvantagens de estratégias Quant Há razões por que tantos investidores não abraçar totalmente o conceito de deixar uma caixa preta executar seus investimentos. Para todos os fundos quant bem sucedidos lá fora, assim como muitos parecem ser malsucedido. Infelizmente para a reputação dos quants, quando falham, falham grande. Long-Term Capital Management foi um dos mais famosos fundos de hedge, já que foi administrado por alguns dos mais respeitados líderes acadêmicos e dois economistas premiados com o Nobel Memorial, Myron S. Scholes e Robert C. Merton. Durante os anos 90, sua equipe gerou retornos acima da média e atraiu capital de todos os tipos de investidores. Eles eram famosos por não apenas explorar as ineficiências, mas usando o acesso fácil ao capital para criar enormes apostas apalancadas nas direções do mercado. A natureza disciplinada de sua estratégia realmente criou a fraqueza que levou ao seu colapso. Long-Term Capital Management foi liquidada e dissolvida no início de 2000. Seus modelos não incluem a possibilidade de que o governo russo poderia inadimplência em parte de sua própria dívida. Esse evento desencadeou eventos e uma reação em cadeia ampliada pelo caos causado pela alavancagem. A LTCM estava tão envolvida com outras operações de investimento que seu colapso afetou os mercados mundiais, desencadeando eventos dramáticos. A longo prazo, o Federal Reserve interveio para ajudar, e outros bancos e fundos de investimento apoiou LTCM para evitar quaisquer danos adicionais. Esta é uma das razões pelas quais os fundos podem fracassar, pois são baseados em eventos históricos que podem não incluir eventos futuros. Enquanto uma equipe de quant forte vai constantemente adicionando novos aspectos aos modelos para prever eventos futuros, é impossível prever o futuro cada vez. Quant fundos também podem se tornar oprimido quando a economia e os mercados estão experimentando maior do que a volatilidade média. Os sinais de compra e venda podem vir tão rapidamente que a alta rotatividade pode criar comissões elevadas e eventos tributáveis. Quant fundos também podem representar um perigo quando eles são comercializados como à prova de urso ou são baseados em estratégias de curto. Previsões de recessão. Usando derivativos e combinando alavancagem pode ser perigoso. Uma vez errada pode levar a implosões, que muitas vezes fazem a notícia. O Bottom Line As estratégias de investimento quantitativo evoluíram de caixas pretas de back office para ferramentas de investimento mainstream. Eles são projetados para utilizar as melhores mentes do negócio e os computadores mais rápidos tanto para explorar as ineficiências e alavancar uso para fazer apostas no mercado. Eles podem ser muito bem sucedidos se os modelos têm incluído todas as entradas direito e são ágeis o suficiente para prever eventos anormais do mercado. Por outro lado, enquanto os fundos quant estão rigorosamente testados até que funcionam, a sua fraqueza é que eles dependem de dados históricos para o seu sucesso. Embora o estilo de estilo de investimento tem seu lugar no mercado, é importante estar ciente de suas deficiências e riscos. Ser coerente com as estratégias de diversificação. É uma boa idéia para tratar estratégias quant como um estilo de investimento e combiná-lo com estratégias tradicionais para alcançar a diversificação adequada. Uma teoria econômica da despesa total na economia e seus efeitos no produto e na inflação. A economia keynesiana foi desenvolvida. A detenção de um activo numa carteira. Um investimento de carteira é feito com a expectativa de ganhar um retorno sobre ele. Este. Um índice desenvolvido por Jack Treynor que mede ganhos obtidos em excesso do que poderia ter sido obtido em um risco. A recompra de ações em circulação (recompra) por uma empresa para reduzir o número de ações no mercado. Empresas. Um reembolso de imposto é um reembolso sobre os impostos pagos a um indivíduo ou agregado familiar quando a responsabilidade fiscal real é inferior ao montante. O valor monetário de todos os produtos acabados e serviços produzidos dentro das fronteiras de um país em um período de tempo específico. Negociação quantitativa Muito tem sido escrito sobre a estratégia de Derivação do Anúncio Pós-Ganhos (PEAD) (veja, por exemplo, o meu livro), mas menos Foi escrito sobre as estratégias de anúncio pré-anúncio. Isso mudou recentemente com a publicação de dois documentos. Assim como no caso do PEAD, essas estratégias de pré-anúncio não fazem uso de números reais de lucros nem mesmo de estimativas. Eles são baseados inteiramente em datas de anúncio (esperado ou real) e talvez recente movimento de preços. O primeiro, por So e Wang 2014, sugere várias estratégias de reversão simples para ações dos EUA que entram em posições no mercado próximo um pouco antes de um anúncio esperado. Aqui está a minha paráfrase de uma dessas estratégias: 1) Suponha que t é a data de anúncio de ganhos esperados para uma ação no índice Russell 3000. 2) Calcule o retorno do pré-anúncio do dia t-4 para t-2 (contando apenas dias de negociação). 3) Subtrair um retorno de índice de mercado sobre o mesmo período de lookback do retorno de pré-anúncio, e chamar este PAR de retorno ajustado pelo mercado. 4) Escolha as 18 ações com o melhor PAR e curto-los (com dólares iguais) no fechamento do mercado de t-1, liquidar no fechamento do mercado de t1. Escolha os 18 estoques com o pior PAR, e faça o oposto. Cubra qualquer exposição líquida com um ETF de mercado ou futuro. Eu backtested esta estratégia usando Wall Street Horizon (WSH) s dados esperados rendimentos datas, aplicando-o às ações no Russell 3000 índice, e hedging com IWV. Eu tenho um CAGR de 9,1 e uma proporção de Sharpe de 1 a partir de 20110803-20160930. A curva de eqüidade é exibida abaixo. Observe que os dados WSHs foram usados ​​em vez dos dados de lucro do Yahoo Finance, Compustat ou mesmo do IBES da Thomson Reuters, porque apenas os dados do WSHs são ponto-a-tempo. WSH capturou a data esperada do anúncio dos lucros no dia antes do anúncio, apenas como nós teríamos se nós vivêssemos negociar. Não usamos a data do anúncio real como capturada na maioria das outras fontes de dados porque não poderíamos ter certeza se uma empresa alterou sua data de anúncio esperada na mesma data. A data do anúncio real só pode ser conhecida com certeza após o fato, e, portanto, não é ponto-in-time. Se tivéssemos de executar o mesmo backtest usando os dados de ganhos históricos do Yahoo Finances, o CAGR teria caído para 6,8, ea relação de Sharpe caiu para 0,8. A noção de que as empresas mudam suas datas de anúncio esperadas nos leva à segunda estratégia, criada por Ekaterina Kramarenko da Deltixs Quantitative Research Team. Em seu artigo Uma Estratégia de Negociação Automatizada Usando Movimentos de Data de Resultados de Wall Street Horizon, ela descreve a seguinte estratégia que explícitamente faz uso de tais mudanças como um sinal de negociação: 1) No fechamento do mercado antes do anúncio de lucro esperado entre o fechamento atual e Os próximos dias abertos, computa deltaD que é a última mudança da data esperada anúncio para o próximo anúncio, medido em dias de calendário. DeltaD gt 0 se a empresa mudou a data do anúncio mais tarde, e deltaD lt 0 se a empresa mudou a data de anúncio mais cedo. 2) Além disso, no mesmo mercado próximo, calcula deltaU que é o número de dias de calendário desde a última mudança da data de anúncio esperada. 3) Se deltaD lt 0 e deltaU lt 45, comprar o estoque no fechamento do mercado e liquidar no dia seguinte mercado aberto. Se deltaD gt 0 e deltaU gt 45, faça o contrário. A intuição por trás desta estratégia é que se uma empresa move uma data esperada anúncio mais cedo, especialmente se isso acontece perto da data prevista, que é uma indicação de boas notícias, e vice-versa. Kramarenko encontrou um CAGR de 14,95 e um índice de Sharpe de 2,08, aplicando esta estratégia às ações SPX de 200613 - 201592. Para reproduzir esse resultado, é preciso garantir que a alocação de capital se baseie na seguinte fórmula: suponha que o total O poder de compra é M, e o número de sinais de negociação no mercado próximo é n, então o tamanho de negociação por ação é M5 se n lt 5, e é Mn se n gt 5. Eu backtested esta estratégia de 201183-2016930 em um fixo SPX universo em 201175, e obteve CAGR17,6 e Sharpe rácio de 0,6. Backtesting isto no Russell 3000 índice universo de estoques produziu melhores resultados, com CAGR17 e Sharpe ratio1.9. Aqui, eu ajustar o tamanho de negociação por ação para M30 se n lt30 e para Mn se n gt 30, dado que o número total de ações em Russell 3000 é cerca de 6 vezes maior do que o SPX. A curva de equidade é exibida abaixo: Curiosamente, uma versão neutra do mercado dessa estratégia (usando a IWV para proteger qualquer exposição líquida) não melhora a relação Sharpe, mas diminui significativamente o CAGR. Reconhecimento. Agradeço a Michael Raines no Wall Street Horizon por fornecer o histórico ponto-in-time esperado ganhando datas dados para esta pesquisa. Além disso, eu agradeço Stuart Farr e Ekaterina Kramarenko em Deltix para me fornecer uma cópia de seu papel e explicando-me as nuances de sua estratégia. Minha Próxima Oficina 14 e 21 de Janeiro: Opções Algorítmicas Estratégias Este curso on-line é diferente da maioria das outras oficinas de opções oferecidas em outros lugares. Abrangerá backtesting estratégias de opção intraday e estratégias de opção de carteira. Eu escrevi em um artigo anterior sobre por que devemos backtest mesmo fim-de-dia (diariamente) estratégias com intraday cotação dados. Caso contrário, o desempenho de tais estratégias pode ser inflacionado. Aqui está outro exemplo brilhante que me deparei recentemente. Considere o futuro do petróleo ETF USO e seu gêmeo do mal, o futuro inverso do petróleo ETF DNO. Em teoria, se USO tem um retorno diário de x, DNO terá um retorno diário de - x. Na prática, se traçarmos os retornos diários da DNO em relação à USO de 2010927-201699, usando os dados de fim de dia consolidados habituais que você pode encontrar no Yahoo Finance ou em qualquer outro fornecedor, vemos que embora a inclinação seja realmente -1 (para dentro de um erro padrão de 0,004), há muitos dias com desvio significativo da linha reta. O trader em nós vai pensar imediatamente oportunidades de arbitragem De fato, se backtest uma estratégia de reversão simples sobre este par - basta comprar igual montante em dólar de USO e DNO quando a soma de seus retornos diários é inferior a 40 bps no fechamento do mercado, mantenha Um dia e vice-versa - vamos encontrar uma estratégia com uma taxa de Sharpe decente de 1, mesmo depois de deduzir 5 bps por lado como custos de transação. Aqui está a curva de equidade: Parece razoável, não é No entanto, se backtest esta estratégia novamente com dados BBO no mercado próximo, tendo o cuidado de subtrair metade do spread bid-ask como custo de transação, encontramos esta curva de equidade: Podemos ver Que o problema não é só que perdemos dinheiro em praticamente todos os negócios, mas que raramente há comércio desencadeado. Quando os dados diários do EOD sugerem que um comércio deve ser desencadeado, os dados BBO de 1 minuto mostram que de fato não houve desvio em relação à média. (A propósito, os retornos acima foram calculados antes mesmo de deduzir os custos de empréstimos de ocasionalmente shorting estes ETFs. A taxa de desconto para USO é de cerca de 1 por ano em Interactive Brokers, mas um íngreme 5.6 para DNO.) Caso você acha isso Problema é peculiar a USO vs DNO, você pode tentar TBT vs UBT também. Aliás, acabamos de verificar uma regra de ouro dos mercados financeiros: aparente desvio do mercado eficiente é permitido quando ninguém pode rentável comércio na oportunidade de arbitragem. Nota: de acordo com a etf, O emissor da DNO suspendeu temporariamente as criações para este fundo a partir de 22 de março de 2016 enquanto aguarda a apresentação de nova documentação com a SEC. Esta ação poderia criar prémios anormais ou excessivos8212 um aumento do preço de mercado do fundo em relação ao seu justo valor. Os resgates não são afetados. Comércio com cuidado verificar iNAV vs preço. Para uma explicação da criação de unidades de ETF, veja meu artigo Coisas que você não quer saber sobre ETFs e ETNs. Atualização da indústria Quantiacs recentemente registrado como um CTA e opera um mercado para negociação algoritmos que qualquer pessoa pode contribuir. Eles também publicaram um blog educacional para os backtesters do Python e Matlab: quantiacsBlogIntro-to-Algorithmic-Trading-with-Heikin-Ashi. aspx Eu vou moderar uma discussão em painel sobre como os fundos podem alavancar fontes de dados não tradicionais para impulsionar os retornos de investimento Quant World Canadá em Toronto, 10 de novembro de 2016. Próximos Workshops 22 e 29 de outubro, Sábados, Quantitative Momentum Strategies workshops on-line. Momentum estratégias são para aqueles que querem se beneficiar de cauda eventos. Vou discutir as razões fundamentais para a existência de impulso em vários mercados, bem como estratégias específicas momento que ocupam posições de horas para dias. Um diretor sênior em um grande banco me escreveu: 8230thank você novamente para o Momentum Strategies curso esta semana . Foi muito benéfico. Eu encontrei suas explicações dos conceitos muito claros e os exemplos bem desenvolvidos. Eu gosto da abordagem rigorosa que você toma para a avaliação da estratégia.8221 Sexta-feira, 17 de junho de 2016 Todo mundo adora trocar ou investir em ETPs. ETP é o acrônimo de produtos negociados em bolsa, que incluem tanto fundos negociados em bolsa (ETF) como notas negociadas em bolsa (ETN). Parecem simples, transparentes, fáceis de entender. Mas há algumas sutilezas que você pode não saber sobre. 1) O ETN mais popular é VXX, o índice de volatilidade ETF. Diferentemente do ETF, o ETN é na verdade uma obrigação não garantida emitida pelo emissor. Isso significa que o preço do ETN pode não apenas depender dos ativos subjacentes ou índice. Poderia potencialmente depender da credibilidade do emitente. Agora, o VXX é emitido pelo Barclays. Você pode pensar que Barclays é um grande banco, Too Big To Fail, e você pode estar certo. No entanto, ninguém promete que sua classificação de crédito nunca será rebaixada. Negociação do VX futuro, no entanto, não tem esse problema. 2) O emitente ETP, juntamente com os Participantes Autorizados (os criadores de mercado que podem pedir ao emitente a emissão de mais acções da ETP ou resgatar tais acções para os activos ou numerário subjacentes) devem manter o valor de mercado total das acções da ETP Acompanhando de perto o NAV dos activos subjacentes. No entanto, houve um exemplo notável quando o emissor deliberadamente não fazê-lo, resultando em grandes perdas para alguns investidores. Foi quando o emissor da TVIX, o ETN alavancado que rastreia 2 vezes o retorno diário da VXX, parou toda a criação de novas ações TVIX temporariamente em 22 de fevereiro de 2012 (veja o artigo sobre como investir201510como-não-tvix). Esse emissor é o Credit Suisse, que pode ter descoberto que os custos de transação de reequilíbrio deste ETN altamente volátil estavam se tornando muito altos. Por causa desta paralisação, TVIX se transformou em um fundo fechado (temporariamente), e seu NAV divergiu significativamente de seu valor de mercado. A TVIX estava negociando com um ágio de 90% em relação ao índice subjacente. Em outras palavras, os investidores que compraram TVIX no mercado de ações até o final de março estavam pagando mais 90 do que teriam se fossem capazes de comprar o índice VIX. Logo depois disso, o Credit Suisse anunciou que retomaria a criação de ações da TVIX. O preço de mercado de TVIX caiu imediatamente para seu NAV por a parte, causando perdas enormes para aqueles investors que compraram imediatamente antes da retomada. 3) Você pode estar familiarizado com o fato de que um ETF alavancado é suposto rastrear apenas vezes os retornos diários do índice subjacente, e não o seu retorno a longo prazo. Mas você pode estar menos familiarizado com o fato de que também não é suposto para acompanhar vezes o retorno intraday desse índice (embora na maioria das vezes ele realmente faz, graças a muitos arbitrageurs.) Caso em questão: durante o Flash Flash 2010 , Muitos ETFs com alavancas inversas experimentaram uma queda no preço quando o mercado estava caindo para baixo. Como ETFs inversa, muitos investidores pensaram que eles são supostos a subir de preço e agir como hedge contra o mercado diminui. Por exemplo, esta carta de comentários à SEC indicou que o DOG, o ETF inverso que rastreia o índice -1x Dow 30, desceu mais de 60 do seu valor no início (2:40 pm ET) do Flash Crash. Isso ocorre porque vários criadores de mercado, incluindo os Participantes Autorizados para DOG, não estavam fazendo mercados naquele momento. Mas um ponto igualmente importante a notar é que no final do dia de negociação, DOG fez retornar 3,2, quase exatamente -1x o retorno do DIA (ETF que rastreia o Dow 30). Assim funcionou como anunciado. Lição aprendida: Não devemos usar ETFs inversos para coberturas intradiárias nem de longo prazo. 4) O VPL (não o NAV por ação) de um ETF não precisa mudar no mesmo valor de mercado dos ativos subjacentes. Por exemplo, a mesma carta de comentários que eu citei acima escreveu que GLD, o ETF ouro, declinou no preço por 24 de 1 de março a 31 de dezembro de 2013, acompanhando a mesma queda de 24 no preço do ouro à vista. Porém, o NAV caiu 52. Por que os Participantes Autorizados resgataram muitas ações da GLD, fazendo com que as ações em circulação da GLD baixassem de 416 milhões para 266 milhões. Isso é um problema? Nem um pouco. Um investidor nessa ETF só se preocupa que ela experimentou o mesmo retorno do ouro spot, e não quanto os ativos da ETF realizada. O autor dessa carta de comentário estranhamente escreveu que os investidores que desejassem participar do mercado de ouro não comprariam o GLD se soubessem que uma queda no preço do ouro poderia resultar em duas vezes mais declínio de ativos subjacentes para o GLD. Isso, creio, é um absurdo. Atualização do Setor Alex Boykov co-desenvolveu o WFAToolbox 8211 Walk-Forward Analysis Toolbox para MATLAB, que automatiza o processo de usar uma janela em movimento para otimizar parâmetros e entrar comércios somente no período fora da amostra. Ele também compilou um aplicativo autônomo do MATLAB que permite que qualquer usuário (tendo MATLAB ou não) para carregar citações em formato csv do Google Finance para importação adicional para outros programas e para trabalhar no Excel. Você pode baixá-lo aqui: wfatoolboxepchan. As técnicas de aprendizado são mais úteis quando alguém nos dá novos indicadores técnicos ou fundamentais e ainda não desenvolvemos a intuição de como usá-los. As técnicas de AI podem sugerir maneiras de incorporá-las em sua estratégia de negociação e acelerar sua compreensão desses indicadores. É claro que, por vezes, essas técnicas também podem sugerir estratégias inesperadas em mercados familiares. Meu curso abrange as técnicas básicas de IA útil para um comerciante, com ênfase nas muitas maneiras de evitar overfitting. Todo mundo sabe que a volatilidade depende da freqüência de medição: o desvio padrão dos retornos de 5 minutos é diferente do retorno diário. Para ser preciso, se z é o preço do log, então a volatilidade, amostrada em intervalos de, é onde Var significa tomar a variância ao longo de muitos tempos de amostragem. Se os preços seguem realmente uma caminhada geométrica aleatória, então Var () (8801Var ((z (t) - z (t)) 8733 ea volatilidade simplesmente escalam com a raiz quadrada do intervalo de amostragem. Devemos retornar diariamente, precisamos multiplicar a volatilidade diária por 8730252 para obter a volatilidade anualizada. Os comerciantes também sabem que os preços realmente não seguem uma caminhada aleatória geométrica. Se os preços são reverter média, vamos descobrir que eles não vagueiam longe de sua inicial O valor é tão rápido quanto uma caminhada aleatória. Se os preços estão tendendo, eles vagueiam mais rápido. Em geral, podemos escrever onde H é chamado o expoente Hurst, e é igual a 0,5 para uma verdadeira caminhada aleatória geométrica, mas será menor que 0,5 para os preços médios de reversão e maior que 0,5 para os preços tendenciais. Se anualizarmos a volatilidade de uma série de preços de média revertida, ela acabará tendo uma volatilidade anualizada menor do que a de uma caminhada aleatória geométrica, mesmo se ambas tiverem exatamente a mesma Mesma volatilidade medida em, digamos, barras de 5 min. Oposto é verdadeiro para uma série de tendências de preços. Por exemplo, se tentarmos isso em AUDCAD, uma série de tempo obviamente significando reverter, vamos obter H0.43. Todos os acima são bem conhecidos por muitos comerciantes, e são de fato discutido em meu livro. Mas o que é mais interessante é que o próprio expoente de Hurst pode mudar em alguma escala de tempo, e esta mudança às vezes sinaliza uma mudança de uma reversão média para um regime de momentum, ou vice-versa. Para ver isso, vamos plotar volatilidade (ou mais convenientemente, variação) em função de. Isto é chamado frequentemente a estrutura do termo da volatilidade (realizada). Comece com o SPY familiar. Podemos calcular os retornos intradiários usando midprices de 1 minutos para 210 minutos (17 hrs), e traçar o log (Var ()) contra log (). O ajuste, mostrado abaixo, é excelente. (Clique na figura para ampliar). A inclinação, dividida por 2, é o expoente de Hurst, que resulta ser 0.4941770.003, o que é muito ligeiramente revertido. Mas se fizermos o mesmo para os retornos diários de SPY, para intervalos de 1 dia até 28 (256) dias, verificamos que H é agora 0.4691770.007, o que significa significativamente a reversão da média. Conclusão: as estratégias de reversão média no SPY devem funcionar melhor do que intraday. Podemos fazer a mesma análise para USO (o WTI petróleo bruto futuros ETF). O intradiário H é 0.5151770.001, indicando comportamento de tendência significativo. O diário H é 0.561770.02, ainda mais significativamente tendência. Assim, as estratégias de impulso devem funcionar para futuros de petróleo bruto em qualquer escala de tempo razoável. Vamos voltar agora para GLD, o ouro ETF. Intraday H0.5051770.002, que é ligeiramente tendência. Mas diariamente H0.4691770.007: Significativamente significa reverter Momentum estratégias sobre o ouro pode trabalhar intraday, mas as estratégias de reversão média certamente funcionam melhor ao longo de vários dias. Onde a transição ocorre? Podemos examinar a estrutura do termo de perto: Podemos ver que em torno de 16-32 dias, as volatilidades se afastam da linha reta extrapolada a partir de freqüências intraday. Isso é onde devemos mudar de impulso para estratégias de reversão de média. Uma nota lateral de interesse: quando calculamos a variância de retornos sobre períodos que se estendem dois dias de negociação e os traçamos como função de log (). Deve incluir as horas quando o mercado foi fechado Acontece que a resposta é sim, mas não completamente. A fim de produzir o gráfico acima onde as variações diárias inicialmente caem na mesma linha reta que as variações intraday, temos que contar 1 dia de negociação como equivalente a 10 horas de negociação. Não 6,5 (para os mercados de equitiesETF dos EUA), e não 24. O número exato de horas de negociação equivalentes, é claro, varia de acordo com os diferentes instrumentos. Nick sobre a mintegration. eu discute os novos bancos de dados intradiários em Quandl e Kerf. Factorwave (Euan Sinclairs criação) começou um novo fórum: slack. factorwave. Tem algumas discussões muito ativas e aprofundadas de muitos tópicos de negociação e investimento. O professor Matthew Lyle, da Kellogg School of Management, publicou um novo artigo que relaciona os fundamentos com os prêmios de risco de variância: papers. ssrnsol3papers. cfmabstractid2696183. Há muito mais para significar estratégias de reversão do que apenas pares de negociação. Descubra como prosperar no atual ambiente de baixa volatilidade favorável a este tipo de estratégias. Prever a volatilidade é um tópico muito antigo. Cada estudante de finanças tem sido ensinado a usar o modelo GARCH para isso. Mas, como a maioria das coisas que aprendemos na escola, não necessariamente esperamos que elas sejam úteis na prática ou que funcionem bem fora da amostra. (Quando foi a última vez que você precisa usar o cálculo em seu trabalho) Mas por curiosidade, eu fiz uma rápida investigação de seu poder sobre a previsão da volatilidade do SPY diariamente close-to-close retorna. Eu estimou os parâmetros de um modelo GARCH em dados de treinamento de 21 de dezembro de 2005 a 5 de dezembro de 2011 usando a caixa de ferramentas econométricas Matlabs e testou quantas vezes o sinal da mudança prevista de 1 dia na volatilidade de acordo com a realidade no conjunto de teste de dezembro 6, 2011 a 25 de novembro de 2015. (Uma mudança de dia em volatilidade realizada é definida como a mudança no valor absoluto do retorno de 1 dia.) Uma surpresa agradável: o acordo é 58 dos dias. Se esta fosse a exatidão para predizer o sinal do retorno SPY em si, devemos nos preparar para se aposentar no luxo. A volatilidade é mais fácil de prever do que os retornos assinados, já que todos os estudantes de finanças também foram ensinados. Mas que bom é uma boa previsão de volatilidade Seria útil para os comerciantes de opções, que podem trocar volatilidades implícitas em vez de retornos direcionais A resposta é sim, a previsão de volatilidade realizada é útil para a previsão de volatilidade implícita, mas não da maneira que você esperaria. Se a GARCH nos disser que a volatilidade percebida aumentará amanhã, a maioria de nós instintivamente sair e comprar-nos algumas opções (ou seja, volatilidade implícita). No caso de SPY, nós provavelmente iríamos comprar alguns VXX. Mas isso seria um erro terrível. Lembre-se que a volatilidade que previmos é um retorno não assinado: uma previsão de maior volatilidade pode significar um dia muito otimista amanhã. Um alto retorno positivo em SPY é geralmente acompanhado por uma queda acentuada em VXX. Em outras palavras, um aumento na volatilidade realizada é geralmente acompanhado por uma diminuição na volatilidade implícita neste caso. Mas o que é realmente estranho é que essa anti-correlação entre a mudança na volatilidade realizada ea mudança na volatilidade implícita também se mantém quando o retorno é negativo (57 dias com retornos negativos). Um retorno muito negativo em SPY é, na verdade, geralmente acompanhado por um aumento na volatilidade implícita ou VXX, induzindo correlação positiva. Mas, em média, um aumento na volatilidade realizada devido a retornos negativos ainda é acompanhado por uma diminuição na volatilidade implícita. O resultado de tudo isso é que se você prever a volatilidade do SPY vai aumentar amanhã, você deve curto VXX vez. Quantiacs acaba de lançar uma concorrência sistema de comércio com investimentos garantidos de 2,25M para os três melhores sistemas de negociação. (Quantiacs ajuda Quants a obter investimentos para seus algoritmos de negociação e ajuda os investidores a encontrar o sistema de negociação certo.) Um novo livro chamado Momo Traders - Dicas, Truques e Estratégias de Ten Top Traders apresenta extensas entrevistas com dez top dia e swing comerciantes que encontram estoques Que se movem e capitalizam nesse momento. Outro novo livro chamado Algorithmic e High-Frequency Trading por 3 professores de finanças matemáticas descreve as ferramentas matemáticas sofisticadas que estão sendo aplicadas ao comércio de alta freqüência e execução ideal. Sim, o cálculo é necessário aqui. Minha Próxima Workshop 27-28 janeiro: Algorithmic Options Strategies Este é um novo curso on-line que é diferente da maioria das outras oficinas de opções oferecidas em outros lugares. Ele irá cobrir como um pode backtest estratégias de opção intraday e estratégias de opção de carteira. 7 a 11 de março: Arbitragem Estatística, Momentum Quantitativo e Inteligência Artificial para Traders. Estes cursos são sessões de treinamento altamente intensivas realizadas em Londres por uma semana inteira. I tipicamente precisam para caminhar por uma hora ao longo do Tamisa para rejuvenescer após cada dias classe. O curso de AI é novo, e para minha surpresa, algumas das técnicas melhoradas realmente funcionam. Minha Próxima Fala Eu estarei falando na QuantCon 2016 em 9 de abril em Nova York. O tópico será As Peculiaridades da Volatilidade. Eu apontei uma peculiaridade acima, mas há outras. QTS Partners, L. P. tem um retorno líquido de 1,56 em outubro (YTD: 11,50). Detalhes disponíveis para Pessoas Elegíveis Qualificadas conforme definido na Regra 4.7 da CFTC. Por Lukasz Wojtow Tradicionais mecânicos nunca param de pesquisar para a próxima borda do mercado. Não só para obter melhores resultados, mas também para ter mais de um sistema. Os melhores resultados de negociação podem ser alcançados com múltiplos sistemas não correlacionados negociados simultaneamente. Unfortunately, most traders use similar market inefficiency: some traders specialize in trend following, some in mean reversion and so on. Thats because learning to exploit one kind of edge is hard enough, mastering all of them 8211 impossible. It would be beneficial to have a software that creates many non-related systems. Recently I released Genotick - an open source software that can create and manage a group of trading systems. At the Genoticks core lies an epiphany: if its possible to create any software with just a handful of assembler instructions, it should be possible to create any trading systems with a handful of similarly simple instructions. These simple and meaningless-on-its-own instructions become extremely powerful when combined together. Right instructions in the right order can create any type of mechanical system: trend following, mean reverting or even based on fundamental data. The driving engine behind Genoticks power is a genetic algorithm. Current implementation is quite basic, but with some extra quirks. For example, if any of the systems is really bad 8211 it stays in the population but its predictions are reversed. Another trick is used to help recognize biased trading systems: a system can be removed if it doesnt give mirrored prediction on mirrored data. So for example, position on GBPUSD must be opposite to the one on USDGBP. Genotick also supports optional elitism (where the best systems always stay in the population, while others are retired due to old age), protection for new systems (to avoid removing systems that didnt yet have a chance to prove themselves) and inheriting initial systems weight from parents. These options give users plenty of room for experimentation. When Genotick is run for the first time - there are no systems. They are created at the start using randomly chosen instructions. Then, a genetic algorithm takes over: each system is executed to check its prediction on historical data. Systems that predicted correctly gain weight for future predictions, systems that predicted incorrectly 8211 lose weight. Gradually, day after day, population of systems grows. Bad systems are removed and good systems breed. Prediction for each day is calculated by adding predictions of all systems available at the time. Genotick doesnt iterate over the same historical data more than once 8211 training process looks exactly as if it was executed in real life: one day at a time. In fact, there is no separate 8220training8221 phase, program learns a little bit as each day passes by. Interestingly, Genotick doesnt check for rationale behind created systems. As each system is created out of random instructions, its possible (and actually very likely) that some systems use ridiculous logic. For example, its possible that a system will give a 8220Buy8221 signal if Volume was positive 42 days ago. Another system may want to go short each time the third digit in yesterdays High is the same as second digit in todays Open. Of course, such systems would never survive in real world and also they wouldnt survive for long in Genoticks population. Because each systems initial weight is zero, they never gain any significant weight and therefore dont spoil cumulative prediction given by the program. It may seem a little silly to allow such systems in the first place, but it enables Genotick to test algorithms that are free from traders believes, misguided opinions and personal limitations. The sad fact is, the market doesnt care about what system you use and how much sweat and tears you put into it. Market is going to do what it wants to do 8211 no questions asked, not taking prisoners. Market doesnt even care if you use any sort of intelligence, artificial or not. And so, the only rationale behind every trading system should be very simple: 8220Does it work8221. Nothing more, nothing less. This is the only metric Genotick uses to gauge systems. Each programs run will be a little bit different. Equity chart below shows one possible performance. Years shown are 2007 until 2015 with actual training starting in 2000. There is nothing special about year 2007, remember 8211 Genotick learns as it goes along. However, I felt its important to look how it performed during financial crisis. Markets traded were: USDCHF, USDJPY, 10 Year US Bond Yield, SPX, EURUSD, GBPUSD and Gold. (In some cases, I tested the system on a market index such as SPX instead of an instrument that tracks the index such as SPY, but the difference should be minor.) All markets were mirrored to allow removing biased systems. Some vital numbers: CAGR: 9.88 Maxim drawdown: -21.6 Longest drawdown: 287 trading days Profitable days: 53.3 CALMAR ratio: 0.644 Sharpe ratio: 1.06 Mean annual gain: 24.1 Losing year: 2013 (-12) (Click the cumulative returns in chart below to enlarge.) Cumulative Returns () since 2007 These numbers represent only 8220directional edge8221 offered by the software. There were no stop-losses, no leverage and no position sizing, which could greatly improve real life results. The performance assumes that at the end of each day, the positions are rebalanced so that each instrument starts with equal dollar value. (I. e. this is a constant rebalanced portfolio.) Artificial Intelligence is a hot topic. Self driving cars that drive better than an average human and chess algorithms that beat an average player are facts. The difference is that using AI for trading is perfectly legal and opponents may never know. Unlike chess and driving, there is a lot of randomness in financial markets and it may take us longer to notice when AI starts winning. Best hedge funds can be still run by humans but if any trading method is really superior, AI will figure it out as well. At the moment Genotick is more of a proof-of-concept rather than production-ready. It is very limited in usability, it doesnt forgive mistakes and its best to ask before using it for real trading. You will need Java 7 to run it. Its tested on both Linux and Windows 10. Example historical data is included. Any questions or comments are welcomed. I have been a big fan of options trader and author Euan Sinclair for a long time. I have cited his highly readable and influential book Option Trading in my own work, and it is always within easy reach from my desk. His more recent book Volatility Trading is another must-read. I ran into him at the Chicago Trading Show a few months ago where he was a panelist on volatility trading, and he graciously agreed to be interviewed by me. What is your educational background, and how did you start your trading career I got a Ph. D. in theoretical physics, studying the transition from quantum to classical mechanics. I always had intended to become a professor but the idea became less appealing once I saw what they did all day. At this time Nick Leeson was making news by blowing up Barings Bank and I thought I could do that. I mean trade derivatives not blowing up a bank (although I could probably manage that as well). Do you recommend a new graduate with a similar educational background as yours to pursue finance or trading as a career today I dont think I would for a few reasons. The world of derivatives and trading in general is now so much more visible than it was and there are now far better ways to prepare. When I started, physics Ph. D.s were hired only because they were smart and numerate and could pick things up on their own. My first trading firm had no training program. You just had to figure stuff out on your own. Now there are many good MFE courses or you could do a financial economics Ph. D. Further, it would very much depend on exactly what kind of physics had been studied. I did a lot of classical mechanics which is really geometry. This kind of pure theory isnt nearly as useful as a background heavy with stats or simulation. I think I could still make the transition, but it is no longer close to the ideal background. You have been a well-known options trader with a long track record: what do you think is the biggest obstacle to success for a retail options trader Trading costs. Most option trading ideas are still built on the Black-Scholes-Merton framework and the idea of dynamic hedging (albeit heavily modified). Most pro firms have stat arb like execution methods to reduce the effective bid-ask they pay in the underlying. They also pay practically no ticket charges and probably get rebates. Even then, their average profit per option trade is very small and has been steadily decreasing. Further, a lot of positional option trading relies on a large universe of possible trades to consider. This means a trader needs good scanning software to find trades, and a decent risk system because she will tend to have hundreds of positions on at one time. This is all expensive as well. Retail traders cant play this game at all. They have to look for situations that require little or no rebalancing and that can be limited to a much smaller universe. I would recommend the VIX complex or equity earnings events. As an options trader, do you tend to short or long volatility I am short about 95 of the time, but about 35 of my profits come from the long trades. Do you find it possible to fully automate options trading in the same way as that stocks, futures, and FX trading have been automated I see no reason why not. You have recently started a new website called FactorWave. Can you tell us about it What prompted the transition of your focus from options to stocks FactorWave is a set of stock and portfolio tools that do analysis in terms of factors such as value, size, quality and momentum. There is a lot of research by both academics and investors that shows that these (and other) factors can give market beating returns and lower volatility. Ive been interested in stocks for a long time. Most of my option experience has been with stock options and some of my best research was on how these factors affected volatility trading returns. Also, equity markets are a great place to build wealth over the long term. They are a far more suitable vehicle for retirement planning than options I actually think the distinction between trading and investing is fairly meaningless. The only difference seems to be the time scale and this is very dependent on the person involved as well, with long-term meaning anything form months to inter-generational. All Ive ever done as a trader is to look for meaningful edges and I found a lot of these in options. But Ive never found anything as persistent as the stock factors. There is over a hundred years of statistical evidence, studies in many countries and economic and behavioral reasons for their existence. They present some of the best edges I have ever found. That should be appealing to any trader or investor. Thank you These are really valuable insights. Most time series techniques such as the ADF test for stationarity, Johansen test for cointegration, or ARIMA model for returns prediction, assume that our data points are collected at regular intervals. In traders parlance, it assumes bar data with fixed bar length. It is easy to see that this mundane requirement immediately presents a problem even if we were just to analyze daily bars: how are we do deal with weekends and holidays You can see that the statistics of return bars over weekdays can differ significantly from those over weekends and holidays. Here is a table of comparison for SPY daily returns from 20050504-20150409: SPY daily returns Mean Returns (bps) Mean Absolute Returns (bps) Kurtosis (3 is 8220normal8221) Though the absolute magnitude of the returns over a weekday is similar to that over a weekend, the mean returns are much more positive on the weekdays. Note also that the kurtosis of returns is almost doubled on the weekends. (Much higher tail risks on weekends with much less expected returns: why would anyone hold a position over weekends) So if we run any sort of time series analysis on daily data, we are force-fitting a model on data with heterogeneous statistics that wont work well. The problem is, of course, much worse if we attempt time series analysis on intraday bars. Not only are we faced with the weekend gap, in the case of stocks or ETFs we are faced with the overnight gap as well. Here is a table of comparison for AUDCAD 15-min returns vs weekend returns from 20090101-20150616: AUDCAD 15-min returns Mean Returns (bps) Mean Absolute Returns (bps) Kurtosis (3 is 8220normal8221) In this case, every important statistic is different (and it is noteworthy that kurtosis is actually lower on the weekends here, illustrating the mean-reverting character of this time series.) So how should we predict intraday returns with data that has weekend gaps (The same solution should apply to overnight gaps for stocks, and so omitted in the following discussion.) Lets consider several proposals: 1) Just delete the weekend returns, or set them as NaN in Matlab, or missing values NA in R. This wont work because the first few bars of a week isnt properly predicted by the last few bars of the previous week. We shouldnt use any linear model built with daily or intraday data to predict the returns of the first few bars of a week, whether or not that model contains data with weekend gaps. As for how many bars constitute the first few bars, it depends on the lookback of the model. (Notice I emphasize linear model here because some nonlinear models can deal with large jumps during the weekends appropriately.) 2) Just pretend the weekend returns are no different from the daily or intraday returns when buildingtraining the time series model, but do not use the model for predicting weekend returns. I. e. do not hold positions over the weekends. This has been the default, and perhaps simplest (naive) way of handling this issue for many traders, and it isnt too bad. The predictions for the first few bars in a week will again be suspect, as in 1), so one may want to refrain from trading then. The model built this way isnt the best possible one, but then we dont have to be purists. 3) Use only the most recent period without a gap to train the model. So for an intraday FX model, we would be using the bars in the previous week, sans the weekends, to train the model. Do not use the model for predicting weekend returns nor the first few bars of a week. This sounds fine, except that there is usually not enough data in just a week to build a robust model, and the resulting model typically suffers from severe data snooping bias. You might think that it should be possible to concatenate data from multiple gapless periods to form a larger training set. This concatenation does not mean just piecing together multiple weeks time series into one long time series - that would be equivalent to 2) and wrong. Concatenation just means that we maximize the total log likelihood of a model over multiple independent time series, which in theory can be done without much fuss since log likelihood (i. e. log probability) of independent data are additive. But in practice, most pre-packaged time series model programs do not have this facility. (Do add a comment if anyone knows of such a package in Matlab, R, or Python) Instead of modifying the guts of a likelihood-maximization routine of a time series fitting package, we will examine a short cut in the next proposal. 4) Rather than using a pre-packaged time series model with maximum likelihood estimation, just use an equivalent multiple linear regression (LR) model. Then just fit the training data with this LR model with all the data in the training set except the weekend bars, and use it for predicting all future bars except the weekend bars and the first few bars of a week. This conversion of a time series model into a LR model is fairly easy for an autoregressive model AR(p), but may not be possible for an autoregressive moving average model ARMA(p, q). This is because the latter involves a moving average of the residuals, creating a dependency which I dont know how to incorporate into a LR. But I have found that AR(p) model, due to its simplicity, often works better out-of-sample than ARMA models anyway. It is of course, very easy to just omit certain data points from a LR fit, as each data point is presumed independent. Here is a plot of the out-of-sample cumulative returns of one such AR model built for predicting 15-minute returns of NOKSEK, assuming midpoint executions and no transaction costs (click to enlarge.)Beginner39s Guide to Quantitative Trading In this article Im going to introduce you to some of the basic concepts which accompany an end-to-end quantitative trading system . This post will hopefully serve two audiences. The first will be individuals trying to obtain a job at a fund as a quantitative trader. The second will be individuals who wish to try and set up their own retail algorithmic trading business. Quantitative trading is an extremely sophisticated area of quant finance. It can take a significant amount of time to gain the necessary knowledge to pass an interview or construct your own trading strategies. Not only that but it requires extensive programming expertise, at the very least in a language such as MATLAB, R or Python. However as the trading frequency of the strategy increases, the technological aspects become much more relevant. Thus being familiar with CC will be of paramount importance. A quantitative trading system consists of four major components: Strategy Identification - Finding a strategy, exploiting an edge and deciding on trading frequency Strategy Backtesting - Obtaining data, analysing strategy performance and removing biases Execution System - Linking to a brokerage, automating the trading and minimising transaction costs Risk Management - Optimal capital allocation, bet sizeKelly criterion and trading psychology Well begin by taking a look at how to identify a trading strategy. Strategy Identification All quantitative trading processes begin with an initial period of research. This research process encompasses finding a strategy, seeing whether the strategy fits into a portfolio of other strategies you may be running, obtaining any data necessary to test the strategy and trying to optimise the strategy for higher returns andor lower risk. You will need to factor in your own capital requirements if running the strategy as a retail trader and how any transaction costs will affect the strategy. Contrary to popular belief it is actually quite straightforward to find profitable strategies through various public sources. Academics regularly publish theoretical trading results (albeit mostly gross of transaction costs). Quantitative finance blogs will discuss strategies in detail. Trade journals will outline some of the strategies employed by funds. You might question why individuals and firms are keen to discuss their profitable strategies, especially when they know that others crowding the trade may stop the strategy from working in the long term. The reason lies in the fact that they will not often discuss the exact parameters and tuning methods that they have carried out. These optimisations are the key to turning a relatively mediocre strategy into a highly profitable one. In fact, one of the best ways to create your own unique strategies is to find similar methods and then carry out your own optimisation procedure. Here is a small list of places to begin looking for strategy ideas: Many of the strategies you will look at will fall into the categories of mean-reversion and trend-followingmomentum . A mean-reverting strategy is one that attempts to exploit the fact that a long-term mean on a price series (such as the spread between two correlated assets) exists and that short term deviations from this mean will eventually revert. A momentum strategy attempts to exploit both investor psychology and big fund structure by hitching a ride on a market trend, which can gather momentum in one direction, and follow the trend until it reverses. Another hugely important aspect of quantitative trading is the frequency of the trading strategy. Low frequency trading (LFT) generally refers to any strategy which holds assets longer than a trading day. Correspondingly, high frequency trading (HFT) generally refers to a strategy which holds assets intraday. Ultra-high frequency trading (UHFT) refers to strategies that hold assets on the order of seconds and milliseconds. As a retail practitioner HFT and UHFT are certainly possible, but only with detailed knowledge of the trading technology stack and order book dynamics . We wont discuss these aspects to any great extent in this introductory article. Once a strategy, or set of strategies, has been identified it now needs to be tested for profitability on historical data. That is the domain of backtesting . Strategy Backtesting The goal of backtesting is to provide evidence that the strategy identified via the above process is profitable when applied to both historical and out-of-sample data. This sets the expectation of how the strategy will perform in the real world. However, backtesting is NOT a guarantee of success, for various reasons. It is perhaps the most subtle area of quantitative trading since it entails numerous biases, which must be carefully considered and eliminated as much as possible. We will discuss the common types of bias including look-ahead bias . survivorship bias and optimisation bias (also known as data-snooping bias). Other areas of importance within backtesting include availability and cleanliness of historical data, factoring in realistic transaction costs and deciding upon a robust backtesting platform. Well discuss transaction costs further in the Execution Systems section below. Once a strategy has been identified, it is necessary to obtain the historical data through which to carry out testing and, perhaps, refinement. There are a significant number of data vendors across all asset classes. Their costs generally scale with the quality, depth and timeliness of the data. The traditional starting point for beginning quant traders (at least at the retail level) is to use the free data set from Yahoo Finance. I wont dwell on providers too much here, rather I would like to concentrate on the general issues when dealing with historical data sets. The main concerns with historical data include accuracycleanliness, survivorship bias and adjustment for corporate actions such as dividends and stock splits: Accuracy pertains to the overall quality of the data - whether it contains any errors. Errors can sometimes be easy to identify, such as with a spike filter . which will pick out incorrect spikes in time series data and correct for them. At other times they can be very difficult to spot. It is often necessary to have two or more providers and then check all of their data against each other. Survivorship bias is often a feature of free or cheap datasets. A dataset with survivorship bias means that it does not contain assets which are no longer trading. In the case of equities this means delistedbankrupt stocks. This bias means that any stock trading strategy tested on such a dataset will likely perform better than in the real world as the historical winners have already been preselected. Corporate actions include logistical activities carried out by the company that usually cause a step-function change in the raw price, that should not be included in the calculation of returns of the price. Adjustments for dividends and stock splits are the common culprits. A process known as back adjustment is necessary to be carried out at each one of these actions. One must be very careful not to confuse a stock split with a true returns adjustment. Many a trader has been caught out by a corporate action In order to carry out a backtest procedure it is necessary to use a software platform . You have the choice between dedicated backtest software, such as Tradestation, a numerical platform such as Excel or MATLAB or a full custom implementation in a programming language such as Python or C. I wont dwell too much on Tradestation (or similar), Excel or MATLAB, as I believe in creating a full in-house technology stack (for reasons outlined below). One of the benefits of doing so is that the backtest software and execution system can be tightly integrated, even with extremely advanced statistical strategies. For HFT strategies in particular it is essential to use a custom implementation. When backtesting a system one must be able to quantify how well it is performing. The industry standard metrics for quantitative strategies are the maximum drawdown and the Sharpe Ratio . The maximum drawdown characterises the largest peak-to-trough drop in the account equity curve over a particular time period (usually annual). This is most often quoted as a percentage. LFT strategies will tend to have larger drawdowns than HFT strategies, due to a number of statistical factors. A historical backtest will show the past maximum drawdown, which is a good guide for the future drawdown performance of the strategy. The second measurement is the Sharpe Ratio, which is heuristically defined as the average of the excess returns divided by the standard deviation of those excess returns. Here, excess returns refers to the return of the strategy above a pre-determined benchmark . such as the SP500 or a 3-month Treasury Bill. Note that annualised return is not a measure usually utilised, as it does not take into account the volatility of the strategy (unlike the Sharpe Ratio). Once a strategy has been backtested and is deemed to be free of biases (in as much as that is possible), with a good Sharpe and minimised drawdowns, it is time to build an execution system. Execution Systems An execution system is the means by which the list of trades generated by the strategy are sent and executed by the broker. Despite the fact that the trade generation can be semi - or even fully-automated, the execution mechanism can be manual, semi-manual (i. e. one click) or fully automated. For LFT strategies, manual and semi-manual techniques are common. For HFT strategies it is necessary to create a fully automated execution mechanism, which will often be tightly coupled with the trade generator (due to the interdependence of strategy and technology). The key considerations when creating an execution system are the interface to the brokerage . minimisation of transaction costs (including commission, slippage and the spread) and divergence of performance of the live system from backtested performance. There are many ways to interface to a brokerage. They range from calling up your broker on the telephone right through to a fully-automated high-performance Application Programming Interface (API). Ideally you want to automate the execution of your trades as much as possible. This frees you up to concentrate on further research, as well as allow you to run multiple strategies or even strategies of higher frequency (in fact, HFT is essentially impossible without automated execution). The common backtesting software outlined above, such as MATLAB, Excel and Tradestation are good for lower frequency, simpler strategies. However it will be necessary to construct an in-house execution system written in a high performance language such as C in order to do any real HFT. As an anecdote, in the fund I used to be employed at, we had a 10 minute trading loop where we would download new market data every 10 minutes and then execute trades based on that information in the same time frame. This was using an optimised Python script. For anything approaching minute - or second-frequency data, I believe CC would be more ideal. In a larger fund it is often not the domain of the quant trader to optimise execution. However in smaller shops or HFT firms, the traders ARE the executors and so a much wider skillset is often desirable. Bear that in mind if you wish to be employed by a fund. Your programming skills will be as important, if not more so, than your statistics and econometrics talents Another major issue which falls under the banner of execution is that of transaction cost minimisation. There are generally three components to transaction costs: Commissions (or tax), which are the fees charged by the brokerage, the exchange and the SEC (or similar governmental regulatory body) slippage, which is the difference between what you intended your order to be filled at versus what it was actually filled at spread, which is the difference between the bidask price of the security being traded. Note that the spread is NOT constant and is dependent upon the current liquidity (i. e. availability of buysell orders) in the market. Transaction costs can make the difference between an extremely profitable strategy with a good Sharpe ratio and an extremely unprofitable strategy with a terrible Sharpe ratio. It can be a challenge to correctly predict transaction costs from a backtest. Depending upon the frequency of the strategy, you will need access to historical exchange data, which will include tick data for bidask prices. Entire teams of quants are dedicated to optimisation of execution in the larger funds, for these reasons. Consider the scenario where a fund needs to offload a substantial quantity of trades (of which the reasons to do so are many and varied). By dumping so many shares onto the market, they will rapidly depress the price and may not obtain optimal execution. Hence algorithms which drip feed orders onto the market exist, although then the fund runs the risk of slippage. Further to that, other strategies prey on these necessities and can exploit the inefficiencies. This is the domain of fund structure arbitrage . The final major issue for execution systems concerns divergence of strategy performance from backtested performance. This can happen for a number of reasons. Weve already discussed look-ahead bias and optimisation bias in depth, when considering backtests. However, some strategies do not make it easy to test for these biases prior to deployment. This occurs in HFT most predominantly. There may be bugs in the execution system as well as the trading strategy itself that do not show up on a backtest but DO show up in live trading. The market may have been subject to a regime change subsequent to the deployment of your strategy. New regulatory environments, changing investor sentiment and macroeconomic phenomena can all lead to divergences in how the market behaves and thus the profitability of your strategy. Risk Management The final piece to the quantitative trading puzzle is the process of risk management . Risk includes all of the previous biases we have discussed. It includes technology risk, such as servers co-located at the exchange suddenly developing a hard disk malfunction. It includes brokerage risk, such as the broker becoming bankrupt (not as crazy as it sounds, given the recent scare with MF Global). In short it covers nearly everything that could possibly interfere with the trading implementation, of which there are many sources. Whole books are devoted to risk management for quantitative strategies so I wontt attempt to elucidate on all possible sources of risk here. Risk management also encompasses what is known as optimal capital allocation . which is a branch of portfolio theory . This is the means by which capital is allocated to a set of different strategies and to the trades within those strategies. It is a complex area and relies on some non-trivial mathematics. The industry standard by which optimal capital allocation and leverage of the strategies are related is called the Kelly criterion . Since this is an introductory article, I wont dwell on its calculation. The Kelly criterion makes some assumptions about the statistical nature of returns, which do not often hold true in financial markets, so traders are often conservative when it comes to the implementation. Another key component of risk management is in dealing with ones own psychological profile. There are many cognitive biases that can creep in to trading. Although this is admittedly less problematic with algorithmic trading if the strategy is left alone A common bias is that of loss aversion where a losing position will not be closed out due to the pain of having to realise a loss. Similarly, profits can be taken too early because the fear of losing an already gained profit can be too great. Another common bias is known as recency bias . This manifests itself when traders put too much emphasis on recent events and not on the longer term. Then of course there are the classic pair of emotional biases - fear and greed. These can often lead to under - or over-leveraging, which can cause blow-up (i. e. the account equity heading to zero or worse) or reduced profits. As can be seen, quantitative trading is an extremely complex, albeit very interesting, area of quantitative finance. I have literally scratched the surface of the topic in this article and it is already getting rather long Whole books and papers have been written about issues which I have only given a sentence or two towards. For that reason, before applying for quantitative fund trading jobs, it is necessary to carry out a significant amount of groundwork study. At the very least you will need an extensive background in statistics and econometrics, with a lot of experience in implementation, via a programming language such as MATLAB, Python or R. For more sophisticated strategies at the higher frequency end, your skill set is likely to include Linux kernel modification, CC, assembly programming and network latency optimisation. If you are interested in trying to create your own algorithmic trading strategies, my first suggestion would be to get good at programming. My preference is to build as much of the data grabber, strategy backtester and execution system by yourself as possible. If your own capital is on the line, wouldnt you sleep better at night knowing that you have fully tested your system and are aware of its pitfalls and particular issues Outsourcing this to a vendor, while potentially saving time in the short term, could be extremely expensive in the long-term. Just Getting Started with Quantitative TradingModeling Asset Processes Introduction Over the last twenty five years significant advances have been made in the theory of asset processes and there now exist a variety of mathematical models, many of them computationally tractable, that provide a reasonable representation of their defining characteristics. While the Geometric Brownian Motion model remains a staple of stochastic calculus theory, it8230 Systematic Strategies Fund Jan 2017 Commentary The quote from Bloomberg says it all: Last month featured more than its fair share of political excitements, as Donald Trump arrived in the White House. Yet it was resolutely boring for U. S. stocks, with one-month realized volatility on the SampP 500 coming in at 6.51 as the index moved steadily higher. In records8230 Conditional Value at Risk Models One of the most widely used risk measures is the Value-at-Risk, defined as the expected loss on a portfolio at a specified confidence level. In other words, VaR is a percentile of a loss distribution. But despite its popularity VaR suffers from well-known limitations: its tendency to underestimate the risk in the (left) tail of8230 Copulas in Risk Management Copulas in Risk Management The Systematic Volatility Strategy The Systematic Volatility strategy uses mathematical models to quantify the relative value of ETF products based on the CBOE SampP500 Volatility Index (VIX) and create a positive-alpha longshort volatility portfolio. The strategy is designed to perform robustly during extreme market conditions, by utilizing the positive convexity of the underlying ETF assets. It does not rely8230 The Systematic Strategies Quantitative Equity Strategy Systematic Strategies started out in 2009 as a proprietary trading firm engaged in high frequency trading. In 2012 the firm expanded into low frequency systematic trading strategies with the launch of our VIX ETF strategy, which was superseded in 2015 by the Systematic Volatility Strategy. The firm began managing external capital in its managed account platform in 20158230. Strategy Portfolio Construction For many decades the principles of portfolio construction laid out by Harry Markovitz in the 1950s have been broadly accepted as one of the cornerstones of modern portfolio theory (as summarized, for example, in this Wikipedia article). The strengths and weakness of the mean-variance methodology are now widely understood and broadly accepted. But alternatives exist, one8230 HFT VIX Scalper Leads on Collective2 Our high frequency VIX scalping strategy is now the 1 top performing strategy on Collective2, with returns of over 2700 since April 2016 with a Sharpe Ratio above 10 and Profit Factor of 2.8. For more background on HFT scalping strategies see the following post: Systematic Strategies Fund Systematic Strategies was launched in 2009 as a proprietary trading firm engaged in high frequency trading. In 2012 the firm expanded into low frequency systematic trading strategies with the launch of our VIX ETF strategy. The original VIX ETF strategy was superseded in 2015 by the current Systematic Volatility Strategy, which improved on the original version by eliminating8230 The Algorithm A challenge was posted recently on LinkedIn to provide an algorithm to determine the longest palindrome in a specified string. It proved to be fairly straightforward to handle the problem in a single line of Mathematica code, as follows: teststring 8220ItellyoumadamthecatisnotacivicanimalalthoughtisdeifiedinEgypt8221 nlargest 5 TakeLargestByCasesStringCasesteststring, , Overlaps - gt All, PalindromeQ, StringLength, nlargest Flatten8230

No comments:

Post a Comment