Codificação automatizada do sistema de negociação
Como fazer um robô de negociação sem tempo.
Para fazer um robô de negociação, você precisa de um sistema de comércio.
A negociação nos mercados financeiros envolve muitos riscos, incluindo o mais crítico - o risco de tomar uma decisão comercial incorreta. O sonho de todos os comerciantes é encontrar um robô comercial, que está sempre em boa forma e não sujeito a fraquezas humanas - medo, ganância e impaciência.
Cada recém-chegado quer obter ou criar um sistema de negociação claro e rigoroso que possa ser apresentado sob a forma de algoritmos e se livrar completamente das operações de rotina. É possível?
Um sistema de comércio é uma condição necessária para entrar no mercado e esse sistema deve ser lucrativo, é claro. Quando os recém-chegados chegam ao mercado, eles geralmente estão sobrecarregados com a grande massa de informações difíceis de entender. Livros e fóruns de comerciantes podem fornecer alguma ajuda nesse caso.
Infelizmente, nem todos os autores são comerciantes de sucesso e nem todos os comerciantes de sucesso escrevem livros. Muitos recursos web especiais são criados apenas para ganhar lucro para seus proprietários, pois é muito mais difícil negociar seu próprio dinheiro do que emitir previsões e ensinar sistemas de negociação.
Cada comerciante deve passar de forma independente todos os estágios de uma criação do sistema comercial. Há um ditado popular de que não importa o sistema que você usa para negociação, o principal é que você deve negociar de acordo com esse sistema. Caso contrário, a negociação no mercado se converte em uma aposta com um resultado previsível.
Trading Robots e Forex.
Espera-se que o mercado Forex tenha uma grande liquidez. Além disso, permite a negociação 24 horas por dia, ao contrário de muitos outros mercados. Portanto, muitos comerciantes tentam fazer robôs comerciais especialmente para o mercado Forex, pois oferece uma grande quantidade de instrumentos de negociação.
No entanto, os céticos afirmam que todos os pares de moedas estão fortemente correlacionados entre si, proporcionando uma volatilidade muito baixa no mercado. Mas seus oponentes respondem que cada par de moedas possui características próprias e baixa volatilidade é compensada por uma grande alavanca.
Em qualquer caso, os instrumentos Forex são atraentes para fazer robôs comerciais e a maioria dos adeptos do comércio automatizado aprimoram suas habilidades em pares de moedas.
Os terminais comerciais MetaTrader 4 e MetaTrader 5 são especialmente projetados para desenvolver sistemas de negociação automatizados facilmente, mas, ao mesmo tempo, sua interface também é conveniente para negociação manual.
Como começar a fazer um robô de negociação?
Existem muitas abordagens para construir um sistema de negociação automatizado. Descreveremos apenas algumas das principais.
A primeira abordagem é baseada em matemática. Um desenvolvedor tenta criar uma espécie de equação que pode considerar muitos fatores. Esta abordagem baseia-se na firme convicção de que os movimentos de preços são gerenciados por um modelo que pode ser encontrado usando os dados históricos disponíveis.
Na maioria dos casos, os seguidores dessa abordagem conhecem muito matemática, mas não sabem nada sobre / não estão interessados no mercado. O mercado é uma abstração pura, um tipo de jogo intelectual para eles. Esta abordagem geralmente leva a muitos anos de estudo e desenvolvimento, enquanto um resultado definitivo na forma de um sistema de negociação automatizado não é tão importante.
A segunda abordagem baseia-se no estudo das leis de mercado. Não são feitas tentativas para entender por que o preço subiu ou desce quando vários números de análise técnica aparecem em um gráfico. A vantagem desta abordagem é que não requer conhecimentos especiais de matemática e não faz suposições sobre a força motriz do mercado.
É mais claro e conveniente ao estudar comércio. É mais popular entre os comerciantes que receberam reconhecimento universal. A desvantagem da abordagem é a necessidade de acompanhar constantemente todos os símbolos necessários.
Mais cedo ou mais tarde, um comerciante começa a considerar a automação dos processos de negociação e a questão mais considerável aparece nesse estágio - a complexidade da formalização das regras de negociação ao tentar expressá-las sob a forma de algoritmos. Em alguns casos, os comerciantes que tentam solicitar um robô comercial não podem descrever as regras comerciais e encontrar um terreno comum com os programadores.
A terceira abordagem baseia-se na tentativa de criar uma "caixa preta" baseada em redes neurais com o uso das ferramentas pré-fabricadas amplamente disponíveis em pacotes especiais de software e matemática. A criação de um sistema de negociação automatizado com os elementos da inteligência artificial é uma tarefa emocionante e desafiadora, mesmo para os recém-chegados, uma vez que não requer fundo matemático profundo, nem experiência de programação - tudo é feito usando auxílios visuais.
Um comerciante deve conhecer os conceitos básicos de indicadores técnicos, possuir uma capacidade para preparar dados de preços necessários e experiência em algum pacote definido para trabalhar com redes neurais. A principal desvantagem desta abordagem é que um robô comercial obtido usando essas ferramentas especializadas para trabalhar com redes neurais é na verdade uma "caixa preta". Os comerciantes não conhecem seus princípios de trabalho e, em geral, é impossível prever qual a fase de mercado que será o mais problemático para o robô.
Os programadores geralmente escolhem a quarta abordagem - eles começam a fazer um robô comercial desde o início, sem gastar tempo para negociação manual. Por que trocar manualmente? Você pode fazer um robô passar alguns meses e colher os benefícios dos seus esforços, então.
Mas "sem dores, sem ganhos". Na maioria dos casos, os programadores começam a criar toda a infra-estrutura necessária usando uma linguagem de programação familiar em vez de apenas fazer um robô comercial - obter e processar dados de preços, representação visual de gráficos e indicadores, meios personalizados de testar estratégias em dados históricos e assim por diante.
Eles ganham muita experiência no processo. Mas na maioria dos casos, essa experiência não os aproxima do objetivo final - criação de um sistema de negociação automatizado. E, mesmo se um robô comercial for criado, não há garantia de que seja lucrativo. E se um programador quiser escrever outro sistema comercial? Reestruturação profunda e novos erros de programação são inevitáveis.
Há também a quinta abordagem - comprando um sistema comercial pronto feito sob a forma de um robô comercial. Neste caso, um comerciante atua como operador ou sintonizador. Esta abordagem economiza muito tempo (não precisa aprender muitas coisas novas) e permite que os comerciantes entrem rapidamente no mundo da negociação automatizada.
A principal desvantagem desta abordagem decorre de suas vantagens: você não conhece os princípios de operação do seu robô comercial e sua estrutura. E mesmo que um vendedor tenha fornecido uma descrição detalhada do sistema de negociação implementado, você nunca estará completamente seguro nele.
No entanto, nenhuma das abordagens mencionadas pode dar-lhe garantia absoluta exceto um depósito bancário. Mas essa não é uma solução muito adequada para pessoas interessadas em negociação no mercado e maneiras de aumentar seus ativos privados.
Qual é a melhor abordagem para a negociação automatizada de um comerciante?
Cada uma das cinco abordagens descritas tem suas vantagens e corresponde a algum tipo de comerciante definido. É improvável que você escolha a primeira abordagem (descrição analítica do mercado) sem um bom histórico matemático. É igualmente improvável que você comece a fazer robôs comerciais com base em redes neurais. No entanto, ambas as abordagens são muito emocionantes e proporcionam um bom exercício intelectual.
Abaixo, vamos discutir apenas a segunda abordagem, que já é considerada a clássica. Essa é a abordagem geralmente escolhida por novos seguidores do comércio automatizado, uma vez que a análise técnica continua a ser a área de conhecimento chave ao aprender noções básicas de negociação.
Outra vantagem da segunda abordagem é que depois de passar algum tempo para negociação manual e obter o senso do mercado, você já terá uma boa compreensão das ferramentas de análise técnica. Além disso, você poderá programar estratégias de negociação ou criar redes neurais em um nível superior.
Os primeiros passos na criação de um robô de negociação.
Para criar um sistema de negociação automatizado, você precisa de habilidades de programação e conhecimento de todas as complexidades do processamento de pedidos comerciais. Mas, em primeiro lugar, você pode começar com os Expert Advisors, fabricados em linha, negociando robôs da biblioteca gratuita do Code Base.
Baixe qualquer Consultor Especializado (robô comercial) e inicie-o nos terminais de clientes do Strategy Tester de MetaTrader 4 ou MetaTrader 5. Selecione um intervalo de histórico que mostre uma forte tendência e um intervalo com um plano. Execute a otimização de parâmetros de entrada do Expert Advisor e examine suas diferenças nesses dois intervalos.
Inicie um Expert Advisor com os parâmetros ótimos para um plano em um intervalo de tendências e com os parâmetros ótimos para uma tendência em um intervalo plano. Examine as diferenças nos resultados da negociação, distribuições de negócios e outros parâmetros estatísticos. Como resultado, você saberá o quanto o comportamento do seu sistema comercial pode variar quando a situação do mercado muda.
Seria melhor tentar várias estratégias de negociação padrão usando este método em diferentes partes da história e vários símbolos. Tal operação de teste impede o ajuste de um sistema de negociação para algum intervalo de histórico definido e fornece uma melhor compreensão dos sistemas de tendência e contrapressão.
O próximo passo seria criar sistemas de negociação mais complexos com base na combinação de sinais simples já existentes do MQL5 Wizard set. Você pode testar e desenvolver sua intuição comercial, classificando sinais ruins de um sistema usando um filtro baseado em outro sistema sem meios de programação.
O principal não é superar. Quanto mais os parâmetros de entrada que um sistema de negociação tem, mais fácil será montar. Houve muitas discussões sobre as diferenças entre otimização e adequação. Não há soluções amplamente aceitas aqui. Mas a visualização de resultados de teste / otimização e seu próprio senso comum podem ajudá-lo.
Aprenda a identificar os parâmetros de entrada mais críticos que afetam seu sistema comercial de todo o conjunto de dados de entrada. Não preste muita atenção aos parâmetros secundários que levam tempo durante a otimização, mas não afetam a própria lógica do sistema. Lembre-se de que um bom sistema de negociação sempre demonstra um pequeno movimento livre de parâmetros secundários, mas não apresenta volatilidade dramática no caso de mudanças no mercado insignificantes.
Você pode gastar tanto tempo nesta fase, conforme desejar, até ter certeza de que pode entender qualquer estratégia de negociação que examine resultados de teste e otimização. O conhecimento de pontos fortes e fracos dos sistemas padrão permitirá que você esteja melhor preparado ao criar seu próprio robô comercial.
Programação de um robô de negociação.
Suponha que você tenha aprendido / esteja aprendendo linguagem de programação MQL4 ou MQL5 e agora você está pronto para escrever seu primeiro consultor especialista para o terminal do cliente MetaTrader. Vários casos são possíveis aqui.
Primeiro, você pode examinar vários robôs comerciais prontos, descritos nos artigos para entender melhor as complexidades de programação.
Em segundo lugar, você pode fazer perguntas sobre MQL4munity ou MQL5munity, se você tiver problemas não resolvidos. Os participantes da comunidade experientes geralmente ajudam os recém-chegados a mostrarem interesse sincero no assunto.
Em terceiro lugar, você pode solicitar imbricação ou desenvolvimento de um Consultor Especialista ou um indicador no serviço de Emprego, se você não conseguir escrever um programa necessário por conta própria. Mas, mesmo que você faça um pedido por meio do serviço freelance, você deve ter uma idéia sobre testes de estratégia para encontrar um idioma comum com um desenvolvedor.
Além disso, o conhecimento básico de uma linguagem de programação permite implementar pequenas correções e alterações no código depois que o trabalho já foi concluído. Afinal, não seria muito conveniente chamar um programador para corrigir todos os pequenos problemas que você encontrar. Seria muito mais fácil e rápido consertar você mesmo.
Não há necessidade de reinventar a roda.
Como encontrar sua própria estratégia de negociação, ou pelo menos em que direção você deve concentrar sua pesquisa? Todos os comerciantes protegem seus próprios sistemas de negociação, se tiverem um. Todos os recém-chegados querem criar um sistema rentável ou obter um ready-made. Ao mesmo tempo, qualquer solução obtida parece ser muito simples em comparação com as idéias dos recém-chegados sobre um sistema de comércio genuíno.
Os homens do exército de todo o mundo são propensos a níveis excessivos de sigilo. Há muitas piadas sobre isso, incluindo o seguinte: "O segredo militar não está no que você está estudando, - um oficial diz aos estudantes da escola militar, - mas no fato de que exatamente você está estudando isso". A situação com os sistemas de negociação é bastante similar: a maioria dos comerciantes usa idéias comerciais simples e bem conhecidas com pequenas modificações, por exemplo, adicionando Trailing Stop ou confirmações de indicadores de tendência.
Há muitos fóruns de comerciantes com acesso limitado, onde os participantes se unem para desenvolver ou melhorar alguns sistemas comerciais secretos. O mais interessante é que esses sistemas não contêm nada de especial. Geralmente, uma idéia bem conhecida (como "comércio com a tendência") é usada como base. Então, é aperfeiçoado com alguns novos indicadores desconhecidos para o público em geral.
Portanto, você pode facilmente obter códigos de código de robô comercial disponíveis e tentar usá-los corretamente com vários símbolos e prazos. Outro exemplo popular pode ser mencionado aqui: "Você não gosta de gatos? Você simplesmente não sabe como cozinhar!" É difícil de acreditar, mas a probabilidade de desenvolver algo realmente novo é muito pequena. O principal aqui é criar um sistema usando ingredientes disponíveis. Não pense que alguns gênios tenham acesso a alguns sistemas secretos dos laboratórios da NASA. Esse é o segredo do Graal.
Apenas alguns os farão.
Então, por que ninguém usa idéias comerciais, se eles estão literalmente ao alcance do braço? A resposta provavelmente está na psicologia humana. A equipe de muitos bancos e grandes fundos de investimento inclui comerciantes que realizam negócios de acordo com regras rígidas e dentro de volumes limitados. Mas por algumas razões, apenas alguns comerciantes institucionais deixam suas empresas e começam a negociar usando seu próprio dinheiro.
Acontece que você precisa não só de uma estratégia de negociação, mas também da disciplina de ferro para segui-la. Muitos comerciantes descobriram com arrependimento que eles também têm os mesmos problemas psicológicos descritos nos livros. Depois de perceber que o pior inimigo dos comerciantes são eles próprios, um recém-chegado começa a pensar em fazer um robô comercial para eliminar um fardo psicológico.
Embora eu me desvie um pouco do assunto, devo mencionar os lendários comerciantes de tartarugas que negociaram com êxito em múltiplos mercados no final do século XX. Leia "Way of the Turtle" e você verá que a coisa mais importante para um comerciante é uma autodisciplina e não um sistema top secreto. Infelizmente, a maioria dos recém-chegados não conseguirá seguir uma estratégia rentável, mesmo que obtenha gratuitamente.
O problema é que a maioria das estratégias de negociação perfeitamente ajustadas para o comércio manual dificilmente podem ser formalizadas e transcritas para uma linguagem de programação. As estratégias que podem ser facilmente formalizadas (por exemplo, as que envolvem duas médias móveis "interseção") são muito simples e exigem muitos aprimoramentos e melhorias, para que possam ser usados na prática. Assim, uma idéia simples é gradualmente complicada por uma abundância de parâmetros externos impedindo um robô comercial de entradas falsas e erros claramente visíveis para um desenvolvedor. Emerge uma questão de otimização de robô comercial. Este processo não deve se transformar em uma sobre-optimização e ajuste para um intervalo de histórico específico.
Para resolver este problema, o teste direto usando os parâmetros do sistema obtidos foi implementado no terminal MetaTrader 5. Se os resultados de teste direto não diferirem significativamente daqueles obtidos na seção de otimização, existe uma probabilidade de um robô comercial ser suficientemente estável por algum tempo após o lançamento em uma conta de negociação. Um comprimento de um intervalo para otimização de parâmetros e um valor real desse "algum tempo" depende de um determinado sistema de negociação.
Assim, a otimização de um robô comercial antes de iniciá-lo em uma conta comercial lembra de desenrolar uma funda - quanto mais cuidadosamente desenrolamos e lançamos um projétil da funda, mais longe voará e mais precisa será a trajetória dele. Um robô de negociação completamente desenvolvido manterá um resultado positivo em uma conta de negociação por mais tempo do que um robô comercial obtido como resultado de uma montagem. Podemos dizer que o Grail é uma idéia de trabalho e ajuste correto dos parâmetros realizados de tempos em tempos nos momentos de mudanças nas condições do mercado.
Isso pode ser ilustrado pelos resultados do Campeonato Automatizado de Negociação que é realizado por muitos anos já. Os assessores de especialistas enviados de todos os participantes passam por testes automáticos no intervalo de tempo de janeiro até o final de julho. O principal requisito para passar o teste automático é um lucro obtido por oito meses de teste. Mas menos de metade dos robôs comerciais admitidos para o Campeonato continuam lucrativos após os meses de trabalho autônomo.
Você também pode tentar suas habilidades em fazer e ajustar o seu robô comercial para participar do Campeonato e obter os resultados de testes avançados do seu Consultor Especialista. Além disso, a participação é gratuita e os prêmios são impressionantes. Esperamos ver você lá!
Conclusão.
Os comerciantes intradiários profissionais passam muitas horas sentados em seus computadores e esperando o momento certo para realizar um acordo. Claro, eles não podem estar em boa forma o tempo todo.
A maioria dos comerciantes chega à conclusão de que suas ações violam suas próprias regras de negociação. Nem todos os sistemas de negociação podem ser completamente formalizados, mas mesmo esses sistemas podem, na maioria dos casos, adotar ferramentas adicionais, como indicadores, sistemas analíticos e filtros de sinais falsos.
Não fazemos recomendações especiais aqui sobre o aprendizado de línguas MQL4 ou MQL5, pois há muitos outros artigos úteis sobre esse assunto. O objetivo deste artigo foi fornecer uma idéia inicial sobre como começar a fazer seu robô comercial para os terminais MetaTrader 4 e MetaTrader 5.
Esperamos que este artigo economize tempo para os recém-chegados e mostre a direção certa na difícil tarefa de desenvolver um sistema de negociação automatizado.
Traduzido do russo pela MetaQuotes Software Corp.
Codificação de sistemas de negociação.
Por Justin Kuepper.
Como são criados sistemas de negociação automatizados?
Este tutorial se concentrará nas segunda e terceira partes deste processo, onde suas regras são convertidas em um código que seu software comercial pode entender e usar.
Vantagens e desvantagens.
Um sistema automatizado leva a emoção e ocupado - trabalhe fora da negociação, o que permite que você se concentre em melhorar sua estratégia e regras de gerenciamento de dinheiro. Uma vez que um sistema lucrativo é desenvolvido, não requer nenhum trabalho de sua parte até que ele quebre, ou as condições do mercado exigem uma mudança. Desvantagens:
Se o sistema não estiver corretamente codificado e testado, grandes perdas podem ocorrer muito rapidamente. Às vezes, é impossível colocar certas regras em código, o que dificulta o desenvolvimento de um sistema de negociação automatizado. Neste tutorial, você aprenderá como planejar e projetar um sistema de negociação automatizado, como traduzir esse design para o código que seu computador irá entender, como testar seu plano para garantir um desempenho ótimo e, finalmente, como colocar seu sistema em uso.
QuantStart.
Junte-se ao portal de membros privados da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento. Você encontrará um grupo bem informado de mentalistas quant pronto para responder suas perguntas comerciais mais importantes.
Confira meu ebook sobre o comércio de quant, onde eu ensino você como criar estratégias de negociação sistemáticas lucrativas com ferramentas Python, desde o início.
Dê uma olhada no meu novo ebook sobre estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas bayesianas, com Python e R.
Por Michael Halls-Moore em 26 de julho de 2018.
Uma das perguntas mais freqüentes que recebo no QS mailbag é "Qual é a melhor linguagem de programação para negociação algorítmica?". A resposta curta é que não existe um "melhor" idioma. Parâmetros de estratégia, desempenho, modularidade, desenvolvimento, resiliência e custo devem ser considerados. Este artigo descreve os componentes necessários de uma arquitetura de sistema de negociação algorítmica e como as decisões relativas à implementação afetam a escolha do idioma.
Em primeiro lugar, serão considerados os principais componentes de um sistema de negociação algorítmico, como ferramentas de pesquisa, otimizador de portfólio, gerenciador de riscos e motor de execução. Posteriormente, serão examinadas diferentes estratégias de negociação e como elas afetam o design do sistema. Em particular, a freqüência de negociação e o provável volume de negociação serão discutidos.
Uma vez que a estratégia de negociação foi selecionada, é necessário arquitetar todo o sistema. Isso inclui a escolha de hardware, o (s) sistema (s) operacional (is) e a resiliência do sistema contra eventos raros e potencialmente catastróficos. Enquanto a arquitetura está sendo considerada, deve-se ter em conta o desempenho, tanto para as ferramentas de pesquisa quanto para o ambiente de execução ao vivo.
Qual é o sistema de comércio tentando fazer?
Antes de decidir sobre o "melhor" idioma com o qual escrever um sistema de negociação automatizado, é necessário definir os requisitos. O sistema será puramente baseado em execução? O sistema exigirá um módulo de gerenciamento de risco ou construção de portfólio? O sistema exigirá um backtester de alto desempenho? Para a maioria das estratégias, o sistema comercial pode ser dividido em duas categorias: Pesquisa e geração de sinal.
A pesquisa está preocupada com a avaliação de um desempenho de estratégia em relação aos dados históricos. O processo de avaliação de uma estratégia de negociação em relação aos dados anteriores do mercado é conhecido como backtesting. O tamanho dos dados e a complexidade algorítmica terão um grande impacto na intensidade computacional do backtester. A velocidade da CPU e a concorrência são muitas vezes os fatores limitantes na otimização da velocidade de execução da pesquisa.
A geração de sinal está preocupada com a geração de um conjunto de sinais de negociação a partir de um algoritmo e envio de ordens para o mercado, geralmente através de uma corretora. Para determinadas estratégias, é necessário um alto nível de desempenho. As questões de E / S, como a largura de banda da rede e a latência, muitas vezes são fatores limitantes na otimização de sistemas de execução. Assim, a escolha de idiomas para cada componente de todo o seu sistema pode ser bastante diferente.
Tipo, Frequência e Volume de Estratégia.
O tipo de estratégia algorítmica empregada terá um impacto substancial no design do sistema. Será necessário considerar os mercados comercializados, a conectividade com os fornecedores de dados externos, a freqüência e o volume da estratégia, o trade-off entre facilidade de desenvolvimento e otimização de desempenho, bem como qualquer hardware personalizado, incluindo customizado servidores, GPUs ou FPGAs que possam ser necessários.
As opções de tecnologia para uma estratégia de ações de baixa freqüência dos EUA serão muito diferentes das de uma negociação de estratégias de arbitragem estatística de alta freqüência no mercado de futuros. Antes da escolha do idioma, muitos fornecedores de dados devem ser avaliados que pertencem à estratégia em questão.
Será necessário considerar a conectividade com o fornecedor, a estrutura de todas as APIs, a pontualidade dos dados, os requisitos de armazenamento e a resiliência em face de um fornecedor que está offline. Também é aconselhável possuir acesso rápido a vários fornecedores! Vários instrumentos têm todos os seus peculiaridades de armazenamento, exemplos dos quais incluem símbolos de ticker múltiplos para ações e datas de vencimento para futuros (sem mencionar nenhum dado OTC específico). Isso precisa ser incorporado ao design da plataforma.
A frequência da estratégia provavelmente será um dos maiores drivers de como a pilha de tecnologia será definida. Estratégias que empregam dados com mais freqüência do que minuciosamente ou em segundo lugar, exigem uma consideração significativa em relação ao desempenho.
Uma estratégia que excede as barras segundo (isto é, dados de marca) leva a um design orientado a desempenho como o principal requisito. Para estratégias de alta freqüência, uma quantidade substancial de dados do mercado precisará ser armazenada e avaliada. Software como HDF5 ou kdb + é comumente usado para essas funções.
Para processar os extensos volumes de dados necessários para aplicações HFT, um sistema de backtester e execução extensivamente otimizado deve ser usado. C / C ++ (possivelmente com algum montador) é provável para o candidato a linguagem mais forte. As estratégias de ultra-alta freqüência certamente exigirão hardware personalizado, como FPGAs, co-localização de troca e ajuste de interface de rede / kernal.
Sistemas de pesquisa.
Os sistemas de pesquisa geralmente envolvem uma mistura de desenvolvimento interativo e script automatizado. O primeiro geralmente ocorre dentro de um IDE, como Visual Studio, MatLab ou R Studio. O último envolve cálculos numéricos extensos em vários parâmetros e pontos de dados. Isso leva a uma escolha de idioma que fornece um ambiente direto para testar código, mas também fornece desempenho suficiente para avaliar estratégias em várias dimensões de parâmetros.
Os IDE típicos neste espaço incluem Microsoft Visual C ++ / C #, que contém extensos utilitários de depuração, recursos de conclusão de código (via "Intellisense") e visões gerais diretas de toda a pilha do projeto (via o banco de dados ORM, LINQ); MatLab, que é projetado para uma grande variedade de álgebras lineares numéricas e operações vetoriais, mas de uma forma de console interativo; R Studio, que envolve o console de linguagem estatística R em um IDE de pleno direito; Eclipse IDE para Linux Java e C ++; e IDE semi-proprietários, como Enthought Canopy para Python, que incluem bibliotecas de análise de dados, como NumPy, SciPy, scikit-learn e pandas em um único ambiente interativo (console).
Para backtesting numérico, todos os idiomas acima são adequados, embora não seja necessário utilizar uma GUI / IDE, pois o código será executado "em segundo plano". A principal consideração nesta fase é a velocidade de execução. Um idioma compilado (como C ++) geralmente é útil se as dimensões do parâmetro backtest forem grandes. Lembre-se de que é necessário desconfiar de tais sistemas se for esse o caso!
Idiomas interpretados, como Python, muitas vezes fazem uso de bibliotecas de alto desempenho, como NumPy / pandas para a etapa de teste, para manter um grau razoável de competitividade com equivalentes compilados. Em última análise, o idioma escolhido para o backtesting será determinado por necessidades algorítmicas específicas, bem como o intervalo de bibliotecas disponíveis no idioma (mais sobre isso abaixo). No entanto, o idioma utilizado para o backtester e os ambientes de pesquisa podem ser completamente independentes dos usados na construção de portfólio, gerenciamento de riscos e componentes de execução, como será visto.
Construção de carteiras e gerenciamento de riscos.
A construção do portfólio e os componentes de gerenciamento de riscos são muitas vezes ignorados pelos comerciantes algorítmicos de varejo. Isso é quase sempre um erro. Essas ferramentas fornecem o mecanismo pelo qual o capital será preservado. Eles não só tentam aliviar o número de apostas "arriscadas", mas também minimizam o churn dos próprios negócios, reduzindo os custos de transação.
Versões sofisticadas desses componentes podem ter um efeito significativo na qualidade e consistência da lucratividade. É direto criar um estável de estratégias, pois o mecanismo de construção do portfólio e o gerenciador de riscos podem ser facilmente modificados para lidar com múltiplos sistemas. Assim, eles devem ser considerados componentes essenciais no início do projeto de um sistema de comércio algorítmico.
O trabalho do sistema de construção de carteiras é levar um conjunto de trades desejados e produzir o conjunto de negócios reais que minimizam o churn, manter exposições a vários fatores (como setores, classes de ativos, volatilidade, etc.) e otimizar a alocação de capital para vários estratégias em um portfólio.
A construção do portfólio geralmente se reduz a um problema de álgebra linear (como uma fatoração da matriz) e, portanto, o desempenho é altamente dependente da eficácia da implementação de álgebra linear numérica disponível. As bibliotecas comuns incluem uBLAS, LAPACK e NAG para C ++. O MatLab também possui operações de matriz amplamente otimizadas. Python utiliza NumPy / SciPy para tais cálculos. Um portfólio freqüentemente reequilibrado exigirá uma biblioteca de matriz compilada (e bem otimizada!) Para levar a cabo esta etapa, de modo a não engarrafar o sistema de negociação.
O gerenciamento de riscos é outra parte extremamente importante de um sistema de comércio algorítmico. O risco pode vir de várias formas: aumento da volatilidade (embora isso possa ser visto como desejável para certas estratégias!), Aumento de correlações entre classes de ativos, contraparte padrão, interrupções do servidor, eventos de "cisnes negros" e erros não detectados no código comercial, para nomear alguns.
Os componentes de gerenciamento de risco tentam antecipar os efeitos da volatilidade excessiva e a correlação entre as classes de ativos e seus efeitos (s) subsequentes sobre o capital de negociação. Muitas vezes isso se reduz a um conjunto de cálculos estatísticos, como Monte Carlo "testes de estresse". Isso é muito semelhante às necessidades computacionais de um mecanismo de preços de derivativos e, como tal, será vinculado à CPU. Essas simulações são altamente paralelizáveis (veja abaixo) e, até certo ponto, é possível "lançar hardware no problema".
Sistemas de Execução.
O trabalho do sistema de execução é receber sinais de negociação filtrados dos componentes de construção de portfólio e gerenciamento de riscos e enviá-los para uma corretora ou outros meios de acesso ao mercado. Para a maioria das estratégias de negociação algorítmica de varejo, isso envolve uma conexão API ou FIX para uma corretora, como Interactive Brokers. As considerações primárias ao decidir sobre um idioma incluem a qualidade da API, a disponibilidade do idioma para uma API, a freqüência de execução e o deslizamento antecipado.
A "qualidade" da API refere-se ao quão bem documentado é, qual o tipo de desempenho que ele fornece, se ele precisa de um software autônomo para ser acessado ou se um gateway pode ser estabelecido de forma sem cabeça (ou seja, sem GUI). No caso dos Interactive Brokers, a ferramenta Trader WorkStation precisa ser executada em um ambiente GUI para acessar sua API. Uma vez, tive que instalar uma edição do Desktop Ubuntu em um servidor de nuvem da Amazon para acessar os corretores interativos de forma remota, apenas por esse motivo!
A maioria das APIs fornecerá uma interface C ++ e / ou Java. Geralmente, é de responsabilidade da comunidade desenvolver wrappers específicos do idioma para C #, Python, R, Excel e MatLab. Note-se que, com cada plugin adicional utilizado (especialmente os wrappers da API), há possibilidades de insetos no sistema. Sempre testar plugins desse tipo e garantir que eles sejam ativamente mantidos. Um indicador valioso é ver quantas novas atualizações de uma base de código foram feitas nos últimos meses.
A frequência de execução é de extrema importância no algoritmo de execução. Note que centenas de pedidos podem ser enviados a cada minuto e, como tal, o desempenho é crítico. Slippage será incorrido através de um sistema de execução mal executado e isso terá um impacto dramático sobre a rentabilidade.
Os idiomas estaticamente digitados (veja abaixo), como C ++ / Java, geralmente são ótimos para execução, mas há um trade-off em tempo de desenvolvimento, testes e facilidade de manutenção. Idiomas dinamicamente digitados, como Python e Perl, geralmente são geralmente "rápidos o suficiente". Certifique-se sempre de que os componentes foram projetados de forma modular (veja abaixo) para que eles possam ser "trocados" à medida que o sistema se reduz.
Processo de Planejamento e Desenvolvimento Arquitetônico.
Os componentes de um sistema de comércio, seus requisitos de freqüência e volume foram discutidos acima, mas a infraestrutura do sistema ainda não foi coberta. Aqueles que atuam como comerciante de varejo ou que trabalham em um fundo pequeno provavelmente estarão "vestindo muitos chapéus". Será necessário cobrir o modelo alfa, o gerenciamento de riscos e os parâmetros de execução, bem como a implementação final do sistema. Antes de aprofundar linguagens específicas, o design de uma arquitetura de sistema ideal será discutido.
Separação de preocupações.
Uma das decisões mais importantes que devem ser tomadas no início é como "separar as preocupações" de um sistema comercial. No desenvolvimento de software, isso significa essencialmente como dividir os diferentes aspectos do sistema de negociação em componentes modulares separados.
Ao expor as interfaces em cada um dos componentes, é fácil trocar partes do sistema por outras versões que ajudem o desempenho, confiabilidade ou manutenção, sem modificar nenhum código de dependência externo. Esta é a "melhor prática" para esses sistemas. Para estratégias em frequências mais baixas, tais práticas são aconselhadas. Para a negociação de alta freqüência, o livro de regras pode ser ignorado à custa de ajustar o sistema para ainda mais desempenho. Um sistema mais acoplado pode ser desejável.
Criar um mapa de componentes de um sistema de negociação algorítmico vale um artigo em si. No entanto, uma abordagem ótima é garantir que haja componentes separados para as entradas de dados de mercado históricos e em tempo real, armazenamento de dados, API de acesso a dados, backtester, parâmetros de estratégia, construção de portfólio, gerenciamento de riscos e sistemas de execução automatizada.
For instance, if the data store being used is currently underperforming, even at significant levels of optimisation, it can be swapped out with minimal rewrites to the data ingestion or data access API. As far the as the backtester and subsequent components are concerned, there is no difference.
Another benefit of separated components is that it allows a variety of programming languages to be used in the overall system. There is no need to be restricted to a single language if the communication method of the components is language independent. This will be the case if they are communicating via TCP/IP, ZeroMQ or some other language-independent protocol.
As a concrete example, consider the case of a backtesting system being written in C++ for "number crunching" performance, while the portfolio manager and execution systems are written in Python using SciPy and IBPy.
Performance Considerations.
Performance is a significant consideration for most trading strategies. For higher frequency strategies it is the most important factor. "Performance" covers a wide range of issues, such as algorithmic execution speed, network latency, bandwidth, data I/O, concurrency/parallelism and scaling. Each of these areas are individually covered by large textbooks, so this article will only scratch the surface of each topic. Architecture and language choice will now be discussed in terms of their effects on performance.
The prevailing wisdom as stated by Donald Knuth, one of the fathers of Computer Science, is that "premature optimisation is the root of all evil". This is almost always the case - except when building a high frequency trading algorithm! For those who are interested in lower frequency strategies, a common approach is to build a system in the simplest way possible and only optimise as bottlenecks begin to appear.
Profiling tools are used to determine where bottlenecks arise. Profiles can be made for all of the factors listed above, either in a MS Windows or Linux environment. There are many operating system and language tools available to do so, as well as third party utilities. Language choice will now be discussed in the context of performance.
C++, Java, Python, R and MatLab all contain high-performance libraries (either as part of their standard or externally) for basic data structure and algorithmic work. C++ ships with the Standard Template Library, while Python contains NumPy/SciPy. Common mathematical tasks are to be found in these libraries and it is rarely beneficial to write a new implementation.
One exception is if highly customised hardware architecture is required and an algorithm is making extensive use of proprietary extensions (such as custom caches). However, often "reinvention of the wheel" wastes time that could be better spent developing and optimising other parts of the trading infrastructure. Development time is extremely precious especially in the context of sole developers.
Latency is often an issue of the execution system as the research tools are usually situated on the same machine. For the former, latency can occur at multiple points along the execution path. Databases must be consulted (disk/network latency), signals must be generated (operating syste, kernal messaging latency), trade signals sent (NIC latency) and orders processed (exchange systems internal latency).
For higher frequency operations it is necessary to become intimately familiar with kernal optimisation as well as optimisation of network transmission. This is a deep area and is significantly beyond the scope of the article but if an UHFT algorithm is desired then be aware of the depth of knowledge required!
Caching is very useful in the toolkit of a quantitative trading developer. Caching refers to the concept of storing frequently accessed data in a manner which allows higher-performance access, at the expense of potential staleness of the data. A common use case occurs in web development when taking data from a disk-backed relational database and putting it into memory. Any subsequent requests for the data do not have to "hit the database" and so performance gains can be significant.
For trading situations caching can be extremely beneficial. For instance, the current state of a strategy portfolio can be stored in a cache until it is rebalanced, such that the list doesn't need to be regenerated upon each loop of the trading algorithm. Such regeneration is likely to be a high CPU or disk I/O operation.
However, caching is not without its own issues. Regeneration of cache data all at once, due to the volatilie nature of cache storage, can place significant demand on infrastructure. Outra questão é o empilhamento de cães, onde múltiplas gerações de uma nova cópia de cache são realizadas sob uma carga extremamente alta, o que leva a uma falha em cascata.
Dynamic memory allocation is an expensive operation in software execution. Thus it is imperative for higher performance trading applications to be well-aware how memory is being allocated and deallocated during program flow. Newer language standards such as Java, C# and Python all perform automatic garbage collection , which refers to deallocation of dynamically allocated memory when objects go out of scope .
Garbage collection is extremely useful during development as it reduces errors and aids readability. However, it is often sub-optimal for certain high frequency trading strategies. Custom garbage collection is often desired for these cases. In Java, for instance, by tuning the garbage collector and heap configuration, it is possible to obtain high performance for HFT strategies.
C++ doesn't provide a native garbage collector and so it is necessary to handle all memory allocation/deallocation as part of an object's implementation. While potentially error prone (potentially leading to dangling pointers) it is extremely useful to have fine-grained control of how objects appear on the heap for certain applications. When choosing a language make sure to study how the garbage collector works and whether it can be modified to optimise for a particular use case.
Many operations in algorithmic trading systems are amenable to parallelisation . This refers to the concept of carrying out multiple programmatic operations at the same time, i. e in "parallel". So-called "embarassingly parallel" algorithms include steps that can be computed fully independently of other steps. Certain statistical operations, such as Monte Carlo simulations, are a good example of embarassingly parallel algorithms as each random draw and subsequent path operation can be computed without knowledge of other paths.
Other algorithms are only partially parallelisable. Fluid dynamics simulations are such an example, where the domain of computation can be subdivided, but ultimately these domains must communicate with each other and thus the operations are partially sequential. Parallelisable algorithms are subject to Amdahl's Law, which provides a theoretical upper limit to the performance increase of a parallelised algorithm when subject to $N$ separate processes (e. g. on a CPU core or thread ).
Parallelisation has become increasingly important as a means of optimisation since processor clock-speeds have stagnated, as newer processors contain many cores with which to perform parallel calculations. The rise of consumer graphics hardware (predominently for video games) has lead to the development of Graphical Processing Units (GPUs), which contain hundreds of "cores" for highly concurrent operations. Such GPUs are now very affordable. High-level frameworks, such as Nvidia's CUDA have lead to widespread adoption in academia and finance.
Such GPU hardware is generally only suitable for the research aspect of quantitative finance, whereas other more specialised hardware (including Field-Programmable Gate Arrays - FPGAs) are used for (U)HFT. Nowadays, most modern langauges support a degree of concurrency/multithreading. Thus it is straightforward to optimise a backtester, since all calculations are generally independent of the others.
Scaling in software engineering and operations refers to the ability of the system to handle consistently increasing loads in the form of greater requests, higher processor usage and more memory allocation. In algorithmic trading a strategy is able to scale if it can accept larger quantities of capital and still produce consistent returns. The trading technology stack scales if it can endure larger trade volumes and increased latency, without bottlenecking .
While systems must be designed to scale, it is often hard to predict beforehand where a bottleneck will occur. Rigourous logging, testing, profiling and monitoring will aid greatly in allowing a system to scale. Languages themselves are often described as "unscalable". This is usually the result of misinformation, rather than hard fact. It is the total technology stack that should be ascertained for scalability, not the language. Clearly certain languages have greater performance than others in particular use cases, but one language is never "better" than another in every sense.
One means of managing scale is to separate concerns, as stated above. In order to further introduce the ability to handle "spikes" in the system (i. e. sudden volatility which triggers a raft of trades), it is useful to create a "message queuing architecture". This simply means placing a message queue system between components so that orders are "stacked up" if a certain component is unable to process many requests.
Rather than requests being lost they are simply kept in a stack until the message is handled. This is particularly useful for sending trades to an execution engine. If the engine is suffering under heavy latency then it will back up trades. A queue between the trade signal generator and the execution API will alleviate this issue at the expense of potential trade slippage. A well-respected open source message queue broker is RabbitMQ.
Hardware e sistemas operacionais.
The hardware running your strategy can have a significant impact on the profitability of your algorithm. This is not an issue restricted to high frequency traders either. A poor choice in hardware and operating system can lead to a machine crash or reboot at the most inopportune moment. Thus it is necessary to consider where your application will reside. The choice is generally between a personal desktop machine, a remote server, a "cloud" provider or an exchange co-located server.
Desktop machines are simple to install and administer, especially with newer user friendly operating systems such as Windows 7/8, Mac OSX and Ubuntu. Desktop systems do possess some significant drawbacks, however. The foremost is that the versions of operating systems designed for desktop machines are likely to require reboots/patching (and often at the worst of times!). They also use up more computational resources by the virtue of requiring a graphical user interface (GUI).
Utilising hardware in a home (or local office) environment can lead to internet connectivity and power uptime problems. The main benefit of a desktop system is that significant computational horsepower can be purchased for the fraction of the cost of a remote dedicated server (or cloud based system) of comparable speed.
A dedicated server or cloud-based machine, while often more expensive than a desktop option, allows for more significant redundancy infrastructure, such as automated data backups, the ability to more straightforwardly ensure uptime and remote monitoring. They are harder to administer since they require the ability to use remote login capabilities of the operating system.
In Windows this is generally via the GUI Remote Desktop Protocol (RDP). In Unix-based systems the command-line Secure SHell (SSH) is used. Unix-based server infrastructure is almost always command-line based which immediately renders GUI-based programming tools (such as MatLab or Excel) to be unusable.
A co-located server, as the phrase is used in the capital markets, is simply a dedicated server that resides within an exchange in order to reduce latency of the trading algorithm. This is absolutely necessary for certain high frequency trading strategies, which rely on low latency in order to generate alpha.
The final aspect to hardware choice and the choice of programming language is platform-independence. Is there a need for the code to run across multiple different operating systems? Is the code designed to be run on a particular type of processor architecture, such as the Intel x86/x64 or will it be possible to execute on RISC processors such as those manufactured by ARM? These issues will be highly dependent upon the frequency and type of strategy being implemented.
Resilience and Testing.
One of the best ways to lose a lot of money on algorithmic trading is to create a system with no resiliency . This refers to the durability of the sytem when subject to rare events, such as brokerage bankruptcies, sudden excess volatility, region-wide downtime for a cloud server provider or the accidental deletion of an entire trading database. Years of profits can be eliminated within seconds with a poorly-designed architecture. It is absolutely essential to consider issues such as debuggng, testing, logging, backups, high-availability and monitoring as core components of your system.
It is likely that in any reasonably complicated custom quantitative trading application at least 50% of development time will be spent on debugging, testing and maintenance.
Nearly all programming languages either ship with an associated debugger or possess well-respected third-party alternatives. In essence, a debugger allows execution of a program with insertion of arbitrary break points in the code path, which temporarily halt execution in order to investigate the state of the system. The main benefit of debugging is that it is possible to investigate the behaviour of code prior to a known crash point .
Debugging is an essential component in the toolbox for analysing programming errors. However, they are more widely used in compiled languages such as C++ or Java, as interpreted languages such as Python are often easier to debug due to fewer LOC and less verbose statements. Despite this tendency Python does ship with the pdb, which is a sophisticated debugging tool. The Microsoft Visual C++ IDE possesses extensive GUI debugging utilities, while for the command line Linux C++ programmer, the gdb debugger exists.
Testing in software development refers to the process of applying known parameters and results to specific functions, methods and objects within a codebase, in order to simulate behaviour and evaluate multiple code-paths, helping to ensure that a system behaves as it should. A more recent paradigm is known as Test Driven Development (TDD), where test code is developed against a specified interface with no implementation. Prior to the completion of the actual codebase all tests will fail. As code is written to "fill in the blanks", the tests will eventually all pass, at which point development should cease.
TDD requires extensive upfront specification design as well as a healthy degree of discipline in order to carry out successfully. In C++, Boost provides a unit testing framework. In Java, the JUnit library exists to fulfill the same purpose. Python also has the unittest module as part of the standard library. Many other languages possess unit testing frameworks and often there are multiple options.
In a production environment, sophisticated logging is absolutely essential. Logging refers to the process of outputting messages, with various degrees of severity, regarding execution behaviour of a system to a flat file or database. Logs are a "first line of attack" when hunting for unexpected program runtime behaviour. Unfortunately the shortcomings of a logging system tend only to be discovered after the fact! As with backups discussed below, a logging system should be given due consideration BEFORE a system is designed.
Both Microsoft Windows and Linux come with extensive system logging capability and programming languages tend to ship with standard logging libraries that cover most use cases. It is often wise to centralise logging information in order to analyse it at a later date, since it can often lead to ideas about improving performance or error reduction, which will almost certainly have a positive impact on your trading returns.
While logging of a system will provide information about what has transpired in the past, monitoring of an application will provide insight into what is happening right now . All aspects of the system should be considered for monitoring. System level metrics such as disk usage, available memory, network bandwidth and CPU usage provide basic load information.
Trading metrics such as abnormal prices/volume, sudden rapid drawdowns and account exposure for different sectors/markets should also be continuously monitored. Further, a threshold system should be instigated that provides notification when certain metrics are breached, elevating the notification method (email, SMS, automated phone call) depending upon the severity of the metric.
System monitoring is often the domain of the system administrator or operations manager. However, as a sole trading developer, these metrics must be established as part of the larger design. Many solutions for monitoring exist: proprietary, hosted and open source, which allow extensive customisation of metrics for a particular use case.
Backups and high availability should be prime concerns of a trading system. Consider the following two questions: 1) If an entire production database of market data and trading history was deleted (without backups) how would the research and execution algorithm be affected? 2) If the trading system suffers an outage for an extended period (with open positions) how would account equity and ongoing profitability be affected? The answers to both of these questions are often sobering!
It is imperative to put in place a system for backing up data and also for testing the restoration of such data. Many individuals do not test a restore strategy. If recovery from a crash has not been tested in a safe environment, what guarantees exist that restoration will be available at the worst possible moment?
Similarly, high availability needs to be "baked in from the start". Redundant infrastructure (even at additional expense) must always be considered, as the cost of downtime is likely to far outweigh the ongoing maintenance cost of such systems. I won't delve too deeply into this topic as it is a large area, but make sure it is one of the first considerations given to your trading system.
Choosing a Language.
Considerable detail has now been provided on the various factors that arise when developing a custom high-performance algorithmic trading system. The next stage is to discuss how programming languages are generally categorised.
Type Systems.
When choosing a language for a trading stack it is necessary to consider the type system . The languages which are of interest for algorithmic trading are either statically - or dynamically-typed . A statically-typed language performs checks of the types (e. g. integers, floats, custom classes etc) during the compilation process. Such languages include C++ and Java. A dynamically-typed language performs the majority of its type-checking at runtime. Such languages include Python, Perl and JavaScript.
For a highly numerical system such as an algorithmic trading engine, type-checking at compile time can be extremely beneficial, as it can eliminate many bugs that would otherwise lead to numerical errors. However, type-checking doesn't catch everything, and this is where exception handling comes in due to the necessity of having to handle unexpected operations. 'Dynamic' languages (i. e. those that are dynamically-typed) can often lead to run-time errors that would otherwise be caught with a compilation-time type-check. For this reason, the concept of TDD (see above) and unit testing arose which, when carried out correctly, often provides more safety than compile-time checking alone.
Another benefit of statically-typed languages is that the compiler is able to make many optimisations that are otherwise unavailable to the dynamically - typed language, simply because the type (and thus memory requirements) are known at compile-time. In fact, part of the inefficiency of many dynamically-typed languages stems from the fact that certain objects must be type-inspected at run-time and this carries a performance hit. Libraries for dynamic languages, such as NumPy/SciPy alleviate this issue due to enforcing a type within arrays.
Open Source or Proprietary?
One of the biggest choices available to an algorithmic trading developer is whether to use proprietary (commercial) or open source technologies. Existem vantagens e desvantagens para ambas as abordagens. It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensing/maintenance costs.
The Microsoft stack (including Visual C++, Visual C#) and MathWorks' MatLab are two of the larger proprietary choices for developing custom algorithmic trading software. Both tools have had significant "battle testing" in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds.
Microsoft and MathWorks both provide extensive high quality documentation for their products. Further, the communities surrounding each tool are very large with active web forums for both. The software allows cohesive integration with multiple languages such as C++, C# and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ. MatLab also has many plugins/libraries (some free, some commercial) for nearly any quantitative research domain.
There are also drawbacks. With either piece of software the costs are not insignificant for a lone trader (although Microsoft does provide entry-level version of Visual Studio for free). Microsoft tools "play well" with each other, but integrate less well with external code. Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned.
MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithmic trading. The main issue with proprietary products is the lack of availability of the source code. This means that if ultra performance is truly required, both of these tools will be far less attractive.
Open source tools have been industry grade for sometime. Much of the alternative asset space makes extensive use of open-source Linux, MySQL/PostgreSQL, Python, R, C++ and Java in high-performance production roles. However, they are far from restricted to this domain. Python and R, in particular, contain a wealth of extensive numerical libraries for performing nearly any type of data analysis imaginable, often at execution speeds comparable to compiled languages, with certain caveats.
The main benefit of using interpreted languages is the speed of development time. Python and R require far fewer lines of code (LOC) to achieve similar functionality, principally due to the extensive libraries. Além disso, eles geralmente permitem um desenvolvimento baseado em console interativo, reduzindo rapidamente o processo de desenvolvimento iterativo.
Given that time as a developer is extremely valuable, and execution speed often less so (unless in the HFT space), it is worth giving extensive consideration to an open source technology stack. Python and R possess significant development communities and are extremely well supported, due to their popularity. Documentation is excellent and bugs (at least for core libraries) remain scarce.
Open source tools often suffer from a lack of a dedicated commercial support contract and run optimally on systems with less-forgiving user interfaces. A typical Linux server (such as Ubuntu) will often be fully command-line oriented. In addition, Python and R can be slow for certain execution tasks. There are mechanisms for integrating with C++ in order to improve execution speeds, but it requires some experience in multi-language programming.
While proprietary software is not immune from dependency/versioning issues it is far less common to have to deal with incorrect library versions in such environments. Os sistemas operacionais de código aberto, como o Linux, podem ser mais difíceis de administrar.
I will venture my personal opinion here and state that I build all of my trading tools with open source technologies. In particular I use: Ubuntu, MySQL, Python, C++ and R. The maturity, community size, ability to "dig deep" if problems occur and lower total cost ownership (TCO) far outweigh the simplicity of proprietary GUIs and easier installations. Having said that, Microsoft Visual Studio (especially for C++) is a fantastic Integrated Development Environment (IDE) which I would also highly recommend.
Batteries Included?
The header of this section refers to the "out of the box" capabilities of the language - what libraries does it contain and how good are they? This is where mature languages have an advantage over newer variants. C++, Java and Python all now possess extensive libraries for network programming, HTTP, operating system interaction, GUIs, regular expressions (regex), iteration and basic algorithms.
C++ is famed for its Standard Template Library (STL) which contains a wealth of high performance data structures and algorithms "for free". Python is known for being able to communicate with nearly any other type of system/protocol (especially the web), mostly through its own standard library. R has a wealth of statistical and econometric tools built in, while MatLab is extremely optimised for any numerical linear algebra code (which can be found in portfolio optimisation and derivatives pricing, for instance).
Outside of the standard libraries, C++ makes use of the Boost library, which fills in the "missing parts" of the standard library. In fact, many parts of Boost made it into the TR1 standard and subsequently are available in the C++11 spec, including native support for lambda expressions and concurrency.
Python has the high performance NumPy/SciPy/Pandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL++ (MySQL/C++), JDBC (Java/MatLab), MySQLdb (MySQL/Python) and psychopg2 (PostgreSQL/Python). Python can even communicate with R via the RPy plugin!
An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API. Most APIs natively support C++ and Java, but some also support C# and Python, either directly or with community-provided wrapper code to the C++ APIs. In particular, Interactive Brokers can be connected to via the IBPy plugin. If high-performance is required, brokerages will support the FIX protocol.
Conclusão.
As is now evident, the choice of programming language(s) for an algorithmic trading system is not straightforward and requires deep thought. The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries.
O benefício de uma arquitetura separada é que permite que os idiomas sejam "conectados" para diferentes aspectos de uma pilha de negociação, conforme e quando os requisitos mudarem. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.
Apenas iniciando o comércio quantitativo?
3 razões para se inscrever para a lista de e-mails QuantStart:
1. Quant Trading Lessons.
Você terá acesso instantâneo a um curso de e-mail gratuito de 10 partes, repleto de sugestões e dicas para ajudá-lo a começar a negociação quantitativa!
2. Todo o conteúdo mais recente.
Todas as semanas, vou enviar-lhe um envoltório de todas as atividades no QuantStart para que você nunca mais perca uma postagem novamente.
Real, dicas de negociação viáveis, sem tonturas.
Começando: Construindo um Sistema de Negociação Totalmente Automatizado.
Nos últimos 6 meses, fiquei focado no processo de construção da pilha de tecnologia completa de um sistema de negociação automatizado. Eu encontrei muitos desafios e aprendi muito sobre os dois métodos diferentes de backtesting (Vectorizado e Evento conduzido). Na minha jornada de construção de um backtester dirigido por um evento, surpreendi que o que você acabasse fosse perto da pilha de tecnologia completa necessária para construir uma estratégia, testá-la e executar a execução ao vivo.
O meu maior problema ao abordar o problema foi a falta de conhecimento. Olhei em muitos lugares para uma introdução à construção da tecnologia ou um blog que me guiaria. Encontrei alguns recursos que vou compartilhar com você hoje.
Para iniciantes:
Para os leitores novos para negociação quantitativa, eu recomendaria o livro de Ernie P. Chan intitulado: Negociação Quantitativa: como construir seu próprio negócio de negociação algorítmica. Este livro é o básico. Na verdade, é o primeiro livro que eu li em negociação quantitativa e, mesmo assim, achei muito básico, mas há algumas notas que você deveria tomar.
Da página 81-84 Ernie escreve sobre como no nível de varejo uma arquitetura de sistema pode ser dividida em estratégias semi-automáticas e totalmente automatizadas.
Um sistema semi-automatizado é adequado se você deseja fazer alguns negócios por semana. Ernie recomenda o uso de Matlab, R ou mesmo do Excel. Utilizei todas as 3 plataformas e este é o meu conselho:
Saltei Matlab, custou muito dinheiro e eu só consegui acesso aos laboratórios universitários. Não há muito material de treinamento como blogs ou livros que irão ensinar-lhe como codificar uma estratégia usando o Matlab. R tem toneladas de recursos que você pode usar para aprender a construir uma estratégia. Meu blog favorito abordando o tópico é: QuantStratTradeR executado por Ilya Kipnis. O Microsoft Excel é provavelmente o local onde você iniciará se você não tiver experiência de programação. Você pode usar o Excel para negociação semi-automatizada, mas não vai fazer o truque quando se trata de construir a pilha de tecnologia completa.
Quadro semi-automático pg 81.
Sistemas de negociação totalmente automatizados são para quando você deseja colocar negócios automaticamente com base em um feed de dados ao vivo. Eu codifiquei o meu em C #, QuantConnect também usa C #, QuantStart anda pelo leitor através da construção dele em Python, Quantopian usa Python, HFT provavelmente usará C ++. Java também é popular.
Estrutura de negociação totalmente automatizada pg 84.
Passo 1: Obter uma vantagem.
Faça o Programa Executivo em Negociação Algorítmica oferecido pela QuantInsti. Acabei de começar o curso e o primeiro conjunto de palestras foi na arquitetura do sistema. Isso me salvaria cerca de 3 meses de pesquisa se eu tivesse começado aqui. As palestras me acompanharam por cada componente que eu precisaria, bem como uma descrição detalhada do que cada componente precisa fazer. Abaixo está uma captura de tela de uma das suas lâminas utilizadas na apresentação:
Você também pode usar esse quadro geral ao avaliar outros sistemas de negociação automática.
No momento da escrita, estou apenas na terceira semana de palestras, mas estou confiante de que um profissional poderá construir uma estratégia de negociação totalmente automatizada que, com um pouco de polonês, possa ser transformada em um hedge fund quantitativo .
Nota: o curso não está focado na construção da pilha de tecnologia.
Etapa 2: codifique um backtester baseado em eventos básicos.
O blog de Michael Hallsmore e o quantstart & amp; livro "Negociação Algorítmica de Sucesso"
Este livro possui seções dedicadas à construção de um backtester dirigido por eventos robustos. Ele dirige o leitor através de uma série de capítulos que irão explicar sua escolha de linguagem, os diferentes tipos de backtesting, a importância do backtesting dirigido a eventos e como codificar o backtester.
Michael apresenta o leitor às diferentes classes necessárias em um design orientado a objetos. Ele também ensina o leitor a construir um banco de dados mestre de valores mobiliários. É aqui que você verá como a arquitetura do sistema da QuantInsti se encaixa.
Nota: Você precisará comprar seu livro: "Successful Algorithmic Trading", seu blog deixa para fora muita informação.
Passo 3: Vire a TuringFinance.
O programa EPAT Leitura "Successful Algorithmic Trading" & amp; codificando um backtester em um idioma diferente da sua escolha.
Você deve se mudar para um blog chamado TuringFinance e ler o artigo intitulado "Algorithmic Trading System Architecture" Por: Stuart Gordon Reid. Em sua publicação, ele descreve a arquitetura seguindo as diretrizes dos padrões ISO / IEC / IEEE 42018 e padrão de descrição de arquitetura de engenharia de software.
Eu achei esta publicação muito técnica e tem algumas ótimas idéias que você deve incorporar na sua própria arquitetura.
Uma captura de tela de sua postagem.
Passo 4: Estudar sistemas de comércio aberto.
4.1) Quantopian.
Escusado será dizer que Quantopian deve ser adicionado a esta lista e estou com vergonha de dizer que não passei muito tempo usando sua plataforma (devido à minha escolha de linguagem). Quantopian tem muitas vantagens, mas as que melhoram para mim são as seguintes:
Fácil de aprender Python Acesso gratuito a muitos conjuntos de dados Uma grande comunidade e competições Eu adoro como eles hospedam QuantCon!
Quantopian é líder de mercado neste campo e é amado por quants por toda parte! Seu projeto de código aberto está sob o nome de código Zipline e isso é um pouco sobre isso:
"Zipline é o nosso motor de código aberto que alimenta o backtester no IDE. Você pode ver o repositório de códigos no Github e contribuir com solicitações de envio para o projeto. Existe um grupo do Google disponível para procurar ajuda e facilitar discussões ".
Aqui está um link para sua documentação:
4.2) QuantConnect.
Para aqueles que não estão familiarizados com a QuantConnect, eles fornecem um mecanismo de troca algorítmica de código aberto completo. Aqui está um link.
Você deve dar uma olhada em seu código, estudá-lo, & amp; dar-lhes elogios. Eles são competição de Quantopians.
Gostaria de aproveitar esta oportunidade para agradecer a equipe da QuantConnect por me deixar escolher seu cérebro e pelo brilhante serviço que eles fornecem.
Aqui está um link para sua documentação:
Observações finais:
Espero que este guia ajude os membros da comunidade. Eu queria ter essa visão 6 meses atrás, quando comecei a codificar nosso sistema.
Gostaria de chegar à comunidade e perguntar: "Quais bons cursos de negociação algorítmica você conhece?" Eu gostaria de escrever uma publicação que analisa o tópico e fornece uma classificação. Existem recomendações para a construção de um sistema de negociação totalmente automatizado que você gostaria de adicionar a esta publicação?
Compartilhar isso:
Compartilhe essa entrada.
Você pode gostar também.
Bom artigo. Eu gostaria de ter tido cerca de 6 meses atrás. Eu uso QuantConnect porque sou um programador C #. Achei muito conveniente poder fazer o download do teste Lean e back test localmente. Rummaging através do seu código também é valioso. Além disso, eles cortaram um acordo com a Trader por negócios de US $ 1. Isso ajuda muito. Não sou tão saliente sobre spreads e execução da Trader. O IB pode ser melhor para isso.
Vou dar uma olhada no curso que você mencionou.
Você não mencionou a Quantocracy ou RBloggers. Ambos são recursos muito valiosos.
O que você usa para traçar resultados de testes de volta? Eu logro os valores do OHLC e do indicador para csv do evento OnData e estou realmente cansado de usar o Excel para traçar os resultados. Gostaria de apontar um pacote de gráficos para um arquivo de dados e simplesmente ir.
Você ainda possui um fornecedor de caixas de seleção?
Tenho um pensamento sobre os sistemas dirigidos a eventos. O problema com os eventos é que eles são assíncronos e latentes. Parece que eles são inevitáveis assim que você obtém uma corretora envolvida, então eu tenho sonhado com um sistema de streaming mais seguindo os princípios da programação funcional.
& # 8211; Injeste um fluxo de tiquetaque ou barra.
& # 8211; Execute-o através de um processo de cálculo de indicadores, execução de análise ou ML, e assim por diante.
& # 8211; Retornar um sinal.
& # 8211; Envie-o para o corretor para executar.
Em seguida, em um fluxo separado.
& # 8211; Receba uma resposta do corretor.
O problema, é claro, é o estado. Tenho margem suficiente para fazer o comércio? O que está no meu portfólio? Como está funcionando? Normalmente, o corretor api pode ser consultado para descobrir essas coisas, mas leva tempo e é assíncrono. Eu também estou olhando extensões Rx. Dessa forma, o sistema pode reagir às mudanças no sistema através do padrão observável.
Os eventos são ótimos para cliques no mouse. Não é tão bom para processamento transacional de alto volume.
Esta é exatamente a abordagem que tomei com minhas próprias coisas. Essencialmente, eu tenho um & # 8216; normal & # 8217; programa que envolve uma pequena parte que é conduzida a eventos para falar com o corretor (IB API). Agora, para o problema do estado. Você tem duas escolhas; obter o estado do corretor, ou armazená-lo internamente, atualizando-o quando você receber um preenchimento. Isso significa que há momentos em que você não conhece seu estado ou quando as duas fontes de estado estão potencialmente em conflito (dados ruins ou atrasos). Parte disso depende da rapidez com que você troca. A menos que você esteja negociando com muita rapidez, então, pausando se você tiver um conflito de estado, ou você está incerto de estado, é melhor do que prosseguir sem saber o seu estado. Eu uso um banco de dados & # 8216; lock & # 8217; paradigma para lidar com isso.
Quanto a quase tudo o que você pediu, você está perto da resposta em Reactive Extension (Rx).
Com Rx indo de tiques para velas é trivial.
Passar de Velas para Indicadores é trivial.
Indicadores de composição de outros indicadores é trivial.
Escrever Posições de Indicadores é trivial.
Composição de Portfolios (como realizada ao longo do tempo) das Posições é trivial.
Simular o modelo de risco é trivial.
Back testing ou trading live é simplesmente decidir entre uma transmissão ao vivo de dados ou uma repetição simulada de dados do banco de dados.
Executar é trivial.
A implementação é possível em tudo, desde C # até F # para JavaScript para C ++ em código quase idêntico.
A otimização é feita rapidamente porque o Rx puramente funcional é massivamente paralisável ao GPU.
É certo que a otimização e a alimentação do efeito da otimização contínua de volta ao teste de back-back não é trivial, mas dado que não é trivial de qualquer maneira, eu irei deixar esse slide 😉
Puramente funcional (ou perto dela) A Rx é, na minha opinião, a única maneira de abordar a infraestrutura desse problema.
Conheço o sistema que quero negociar. Eu não quero programar ou aprender algo que alguém já conhece. Então, quem posso contratar para levar o sistema que eu quero usar e automatizá-lo. Por automatizar isso, quero dizer, eu não quero olhar para ele. Eu vou olhar os resultados uma vez por semana e os negócios serão executados sem a minha atenção. Parece estranho para mim que, em 2018, tanto esforço precisa tomar um conjunto de regras e ter essas regras executadas no meu corretor.
Eu sugeriria inscrever-se com o Quantopian e depois encontrar alguém dentro da comunidade lá para construir a estratégia para você. Eles serão capazes de construí-lo para você dentro da plataforma IB Brokers e ser totalmente automatizado.
Deixe-me dizer, porém, que acho que você deve monitorá-lo de perto, e não apenas "esqueça-o para" # 8221 ;.
QuantStart.
Junte-se ao portal de membros privados da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento. Você encontrará um grupo bem informado de mentalistas quant pronto para responder suas perguntas comerciais mais importantes.
Confira meu ebook sobre o comércio de quant, onde eu ensino você como criar estratégias de negociação sistemáticas lucrativas com ferramentas Python, desde o início.
Dê uma olhada no meu novo ebook sobre estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas bayesianas, com Python e R.
By Michael Halls-Moore on July 26th, 2018.
One of the most frequent questions I receive in the QS mailbag is "What is the best programming language for algorithmic trading?". The short answer is that there is no "best" language. Strategy parameters, performance, modularity, development, resiliency and cost must all be considered. This article will outline the necessary components of an algorithmic trading system architecture and how decisions regarding implementation affect the choice of language.
Firstly, the major components of an algorithmic trading system will be considered, such as the research tools, portfolio optimiser, risk manager and execution engine. Subsequently, different trading strategies will be examined and how they affect the design of the system. In particular the frequency of trading and the likely trading volume will both be discussed.
Uma vez que a estratégia de negociação foi selecionada, é necessário arquitetar todo o sistema. This includes choice of hardware, the operating system(s) and system resiliency against rare, potentially catastrophic events. While the architecture is being considered, due regard must be paid to performance - both to the research tools as well as the live execution environment.
What Is The Trading System Trying To Do?
Before deciding on the "best" language with which to write an automated trading system it is necessary to define the requirements. Is the system going to be purely execution based? Will the system require a risk management or portfolio construction module? Will the system require a high-performance backtester? For most strategies the trading system can be partitioned into two categories: Research and signal generation.
Research is concerned with evaluation of a strategy performance over historical data. The process of evaluating a trading strategy over prior market data is known as backtesting . The data size and algorithmic complexity will have a big impact on the computational intensity of the backtester. CPU speed and concurrency are often the limiting factors in optimising research execution speed.
Signal generation is concerned with generating a set of trading signals from an algorithm and sending such orders to the market, usually via a brokerage. For certain strategies a high level of performance is required. I/O issues such as network bandwidth and latency are often the limiting factor in optimising execution systems. Thus the choice of languages for each component of your entire system may be quite different.
Type, Frequency and Volume of Strategy.
The type of algorithmic strategy employed will have a substantial impact on the design of the system. It will be necessary to consider the markets being traded, the connectivity to external data vendors, the frequency and volume of the strategy, the trade-off between ease of development and performance optimisation, as well as any custom hardware, including co-located custom servers, GPUs or FPGAs that might be necessary.
The technology choices for a low-frequency US equities strategy will be vastly different from those of a high-frequency statistical arbitrage strategy trading on the futures market. Prior to the choice of language many data vendors must be evaluated that pertain to a the strategy at hand.
It will be necessary to consider connectivity to the vendor, structure of any APIs, timeliness of the data, storage requirements and resiliency in the face of a vendor going offline. It is also wise to possess rapid access to multiple vendors! Various instruments all have their own storage quirks, examples of which include multiple ticker symbols for equities and expiration dates for futures (not to mention any specific OTC data). This needs to be factored in to the platform design.
A frequência da estratégia provavelmente será um dos maiores drivers de como a pilha de tecnologia será definida. Strategies employing data more frequently than minutely or secondly bars require significant consideration with regards to performance.
A strategy exceeding secondly bars (i. e. tick data) leads to a performance driven design as the primary requirement. For high frequency strategies a substantial amount of market data will need to be stored and evaluated. Software such as HDF5 or kdb+ are commonly used for these roles.
In order to process the extensive volumes of data needed for HFT applications, an extensively optimised backtester and execution system must be used. C/C++ (possibly with some assembler) is likely to the strongest language candidate. Ultra-high frequency strategies will almost certainly require custom hardware such as FPGAs, exchange co-location and kernal/network interface tuning.
Research Systems.
Research systems typically involve a mixture of interactive development and automated scripting. The former often takes place within an IDE such as Visual Studio, MatLab or R Studio. The latter involves extensive numerical calculations over numerous parameters and data points. This leads to a language choice providing a straightforward environment to test code, but also provides sufficient performance to evaluate strategies over multiple parameter dimensions.
Typical IDEs in this space include Microsoft Visual C++/C#, which contains extensive debugging utilities, code completion capabilities (via "Intellisense") and straightforward overviews of the entire project stack (via the database ORM, LINQ); MatLab, which is designed for extensive numerical linear algebra and vectorised operations, but in an interactive console manner; R Studio, which wraps the R statistical language console in a fully-fledged IDE; Eclipse IDE for Linux Java and C++; and semi-proprietary IDEs such as Enthought Canopy for Python, which include data analysis libraries such as NumPy, SciPy, scikit-learn and pandas in a single interactive (console) environment.
For numerical backtesting, all of the above languages are suitable, although it is not necessary to utilise a GUI/IDE as the code will be executed "in the background". The prime consideration at this stage is that of execution speed. A compiled language (such as C++) is often useful if the backtesting parameter dimensions are large. Remember that it is necessary to be wary of such systems if that is the case!
Interpreted languages such as Python often make use of high-performance libraries such as NumPy/pandas for the backtesting step, in order to maintain a reasonable degree of competitiveness with compiled equivalents. Ultimately the language chosen for the backtesting will be determined by specific algorithmic needs as well as the range of libraries available in the language (more on that below). However, the language used for the backtester and research environments can be completely independent of those used in the portfolio construction, risk management and execution components, as will be seen.
Portfolio Construction and Risk Management.
The portfolio construction and risk management components are often overlooked by retail algorithmic traders. This is almost always a mistake. These tools provide the mechanism by which capital will be preserved. They not only attempt to alleviate the number of "risky" bets, but also minimise churn of the trades themselves, reducing transaction costs.
Sophisticated versions of these components can have a significant effect on the quality and consistentcy of profitability. It is straightforward to create a stable of strategies as the portfolio construction mechanism and risk manager can easily be modified to handle multiple systems. Thus they should be considered essential components at the outset of the design of an algorithmic trading system.
The job of the portfolio construction system is to take a set of desired trades and produce the set of actual trades that minimise churn, maintain exposures to various factors (such as sectors, asset classes, volatility etc) and optimise the allocation of capital to various strategies in a portfolio.
Portfolio construction often reduces to a linear algebra problem (such as a matrix factorisation) and hence performance is highly dependent upon the effectiveness of the numerical linear algebra implementation available. Common libraries include uBLAS, LAPACK and NAG for C++. MatLab also possesses extensively optimised matrix operations. Python utilises NumPy/SciPy for such computations. A frequently rebalanced portfolio will require a compiled (and well optimised!) matrix library to carry this step out, so as not to bottleneck the trading system.
Risk management is another extremely important part of an algorithmic trading system. Risk can come in many forms: Increased volatility (although this may be seen as desirable for certain strategies!), increased correlations between asset classes, counter-party default, server outages, "black swan" events and undetected bugs in the trading code, to name a few.
Risk management components try and anticipate the effects of excessive volatility and correlation between asset classes and their subsequent effect(s) on trading capital. Often this reduces to a set of statistical computations such as Monte Carlo "stress tests". This is very similar to the computational needs of a derivatives pricing engine and as such will be CPU-bound. These simulations are highly parallelisable (see below) and, to a certain degree, it is possible to "throw hardware at the problem".
Sistemas de Execução.
The job of the execution system is to receive filtered trading signals from the portfolio construction and risk management components and send them on to a brokerage or other means of market access. For the majority of retail algorithmic trading strategies this involves an API or FIX connection to a brokerage such as Interactive Brokers. The primary considerations when deciding upon a language include quality of the API, language-wrapper availability for an API, execution frequency and the anticipated slippage.
The "quality" of the API refers to how well documented it is, what sort of performance it provides, whether it needs standalone software to be accessed or whether a gateway can be established in a headless fashion (i. e. no GUI). In the case of Interactive Brokers, the Trader WorkStation tool needs to be running in a GUI environment in order to access their API. I once had to install a Desktop Ubuntu edition onto an Amazon cloud server to access Interactive Brokers remotely, purely for this reason!
Most APIs will provide a C++ and/or Java interface. It is usually up to the community to develop language-specific wrappers for C#, Python, R, Excel and MatLab. Note that with every additional plugin utilised (especially API wrappers) there is scope for bugs to creep into the system. Always test plugins of this sort and ensure they are actively maintained. A worthwhile gauge is to see how many new updates to a codebase have been made in recent months.
Execution frequency is of the utmost importance in the execution algorithm. Note that hundreds of orders may be sent every minute and as such performance is critical. Slippage will be incurred through a badly-performing execution system and this will have a dramatic impact on profitability.
Statically-typed languages (see below) such as C++/Java are generally optimal for execution but there is a trade-off in development time, testing and ease of maintenance. Dynamically-typed languages, such as Python and Perl are now generally "fast enough". Always make sure the components are designed in a modular fashion (see below) so that they can be "swapped out" out as the system scales.
Architectural Planning and Development Process.
The components of a trading system, its frequency and volume requirements have been discussed above, but system infrastructure has yet to be covered. Those acting as a retail trader or working in a small fund will likely be "wearing many hats". It will be necessary to be covering the alpha model, risk management and execution parameters, and also the final implementation of the system. Before delving into specific languages the design of an optimal system architecture will be discussed.
Separation of Concerns.
One of the most important decisions that must be made at the outset is how to "separate the concerns" of a trading system. No desenvolvimento de software, isso significa essencialmente como dividir os diferentes aspectos do sistema de negociação em componentes modulares separados.
By exposing interfaces at each of the components it is easy to swap out parts of the system for other versions that aid performance, reliability or maintenance, without modifying any external dependency code. This is the "best practice" for such systems. For strategies at lower frequencies such practices are advised. For ultra high frequency trading the rulebook might have to be ignored at the expense of tweaking the system for even more performance. A more tightly coupled system may be desirable.
Creating a component map of an algorithmic trading system is worth an article in itself. However, an optimal approach is to make sure there are separate components for the historical and real-time market data inputs, data storage, data access API, backtester, strategy parameters, portfolio construction, risk management and automated execution systems.
For instance, if the data store being used is currently underperforming, even at significant levels of optimisation, it can be swapped out with minimal rewrites to the data ingestion or data access API. As far the as the backtester and subsequent components are concerned, there is no difference.
Another benefit of separated components is that it allows a variety of programming languages to be used in the overall system. There is no need to be restricted to a single language if the communication method of the components is language independent. This will be the case if they are communicating via TCP/IP, ZeroMQ or some other language-independent protocol.
As a concrete example, consider the case of a backtesting system being written in C++ for "number crunching" performance, while the portfolio manager and execution systems are written in Python using SciPy and IBPy.
Performance Considerations.
Performance is a significant consideration for most trading strategies. For higher frequency strategies it is the most important factor. "Performance" covers a wide range of issues, such as algorithmic execution speed, network latency, bandwidth, data I/O, concurrency/parallelism and scaling. Each of these areas are individually covered by large textbooks, so this article will only scratch the surface of each topic. Architecture and language choice will now be discussed in terms of their effects on performance.
The prevailing wisdom as stated by Donald Knuth, one of the fathers of Computer Science, is that "premature optimisation is the root of all evil". This is almost always the case - except when building a high frequency trading algorithm! For those who are interested in lower frequency strategies, a common approach is to build a system in the simplest way possible and only optimise as bottlenecks begin to appear.
Profiling tools are used to determine where bottlenecks arise. Profiles can be made for all of the factors listed above, either in a MS Windows or Linux environment. There are many operating system and language tools available to do so, as well as third party utilities. Language choice will now be discussed in the context of performance.
C++, Java, Python, R and MatLab all contain high-performance libraries (either as part of their standard or externally) for basic data structure and algorithmic work. C++ ships with the Standard Template Library, while Python contains NumPy/SciPy. Common mathematical tasks are to be found in these libraries and it is rarely beneficial to write a new implementation.
One exception is if highly customised hardware architecture is required and an algorithm is making extensive use of proprietary extensions (such as custom caches). However, often "reinvention of the wheel" wastes time that could be better spent developing and optimising other parts of the trading infrastructure. Development time is extremely precious especially in the context of sole developers.
Latency is often an issue of the execution system as the research tools are usually situated on the same machine. For the former, latency can occur at multiple points along the execution path. Databases must be consulted (disk/network latency), signals must be generated (operating syste, kernal messaging latency), trade signals sent (NIC latency) and orders processed (exchange systems internal latency).
For higher frequency operations it is necessary to become intimately familiar with kernal optimisation as well as optimisation of network transmission. This is a deep area and is significantly beyond the scope of the article but if an UHFT algorithm is desired then be aware of the depth of knowledge required!
Caching is very useful in the toolkit of a quantitative trading developer. Caching refers to the concept of storing frequently accessed data in a manner which allows higher-performance access, at the expense of potential staleness of the data. A common use case occurs in web development when taking data from a disk-backed relational database and putting it into memory. Any subsequent requests for the data do not have to "hit the database" and so performance gains can be significant.
For trading situations caching can be extremely beneficial. For instance, the current state of a strategy portfolio can be stored in a cache until it is rebalanced, such that the list doesn't need to be regenerated upon each loop of the trading algorithm. Such regeneration is likely to be a high CPU or disk I/O operation.
However, caching is not without its own issues. Regeneration of cache data all at once, due to the volatilie nature of cache storage, can place significant demand on infrastructure. Outra questão é o empilhamento de cães, onde múltiplas gerações de uma nova cópia de cache são realizadas sob uma carga extremamente alta, o que leva a uma falha em cascata.
Dynamic memory allocation is an expensive operation in software execution. Thus it is imperative for higher performance trading applications to be well-aware how memory is being allocated and deallocated during program flow. Newer language standards such as Java, C# and Python all perform automatic garbage collection , which refers to deallocation of dynamically allocated memory when objects go out of scope .
Garbage collection is extremely useful during development as it reduces errors and aids readability. However, it is often sub-optimal for certain high frequency trading strategies. Custom garbage collection is often desired for these cases. In Java, for instance, by tuning the garbage collector and heap configuration, it is possible to obtain high performance for HFT strategies.
C++ doesn't provide a native garbage collector and so it is necessary to handle all memory allocation/deallocation as part of an object's implementation. While potentially error prone (potentially leading to dangling pointers) it is extremely useful to have fine-grained control of how objects appear on the heap for certain applications. When choosing a language make sure to study how the garbage collector works and whether it can be modified to optimise for a particular use case.
Many operations in algorithmic trading systems are amenable to parallelisation . This refers to the concept of carrying out multiple programmatic operations at the same time, i. e in "parallel". So-called "embarassingly parallel" algorithms include steps that can be computed fully independently of other steps. Certain statistical operations, such as Monte Carlo simulations, are a good example of embarassingly parallel algorithms as each random draw and subsequent path operation can be computed without knowledge of other paths.
Other algorithms are only partially parallelisable. Fluid dynamics simulations are such an example, where the domain of computation can be subdivided, but ultimately these domains must communicate with each other and thus the operations are partially sequential. Parallelisable algorithms are subject to Amdahl's Law, which provides a theoretical upper limit to the performance increase of a parallelised algorithm when subject to $N$ separate processes (e. g. on a CPU core or thread ).
Parallelisation has become increasingly important as a means of optimisation since processor clock-speeds have stagnated, as newer processors contain many cores with which to perform parallel calculations. The rise of consumer graphics hardware (predominently for video games) has lead to the development of Graphical Processing Units (GPUs), which contain hundreds of "cores" for highly concurrent operations. Such GPUs are now very affordable. High-level frameworks, such as Nvidia's CUDA have lead to widespread adoption in academia and finance.
Such GPU hardware is generally only suitable for the research aspect of quantitative finance, whereas other more specialised hardware (including Field-Programmable Gate Arrays - FPGAs) are used for (U)HFT. Nowadays, most modern langauges support a degree of concurrency/multithreading. Thus it is straightforward to optimise a backtester, since all calculations are generally independent of the others.
Scaling in software engineering and operations refers to the ability of the system to handle consistently increasing loads in the form of greater requests, higher processor usage and more memory allocation. In algorithmic trading a strategy is able to scale if it can accept larger quantities of capital and still produce consistent returns. The trading technology stack scales if it can endure larger trade volumes and increased latency, without bottlenecking .
While systems must be designed to scale, it is often hard to predict beforehand where a bottleneck will occur. Rigourous logging, testing, profiling and monitoring will aid greatly in allowing a system to scale. Languages themselves are often described as "unscalable". This is usually the result of misinformation, rather than hard fact. It is the total technology stack that should be ascertained for scalability, not the language. Clearly certain languages have greater performance than others in particular use cases, but one language is never "better" than another in every sense.
One means of managing scale is to separate concerns, as stated above. In order to further introduce the ability to handle "spikes" in the system (i. e. sudden volatility which triggers a raft of trades), it is useful to create a "message queuing architecture". This simply means placing a message queue system between components so that orders are "stacked up" if a certain component is unable to process many requests.
Rather than requests being lost they are simply kept in a stack until the message is handled. This is particularly useful for sending trades to an execution engine. If the engine is suffering under heavy latency then it will back up trades. A queue between the trade signal generator and the execution API will alleviate this issue at the expense of potential trade slippage. A well-respected open source message queue broker is RabbitMQ.
Hardware e sistemas operacionais.
The hardware running your strategy can have a significant impact on the profitability of your algorithm. This is not an issue restricted to high frequency traders either. A poor choice in hardware and operating system can lead to a machine crash or reboot at the most inopportune moment. Thus it is necessary to consider where your application will reside. The choice is generally between a personal desktop machine, a remote server, a "cloud" provider or an exchange co-located server.
Desktop machines are simple to install and administer, especially with newer user friendly operating systems such as Windows 7/8, Mac OSX and Ubuntu. Desktop systems do possess some significant drawbacks, however. The foremost is that the versions of operating systems designed for desktop machines are likely to require reboots/patching (and often at the worst of times!). They also use up more computational resources by the virtue of requiring a graphical user interface (GUI).
Utilising hardware in a home (or local office) environment can lead to internet connectivity and power uptime problems. The main benefit of a desktop system is that significant computational horsepower can be purchased for the fraction of the cost of a remote dedicated server (or cloud based system) of comparable speed.
A dedicated server or cloud-based machine, while often more expensive than a desktop option, allows for more significant redundancy infrastructure, such as automated data backups, the ability to more straightforwardly ensure uptime and remote monitoring. They are harder to administer since they require the ability to use remote login capabilities of the operating system.
In Windows this is generally via the GUI Remote Desktop Protocol (RDP). In Unix-based systems the command-line Secure SHell (SSH) is used. Unix-based server infrastructure is almost always command-line based which immediately renders GUI-based programming tools (such as MatLab or Excel) to be unusable.
A co-located server, as the phrase is used in the capital markets, is simply a dedicated server that resides within an exchange in order to reduce latency of the trading algorithm. This is absolutely necessary for certain high frequency trading strategies, which rely on low latency in order to generate alpha.
The final aspect to hardware choice and the choice of programming language is platform-independence. Is there a need for the code to run across multiple different operating systems? Is the code designed to be run on a particular type of processor architecture, such as the Intel x86/x64 or will it be possible to execute on RISC processors such as those manufactured by ARM? These issues will be highly dependent upon the frequency and type of strategy being implemented.
Resilience and Testing.
One of the best ways to lose a lot of money on algorithmic trading is to create a system with no resiliency . This refers to the durability of the sytem when subject to rare events, such as brokerage bankruptcies, sudden excess volatility, region-wide downtime for a cloud server provider or the accidental deletion of an entire trading database. Years of profits can be eliminated within seconds with a poorly-designed architecture. It is absolutely essential to consider issues such as debuggng, testing, logging, backups, high-availability and monitoring as core components of your system.
It is likely that in any reasonably complicated custom quantitative trading application at least 50% of development time will be spent on debugging, testing and maintenance.
Nearly all programming languages either ship with an associated debugger or possess well-respected third-party alternatives. In essence, a debugger allows execution of a program with insertion of arbitrary break points in the code path, which temporarily halt execution in order to investigate the state of the system. The main benefit of debugging is that it is possible to investigate the behaviour of code prior to a known crash point .
Debugging is an essential component in the toolbox for analysing programming errors. However, they are more widely used in compiled languages such as C++ or Java, as interpreted languages such as Python are often easier to debug due to fewer LOC and less verbose statements. Despite this tendency Python does ship with the pdb, which is a sophisticated debugging tool. The Microsoft Visual C++ IDE possesses extensive GUI debugging utilities, while for the command line Linux C++ programmer, the gdb debugger exists.
Testing in software development refers to the process of applying known parameters and results to specific functions, methods and objects within a codebase, in order to simulate behaviour and evaluate multiple code-paths, helping to ensure that a system behaves as it should. A more recent paradigm is known as Test Driven Development (TDD), where test code is developed against a specified interface with no implementation. Prior to the completion of the actual codebase all tests will fail. As code is written to "fill in the blanks", the tests will eventually all pass, at which point development should cease.
TDD requires extensive upfront specification design as well as a healthy degree of discipline in order to carry out successfully. In C++, Boost provides a unit testing framework. In Java, the JUnit library exists to fulfill the same purpose. Python also has the unittest module as part of the standard library. Many other languages possess unit testing frameworks and often there are multiple options.
In a production environment, sophisticated logging is absolutely essential. Logging refers to the process of outputting messages, with various degrees of severity, regarding execution behaviour of a system to a flat file or database. Logs are a "first line of attack" when hunting for unexpected program runtime behaviour. Unfortunately the shortcomings of a logging system tend only to be discovered after the fact! As with backups discussed below, a logging system should be given due consideration BEFORE a system is designed.
Both Microsoft Windows and Linux come with extensive system logging capability and programming languages tend to ship with standard logging libraries that cover most use cases. It is often wise to centralise logging information in order to analyse it at a later date, since it can often lead to ideas about improving performance or error reduction, which will almost certainly have a positive impact on your trading returns.
While logging of a system will provide information about what has transpired in the past, monitoring of an application will provide insight into what is happening right now . All aspects of the system should be considered for monitoring. System level metrics such as disk usage, available memory, network bandwidth and CPU usage provide basic load information.
Trading metrics such as abnormal prices/volume, sudden rapid drawdowns and account exposure for different sectors/markets should also be continuously monitored. Further, a threshold system should be instigated that provides notification when certain metrics are breached, elevating the notification method (email, SMS, automated phone call) depending upon the severity of the metric.
System monitoring is often the domain of the system administrator or operations manager. However, as a sole trading developer, these metrics must be established as part of the larger design. Many solutions for monitoring exist: proprietary, hosted and open source, which allow extensive customisation of metrics for a particular use case.
Backups and high availability should be prime concerns of a trading system. Consider the following two questions: 1) If an entire production database of market data and trading history was deleted (without backups) how would the research and execution algorithm be affected? 2) If the trading system suffers an outage for an extended period (with open positions) how would account equity and ongoing profitability be affected? The answers to both of these questions are often sobering!
It is imperative to put in place a system for backing up data and also for testing the restoration of such data. Many individuals do not test a restore strategy. If recovery from a crash has not been tested in a safe environment, what guarantees exist that restoration will be available at the worst possible moment?
Similarly, high availability needs to be "baked in from the start". Redundant infrastructure (even at additional expense) must always be considered, as the cost of downtime is likely to far outweigh the ongoing maintenance cost of such systems. I won't delve too deeply into this topic as it is a large area, but make sure it is one of the first considerations given to your trading system.
Choosing a Language.
Considerable detail has now been provided on the various factors that arise when developing a custom high-performance algorithmic trading system. The next stage is to discuss how programming languages are generally categorised.
Type Systems.
When choosing a language for a trading stack it is necessary to consider the type system . The languages which are of interest for algorithmic trading are either statically - or dynamically-typed . A statically-typed language performs checks of the types (e. g. integers, floats, custom classes etc) during the compilation process. Such languages include C++ and Java. A dynamically-typed language performs the majority of its type-checking at runtime. Such languages include Python, Perl and JavaScript.
For a highly numerical system such as an algorithmic trading engine, type-checking at compile time can be extremely beneficial, as it can eliminate many bugs that would otherwise lead to numerical errors. However, type-checking doesn't catch everything, and this is where exception handling comes in due to the necessity of having to handle unexpected operations. 'Dynamic' languages (i. e. those that are dynamically-typed) can often lead to run-time errors that would otherwise be caught with a compilation-time type-check. For this reason, the concept of TDD (see above) and unit testing arose which, when carried out correctly, often provides more safety than compile-time checking alone.
Another benefit of statically-typed languages is that the compiler is able to make many optimisations that are otherwise unavailable to the dynamically - typed language, simply because the type (and thus memory requirements) are known at compile-time. In fact, part of the inefficiency of many dynamically-typed languages stems from the fact that certain objects must be type-inspected at run-time and this carries a performance hit. Libraries for dynamic languages, such as NumPy/SciPy alleviate this issue due to enforcing a type within arrays.
Open Source or Proprietary?
One of the biggest choices available to an algorithmic trading developer is whether to use proprietary (commercial) or open source technologies. Existem vantagens e desvantagens para ambas as abordagens. It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensing/maintenance costs.
The Microsoft stack (including Visual C++, Visual C#) and MathWorks' MatLab are two of the larger proprietary choices for developing custom algorithmic trading software. Both tools have had significant "battle testing" in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds.
Microsoft and MathWorks both provide extensive high quality documentation for their products. Further, the communities surrounding each tool are very large with active web forums for both. The software allows cohesive integration with multiple languages such as C++, C# and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ. MatLab also has many plugins/libraries (some free, some commercial) for nearly any quantitative research domain.
There are also drawbacks. With either piece of software the costs are not insignificant for a lone trader (although Microsoft does provide entry-level version of Visual Studio for free). Microsoft tools "play well" with each other, but integrate less well with external code. Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned.
MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithmic trading. The main issue with proprietary products is the lack of availability of the source code. This means that if ultra performance is truly required, both of these tools will be far less attractive.
Open source tools have been industry grade for sometime. Much of the alternative asset space makes extensive use of open-source Linux, MySQL/PostgreSQL, Python, R, C++ and Java in high-performance production roles. However, they are far from restricted to this domain. Python and R, in particular, contain a wealth of extensive numerical libraries for performing nearly any type of data analysis imaginable, often at execution speeds comparable to compiled languages, with certain caveats.
The main benefit of using interpreted languages is the speed of development time. Python and R require far fewer lines of code (LOC) to achieve similar functionality, principally due to the extensive libraries. Além disso, eles geralmente permitem um desenvolvimento baseado em console interativo, reduzindo rapidamente o processo de desenvolvimento iterativo.
Given that time as a developer is extremely valuable, and execution speed often less so (unless in the HFT space), it is worth giving extensive consideration to an open source technology stack. Python and R possess significant development communities and are extremely well supported, due to their popularity. Documentation is excellent and bugs (at least for core libraries) remain scarce.
Open source tools often suffer from a lack of a dedicated commercial support contract and run optimally on systems with less-forgiving user interfaces. A typical Linux server (such as Ubuntu) will often be fully command-line oriented. In addition, Python and R can be slow for certain execution tasks. There are mechanisms for integrating with C++ in order to improve execution speeds, but it requires some experience in multi-language programming.
While proprietary software is not immune from dependency/versioning issues it is far less common to have to deal with incorrect library versions in such environments. Os sistemas operacionais de código aberto, como o Linux, podem ser mais difíceis de administrar.
I will venture my personal opinion here and state that I build all of my trading tools with open source technologies. In particular I use: Ubuntu, MySQL, Python, C++ and R. The maturity, community size, ability to "dig deep" if problems occur and lower total cost ownership (TCO) far outweigh the simplicity of proprietary GUIs and easier installations. Having said that, Microsoft Visual Studio (especially for C++) is a fantastic Integrated Development Environment (IDE) which I would also highly recommend.
Batteries Included?
The header of this section refers to the "out of the box" capabilities of the language - what libraries does it contain and how good are they? This is where mature languages have an advantage over newer variants. C++, Java and Python all now possess extensive libraries for network programming, HTTP, operating system interaction, GUIs, regular expressions (regex), iteration and basic algorithms.
C++ is famed for its Standard Template Library (STL) which contains a wealth of high performance data structures and algorithms "for free". Python is known for being able to communicate with nearly any other type of system/protocol (especially the web), mostly through its own standard library. R has a wealth of statistical and econometric tools built in, while MatLab is extremely optimised for any numerical linear algebra code (which can be found in portfolio optimisation and derivatives pricing, for instance).
Outside of the standard libraries, C++ makes use of the Boost library, which fills in the "missing parts" of the standard library. In fact, many parts of Boost made it into the TR1 standard and subsequently are available in the C++11 spec, including native support for lambda expressions and concurrency.
Python has the high performance NumPy/SciPy/Pandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL++ (MySQL/C++), JDBC (Java/MatLab), MySQLdb (MySQL/Python) and psychopg2 (PostgreSQL/Python). Python can even communicate with R via the RPy plugin!
An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API. Most APIs natively support C++ and Java, but some also support C# and Python, either directly or with community-provided wrapper code to the C++ APIs. In particular, Interactive Brokers can be connected to via the IBPy plugin. If high-performance is required, brokerages will support the FIX protocol.
Conclusão.
As is now evident, the choice of programming language(s) for an algorithmic trading system is not straightforward and requires deep thought. The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries.
O benefício de uma arquitetura separada é que permite que os idiomas sejam "conectados" para diferentes aspectos de uma pilha de negociação, conforme e quando os requisitos mudarem. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.
Apenas iniciando o comércio quantitativo?
3 razões para se inscrever para a lista de e-mails QuantStart:
1. Quant Trading Lessons.
Você terá acesso instantâneo a um curso de e-mail gratuito de 10 partes, repleto de sugestões e dicas para ajudá-lo a começar a negociação quantitativa!
2. Todo o conteúdo mais recente.
Todas as semanas, vou enviar-lhe um envoltório de todas as atividades no QuantStart para que você nunca mais perca uma postagem novamente.
Real, dicas de negociação viáveis, sem tonturas.
Комментарии
Отправить комментарий