Thursday 19 April 2018

Melhor linguagem de programação para sistemas de negociação algorítmica


Melhor linguagem de programação para sistemas de negociação algorítmica
Obter através da App Store Leia esta publicação em nosso aplicativo!
Linguagem de programação quantitativa de finanças.
Desde algumas semanas, comecei a fazer minhas pesquisas sobre financiamento quantitativo. Durante este tempo, eu poderia descobrir muitas coisas e com essas coisas, muitas perguntas me vieram à minha mente. Muitas notícias ou revistas econômicas / revistas escrevem sobre HFT / Algorithmic trading. A maioria diz que as empresas ou desenvolvedores de software preferem usar o C ++. Em alguns artigos, os escritores falam sobre Java, C #, C ou mesmo ASM. Eu tentei encontrar o motivo do C ++, mas não tive sucesso. Este tópico não fornece respostas que eu preciso (Por que o C ++ ainda é uma linguagem muito popular em financiamento quantitativo?)
Aqui estão as minhas perguntas: 1. Por que C ++? Que algumas empresas podem usar o ASM (e só posso imaginar o ASM no HFT onde milissegundos desempenham um papel), está tudo bem. Mas em comércio de frequência média ou em algoritmos? É por causa da velocidade? Eu procurei bibliotecas de finanças de quant para C ++, mas não consegui encontrar muito. O único é QuantLib, MatLib e TA-Lib. Mas sem APIs de gráficos / Libs ou tutoriais. Parece que ninguém está fazendo tutoriais. 2. Por que algumas pessoas escolhem Java? Eu sei, o Java é um idioma muito popular e tem muitas APIs / Libs e a comunidade está crescendo. Mas se a velocidade pode desempenhar um papel, Java não pode ser o mais rápido (devido ao ambiente virtual). Ou eu estou errado? 3. Por que ninguém está usando Python para negociação de média freqüência ou algo trading? Python tem muitos Apis / Libs como MatLib, TA-Lib, Pyqtgraph. Ok, eu tenho que dizer, Python não é o mais rápido. 4. Nesta discussão Por que o C ++ ainda é uma linguagem muito popular em finanças quantitativas ?, algumas pessoas afirmam que C # pode ser muito melhor para o desenvolvimento de finanças quantitativas. É realmente verdade? Como sobre Libs, APIs, Tutoriais, etc?
E a minha pergunta final, qual é a propriedade importante para a escolha de uma linguagem para financiamento quantitativo? Eu não falo sobre ASM porque é o idioma mais rápido e é usado para cálculos muito complexos que precisam ser feitos rapidamente. Mas sobre C ++, C #, Python e Java? Para mim, é importante que haja Livros e Tutoriais / Exemplos. E o começo, comecei com Python, mas, afinal, lido, não tenho certeza sobre o Python.
As pessoas conseguem esse problema errado porque sempre acabam discutindo as vantagens teóricas dessas línguas, e não as utilizações práticas dessas linguagens.
Haskell é elegante e tem muitas das vantagens teóricas (concisão da linguagem, ortogonalidade, polimorfismo paramétrico, ADTs, funções de ordem superior, compilador inteligente), há cerca de 25 anos, mas ainda não é importante nas finanças.
Python é uma linguagem feia. A sintaxe é adorada pela sua expressividade, mas as decisões de design, como o GIL, a digitação dinâmica, o paradigma orientado a objetos, etc. são inerentemente anti-paralelas e décadas abaixo, quando temos centenas de núcleos em cada processador, nossos filhos vão rir da obscuridade e obsoleteness de tais linguagens (entre outras coisas, como disquetes).
No entanto, hoje quase todos incentivam você a pegar o Python. Por quê?
O futuro de uma língua (ou de qualquer tecnologia, para a matéria) é decidido por sua comunidade, a riqueza de suas bibliotecas e ferramentas de desenvolvimento ea natureza autoperpetuante do código legado naquela linguagem e nunca suas vantagens teóricas. Podemos escrever ensaios sobre como odiamos Java; as bibliotecas ROOT e Boost; a verbosidade do XML, mas essas coisas estão aqui para ficar porque alcançaram uma massa crítica de usuários que estão dispostos a criar ferramentas de força de produção ou bibliotecas ao seu redor. Dezenas de linguagens funcionais, como F #, irão e virão, mas C ++ quase certamente permanecerá por causa da grande quantidade de código legado em C ++. Além disso, C ++ '11 é um enorme marco na classificação dos percalços teóricos ao longo de seu caminho de desenvolvimento.
Algumas escolhas abordarei com cautela:
Idiomas construídos em torno de paradigmas concorrentes e funcionais: Scala, F #. Eu diria abordá-lo com cautela, porque ele é usado na produção na Dropbox, Lime, Tower Research, Credit Suisse, etc., mas essas linguas levaram muito mais tempo para aumentar o uso convencional do que você esperaria que dêem as tendências atuais na arquitetura do processador. É difícil para mim dizer-lhe se ou não investir o seu tempo agora nestas línguas vai pagar exatamente 5 anos a partir de agora, mas todos nós parecem concordar que estas línguas eventualmente. Idiomas específicos do domínio: Julia. Infelizmente, Julia se comercializa com "Loops internos numéricos de velocidade C". Ele atrai o mesmo subconjunto da multidão de Python que argumentaria com esses usuários da Julia que isso é irrelevante, pois eles sempre podem cair para o Cython. Ambas as multidões defendem um paradigma condenado e atraem desenvolvedores de baixa qualidade. (Digo, infelizmente, porque Julia tem um grande número de coisas que as pessoas não percebem: multimethods tipo paramétricos, corutinas simétricas, interfaces limpas com linguagens estrangeiras, influências Lisp e suporte a metaprograma, etc.)
Com isso, gostaria de encorajar algumas escolhas:
Idiomas com apoio de irmão mais velho: Go, Swift, C #. Além do suporte do Google, Go tornou-se muito popular na China; A Microsoft fez um enorme avanço no C #; e muitas ferramentas de desenvolvimento de UI de alta qualidade sempre geram as principais linguas da Apple. Idiomas destinados a suplantar C / C ++ como uma linguagem de programação de nível de sistema: D, Nimrod. D já tem o apoio do Facebook e a Nimrod mantém a expressividade da sintaxe de Python enquanto obtém benchmarks impressionantes e está sendo usada para determinados projetos de programação de nível de sistemas. Tenha cuidado no entanto que ambos ainda dependem da abordagem GC para gerenciamento de memória.
Algum dos acima alcançou uma massa crítica de bons desenvolvedores? Acho que não. A solução real para você é que uma linguagem de programação realmente não é difícil de pegar! O que é mais importante é que você escolha como projetar um programa em vez de um idioma específico. Passe algum tempo com os 6 principais paradigmas de linguagem:
Programação imperativa (C) e abstrações de classes (C ++, C #, Java) Abstração funcional (Lisp, ML, F #) Especificações declarativas (modelos C ++, Haskell, Prolog) Abstração sintática (Lisp) Paralelismo (Cilk, SISAL, Clojure, Erlang) Corutinas (C #, F #, Haskell, Esquema, Ícone)
O comércio quantitativo geralmente invoca conceitos desses três campos principais:
Algoritmos, padrões de design e estruturas de dados: árvores B, listas de ignorar, memorização, DP, etc. Programação de sistemas: endereçamento de memória, montagem, ligação, pilha / pilha, cache etc. Bancos de dados: Normalização, confirmação de duas fases, replicação, espelhamento, esquema design etc.
E se você se aproximar do foco do desenvolvedor quant do espectro:
Infelizmente, não há uma resposta correta para esta questão, é como o carro que você deveria dirigir no fim de semana.
C ++ é uma linguagem popular em finanças quantitativas, mas geralmente é (mas nem sempre!) Usado apenas para construir o backbone da aplicação, como o preço derivado. Por que C ++? O C ++ é uma boa escolha porque o C ++ é independente da plataforma, podemos construir de forma nativa um código de preço de opções para Linux, Mac, Windows etc. O QuantLib é um bom exemplo.
C # é outra linguagem muito popular em finanças. Podemos usar o C # para criar um aplicativo comercial, analisar dados XML de outro banco, criar um servidor web, etc. Claro, também podemos fazer preços derivados em C #, mas talvez não possamos otimizar o desempenho. Em C ++, podemos dividir as cargas de trabalho com o OpenMP, vectorizar um loop de Monte-Carlo, etc., mais difícil com o C #.
C # definitivamente não é uma linguagem melhor do que C ++ em finanças quantitativas. Depende realmente do que você quer fazer. Por exemplo, ninguém usaria C # para negociação HPC.
Nem todo mundo em financiamento quantitativo pode fazer programação difícil, a maioria não. Python (Excel VBL ou R) seria um idioma melhor para eles.
Se quiser aprender algo para o seu primeiro trabalho, comece com o C ++. Tente entender o QuantLib.

Melhor linguagem de programação para sistemas de negociação algorítmica.
Você está com dor quando está tentando fazer sexo? Pode ser uma desordem menor ou pode ser uma impotência.
Estou certo de que isso não é verdade.
Que palavras . super, excelente frase.
Todos os segredos do poder masculino final e da potência são revelados em uma série de letras!
Junte-se. Eu concordo com todos os acima mencionados. Podemos falar sobre isso.
Melhor linguagem de programação para sistemas de negociação algorítmica?
Por Michael Halls-Moore em 26 de julho de 2013.
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 exceda as barras segundo (i. E. Tick data) 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.
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 forma consoante interativa; 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 o 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. 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".
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 (i. E. No 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 teste plugins desse tipo e assegure-se de que 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.
Por exemplo, se o armazenamento de dados em uso estiver atualmente com desempenho inferior, mesmo em níveis significativos de otimização, ele pode ser trocado com reescrituras mínimas para a ingesta de dados ou API de acesso a dados. Até o ponto em que o backtester e os componentes subsequentes estão em causa, não há diferença.
Outro benefício de componentes separados é que permite que uma variedade de linguagens de programação sejam usadas no sistema geral. Não é necessário restringir a um único idioma se o método de comunicação dos componentes for independente de linguagem. Este será o caso se estiverem se comunicando via TCP / IP, ZeroMQ ou algum outro protocolo independente de linguagem.
Como um exemplo concreto, considere o caso de um sistema de backtesting que está sendo escrito em C ++ para o desempenho do "crunching", enquanto o gerenciador de portfólio e os sistemas de execução são escritos em Python usando SciPy e IBPy.
O desempenho é uma consideração significativa para a maioria das estratégias comerciais. Para estratégias de maior freqüência, é o fator mais importante. O "Desempenho" cobre uma ampla gama de problemas, como velocidade de execução algorítmica, latência de rede, largura de banda, E / S de dados, simultaneidade / paralelismo e dimensionamento. Cada uma dessas áreas é coberta individualmente por grandes livros didáticos, portanto este artigo apenas arranhará a superfície de cada tópico. A escolha da arquitetura e da linguagem agora será discutida em termos de seus efeitos sobre o desempenho.
A sabedoria prevalecente, como afirmou Donald Knuth. um dos pais da Ciência da Computação, é que "otimização prematura é a raiz de todo o mal". Este é quase sempre o caso - exceto quando se forma um algoritmo de negociação de alta freqüência! Para aqueles que estão interessados ​​em estratégias de baixa freqüência, uma abordagem comum é construir um sistema da maneira mais simples possível e apenas otimizar à medida que os estrangulamentos começam a aparecer.
Ferramentas de perfil são usadas para determinar onde surgem os estrangulamentos. Perfis podem ser feitos para todos os fatores listados acima, em um ambiente MS Windows ou Linux. Existem muitas ferramentas de sistema operacional e de idioma disponíveis para isso, bem como utilitários de terceiros. A escolha da linguagem agora será discutida no contexto da performance.
C ++, Java, Python, R e MatLab contêm bibliotecas de alto desempenho (como parte do padrão ou externo) para estrutura básica de dados e trabalho algorítmico. C ++ é fornecido com a Biblioteca de modelos padrão, enquanto o Python contém NumPy / SciPy. Tarefas matemáticas comuns são encontradas nessas bibliotecas e raramente é benéfico escrever uma nova implementação.
Uma exceção é se uma arquitetura de hardware altamente personalizada é necessária e um algoritmo está fazendo uso extensivo de extensões proprietárias (como caches personalizados). No entanto, muitas vezes a "reinvenção da roda" desperdiça o tempo que pode ser melhor gasto no desenvolvimento e otimização de outras partes da infra-estrutura de negociação. O tempo de desenvolvimento é extremamente precioso especialmente no contexto dos únicos desenvolvedores.
A latência é muitas vezes uma questão do sistema de execução, pois as ferramentas de pesquisa geralmente estão localizadas na mesma máquina. Para o primeiro, a latência pode ocorrer em vários pontos ao longo do caminho de execução. Os bancos de dados devem ser consultados (latência de disco / rede), os sinais devem ser gerados (sistema operacional, latência de mensagens do kernal), sinais comerciais enviados (latência NIC) e pedidos processados ​​(latência interna dos sistemas de troca).
Para operações de maior freqüência, é necessário familiarizar-se intimamente com a otimização do kernal, além de otimizar a transmissão da rede. Esta é uma área profunda e está significativamente além do escopo do artigo, mas se um algoritmo UHFT é desejado então esteja ciente da profundidade do conhecimento necessário!
O cache é muito útil no conjunto de ferramentas de um desenvolvedor de negócios quantitativo. O armazenamento em cache refere-se ao conceito de armazenar dados freqüentemente acessados ​​de uma maneira que permita um acesso de alto desempenho, em detrimento do potencial estancamento dos dados. Um caso de uso comum ocorre no desenvolvimento da web ao tirar dados de um banco de dados relacional com respaldo de disco e colocá-lo na memória. Quaisquer pedidos subseqüentes para os dados não precisam "acessar o banco de dados" e, portanto, os ganhos de desempenho podem ser significativos.
Para situações de negociação, o cache pode ser extremamente benéfico. Por exemplo, o estado atual de um portfólio de estratégia pode ser armazenado em um cache até ser reequilibrado, de modo que a lista não precisa ser regenerada em cada ciclo do algoritmo de negociação. Essa regeneração provavelmente será uma alta CPU ou operação de E / S de disco.
No entanto, o armazenamento em cache não está sem os seus próprios problemas. A regeneração de dados de cache de uma só vez, devido à natureza volátil do armazenamento de cache, pode colocar uma demanda significativa na infraestrutura. 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.
A alocação de memória dinâmica é uma operação cara na execução de software. Assim, é imperativo que os aplicativos de maior desempenho comercial sejam conscientes de como a memória está sendo alocada e desalocada durante o fluxo do programa. Novos padrões de linguagem, como Java, C # e Python, todos executam a coleta automática de lixo. que se refere à desalocação da memória alocada dinamicamente quando os objetos ficam fora do escopo.
A coleta de lixo é extremamente útil durante o desenvolvimento, pois reduz erros e ajuda a legibilidade. No entanto, muitas vezes é sub óptimo para certas estratégias de negociação de alta freqüência. A coleta de lixo personalizada é muitas vezes desejada para esses casos. Em Java, por exemplo, ao ajustar a configuração do coletor de lixo e do heap, é possível obter alto desempenho para as estratégias de HFT.
C ++ não fornece um coletor de lixo nativo e, portanto, é necessário lidar com toda a alocação / desalocação de memória como parte da implementação de um objeto. Embora potencialmente propenso a erros (potencialmente levando a ponteiros pendurados), é extremamente útil ter um controle fino de como os objetos aparecem no heap para determinadas aplicações. Ao escolher um idioma, certifique-se de estudar como funciona o coletor de lixo e se ele pode ser modificado para otimizar um caso de uso específico.
Muitas operações em sistemas de negociação algorítmica são favoráveis ​​à paralelização. Isso se refere ao conceito de realização de múltiplas operações programáticas ao mesmo tempo, i. e em "paralelo". Os algoritmos denominados "embarassingly paralelos" incluem etapas que podem ser computadas totalmente independentemente de outras etapas. Certas operações estatísticas, como as simulações de Monte Carlo, são um bom exemplo de algoritmos embarazosa paralelos, pois cada sorteio aleatório e subsequente operação do caminho podem ser computados sem o conhecimento de outros caminhos.
Outros algoritmos são apenas parcialmente paralelizados. As simulações de dinâmica de fluidos são um exemplo, onde o domínio da computação pode ser subdividido, mas, em última instância, esses domínios devem se comunicar entre si e, portanto, as operações são parcialmente seqüenciais. Os algoritmos paralisáveis ​​estão sujeitos à Lei de Amdahl. que fornece um limite superior teórico para o aumento de desempenho de um algoritmo paralelizado quando sujeito a processos separados $ N $ (por exemplo, em um núcleo ou segmento de CPU).
A paralelização tornou-se cada vez mais importante como um meio de otimização, uma vez que as velocidades do clock do processador estagnaram, já que os processadores mais novos contêm muitos núcleos com os quais realizar cálculos paralelos. O aumento do hardware de gráficos de consumo (predominantemente para videogames) levou ao desenvolvimento de Unidades de processamento gráfico (GPUs), que contém centenas de "núcleos" para operações altamente concorrentes. Tais GPUs são agora muito acessíveis. Os quadros de alto nível, como o CUDA da Nvidia, levaram a uma adoção generalizada na academia e nas finanças.
Esse hardware de GPU geralmente é apenas adequado para o aspecto de pesquisa de financiamento quantitativo, enquanto que outros equipamentos mais especializados (incluindo matrizes de portas programáveis ​​em campo - FPGAs) são usados ​​para (U) HFT. Atualmente, a maioria dos langauges modernos suporta um grau de concorrência / multithreading. Assim, é direto otimizar um backtester, pois todos os cálculos são geralmente independentes dos outros.
O dimensionamento em engenharia e operações de software refere-se à capacidade do sistema de lidar consistentemente com o aumento de cargas sob a forma de solicitações maiores, maior uso do processador e maior alocação de memória. Na negociação algorítmica, uma estratégia pode escalar se pode aceitar quantidades maiores de capital e ainda produzir retornos consistentes. A pilha de tecnologia de negociação escala se pode suportar maiores volumes de comércio e latência aumentada, sem bloqueio de estrangulamento.
Enquanto os sistemas devem ser projetados para dimensionar, muitas vezes é difícil prever de antemão, onde um gargalo irá ocorrer. O registro, o teste, o perfil e o monitoramento rigorosos ajudarão grandemente em permitir que um sistema seja dimensionado. As próprias línguas são muitas vezes descritas como "inesquecíveis". Isso geralmente é o resultado de uma informação errônea, e não de um fato difícil. É a pilha de tecnologia total que deve ser verificada quanto à escalabilidade, e não ao idioma. Claramente, certas línguas têm maior desempenho do que outras em casos de uso específicos, mas um idioma nunca é "melhor" do que outro em todos os sentidos.
Um meio de gerenciar a escala é separar as preocupações, como afirmado acima. A fim de introduzir ainda a capacidade de lidar com "picos" no sistema (por exemplo, volatilidade súbita que desencadeia uma série de trades), é útil criar uma "arquitetura de filas de mensagens". Isso simplesmente significa colocar um sistema de fila de mensagens entre os componentes para que as ordens sejam "empilhadas" se um determinado componente não conseguir processar muitos pedidos.
Em vez de pedidos de perda, eles simplesmente são mantidos em uma pilha até que a mensagem seja tratada. Isso é particularmente útil para enviar trocas para um mecanismo de execução. 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 and Operating Systems.
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.
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. Further, they often allow interactive console based development, rapidly reducing the iterative development process.
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. Open source operating systems such as Linux can be trickier to administer.
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.
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 .
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.
The benefit of a separated architecture is that it allows languages to be "plugged in" for different aspects of a trading stack, as and when requirements change. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.
Mike is the founder of QuantStart and has been involved in the quantitative finance industry for the last five years, primarily as a quant developer and later as a quant trader consulting for hedge funds.

Best Programming Language for Algorithmic Trading Systems?
Best Programming Language for Algorithmic Trading Systems?
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.
Once the trading strategy has been selected, it is necessary to architect the entire system. 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.
Frequency of strategy is likely to be one of the biggest drivers of how the technology stack will be defined. 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".
Execution Systems.
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. In software development, this essentially means how to break up the different aspects of the trading system into separate modular components.
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. Another issue is dog-piling , where multiple generations of a new cache copy are carried out under extremely high load, which leads to cascade failure.
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 and Operating Systems.
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. Further, they often allow interactive console based development, rapidly reducing the iterative development process.
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. Open source operating systems such as Linux can be trickier to administer.
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.
The benefit of a separated architecture is that it allows languages to be "plugged in" for different aspects of a trading stack, as and when requirements change. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.
A Quantcademy.
Junte-se ao portal de adesão da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento e saiba como aumentar a rentabilidade da sua estratégia.
Comércio Algoritmo bem sucedido.
Como encontrar novas ideias de estratégia de negociação e avaliá-las objetivamente para seu portfólio usando um mecanismo de backtesting personalizado em Python.
Negociação Algorítmica Avançada.
Como implementar estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquinas e estatísticas bayesianas com R e Python.

Escolhendo o software de negociação algorítmica correto.
Ao usar o comércio algorítmico, os comerciantes confiam no seu dinheiro suado para o software comercial que eles usam. O software certo é muito importante para assegurar a execução efetiva e precisa dos pedidos comerciais. O software defeituoso, ou um sem os recursos necessários, pode levar a grandes perdas. Este artigo analisa as principais coisas a considerar para escolher o software certo para negociação algorítmica. (Para mais, veja: Noções básicas de negociação algorítmica: conceitos e exemplos.)
[O software de negociação algorítmica depende de uma compreensão profunda da análise técnica. Afinal, os indicadores técnicos são frequentemente utilizados como insumos para esses sistemas de negociação. O Curso de Análise Técnica da Investopedia fornece uma visão geral aprofundada sobre como identificar padrões, tendências, sinais e indicadores técnicos que impulsionam o comportamento dos preços. Com mais de cinco horas de vídeo sob demanda, exercícios e conteúdo interativo, você aprenderá todas as principais formas de análise técnica e estudos de caso de acesso mostrando como eles são usados.]
Um Quick Primer para Algorithmic Trading.
Um algoritmo é definido como um conjunto específico de instruções passo a passo para completar uma tarefa específica. Seja o jogo de computador simples, ainda viciante, como o Pac-Man ou uma planilha que oferece grande número de funções, cada programa segue um conjunto específico de instruções com base em um algoritmo subjacente.
O comércio algorítmico é o processo de usar um programa de computador que segue um conjunto definido de instruções para colocar uma ordem comercial. O objetivo do programa de negociação algorítmica é identificar dinamicamente oportunidades rentáveis ​​e colocar os negócios para gerar lucros a uma velocidade e freqüência que é impossível combinar por um comerciante humano. Dadas as vantagens de uma maior precisão e velocidade de execução relâmpago, as atividades comerciais baseadas em algoritmos de computador ganharam enorme popularidade. (Para mais, veja: Os prós e os contras dos sistemas de negociação automatizados.)
Quem usa software de negociação algorítmica?
A negociação algorítmica é dominada por grandes empresas comerciais, como hedge funds, bancos de investimento e empresas comerciais proprietárias. Dada a abundante disponibilidade de recursos devido ao seu grande tamanho, essas empresas costumam construir seu próprio software de negociação proprietário, incluindo grandes sistemas de negociação com centros de dados dedicados e equipe de suporte.
Em um nível individual, comerciantes proprietários experientes e quants usam negociação algorítmica. Os comerciantes proprietários, que são menos conhecedores de tecnologia, podem comprar software de negociação readymade para suas necessidades de negociação algorítmica. O software é oferecido por seus corretores ou comprado de provedores de terceiros. Quants tem um bom conhecimento de negociação e programação de computadores, e eles desenvolvem software comercial por conta própria. (Para mais informações, consulte: Quants: o que eles fazem e como evoluíram.)
Algorithmic Trading Software - Construir ou comprar?
Existem duas maneiras de acessar o software de negociação algorítmica: construir ou comprar.
A compra de software pronto oferece acesso rápido e atempado, ao construir o seu próprio, permite flexibilidade total para personalizar as suas necessidades. O software de negociação automatizado é muitas vezes caro para comprar e pode estar cheio de lacunas, o que, se ignorado, pode levá-lo a perdas. Os custos elevados podem tirar o potencial de lucro realista do seu empreendimento de negociação algorítmica. Por outro lado, criar software de negociação algorítmica por conta própria leva tempo, esforço e um profundo conhecimento, e ainda pode não ser infalível.
O risco envolvido na negociação automática é muito alto, o que pode levar a grandes perdas. Independentemente de se decidir comprar ou construir, torna-se importante conhecer os recursos básicos necessários.
As principais características do software de negociação algorítmica.
Disponibilidade de dados do mercado e da empresa: todos os algoritmos de negociação são projetados para atuar em dados de mercado em tempo real e cotações de preços. Alguns programas também são personalizados para dar conta dos dados fundamentais da empresa, como os índices EPS e PE. Qualquer software de negociação algorítmica deve ter feed de dados de mercado em tempo real, bem como um feed de dados da empresa. Ele deve estar disponível como um build-in no sistema ou deve ter uma disposição para integrar facilmente de fontes alternativas. Conectividade a vários mercados: os comerciantes que procuram trabalhar em vários mercados devem ter em atenção que cada troca pode fornecer seu feed de dados em um formato diferente, como TCP / IP, Multicast ou um FIX. Seu software deve ser capaz de aceitar feeds de diferentes formatos. Outra opção é ir com fornecedores de dados de terceiros como a Bloomberg e a Reuters, que agregam dados de mercado de diferentes trocas e fornecem-no em um formato uniforme para clientes finais. O software de negociação algorítmica deve ser capaz de processar esses feeds agregados conforme necessário. Latência: A menor palavra desta lista é o fator mais importante para o algo-trading. Latência é o tempo de atraso introduzido no movimento de pontos de dados de um aplicativo para o outro. Considere a seguinte sequência de eventos. Demora 0,2 segundos para uma cotação de preço proveniente da troca para o centro de dados do seu fornecedor de software (DC), 0,3 segundos do data center para alcançar sua tela de negociação, 0,1 segundo para o seu software de negociação para processar essa cotação recebida, 0,3 segundos para para analisar e colocar um comércio, 0,2 segundos para a sua ordem comercial para chegar ao seu corretor, 0,3 segundos para o seu corretor rotear sua ordem para a troca.
Tempo total decorrido = 0.2 + 0.3 + 0.1 + 0.3 + 0.2 + 0.3 = Total 1.4 segundos.
No mundo comercial dinâmico de hoje, a cotação do preço original teria mudado várias vezes dentro desse período de 1,4 segundo. Esse atraso poderia fazer ou quebrar seu empreendimento de negociação algorítmica. É preciso manter essa latência ao nível mais baixo possível para garantir que você obtenha as informações mais atualizadas e precisas sem intervalo de tempo.
A latência foi reduzida para microssegundos, e todas as tentativas devem ser feitas para mantê-lo o mais baixo possível no sistema comercial. Algumas medidas incluem ter conectividade direta com a troca para obter dados mais rápidos, eliminando o fornecedor no meio; melhorando seu algoritmo de negociação para que ele leve menos de 0.1 + 0.3 = 0.4 segundos para análise e tomada de decisão; ou eliminando o corretor e enviando diretamente trocas para a troca para economizar 0,2 segundos.
Configuração e personalização: a maioria dos softwares de negociação algorítmica oferece algoritmos de comércio embutidos padrão, como aqueles baseados em um crossover da média móvel de 50 dias (MA) com o MA de 200 dias. Um comerciante pode gostar de experimentar mudando para o Mestre de 20 dias com o MA de 100 dias. A menos que o software ofereça tal personalização de parâmetros, o comerciante pode ser limitado pela funcionalidade fixa incorporada. Seja comprando ou construindo, o software de negociação deve ter um alto grau de personalização e configuração. Funcionalidade para escrever programas personalizados: Matlab, Python, C ++, JAVA e Perl são as linguagens de programação comuns usadas para escrever software de negociação. A maioria dos softwares de negociação vendidos pelos fornecedores de terceiros oferece a capacidade de escrever seus próprios programas personalizados dentro dele. Isso permite que um comerciante experimente e experimente qualquer conceito comercial que ela desenvolva. O software que oferece codificação na linguagem de programação de sua escolha é obviamente preferido. (Para mais informações, consulte: Codificação de sistemas de negociação: Introdução.) Recurso Backtesting em dados históricos: a simulação Backtesting envolve testar uma estratégia de negociação em dados históricos. Ele avalia a praticidade e rentabilidade da estratégia em dados passados, certificando-o para o sucesso (ou falha ou qualquer alteração necessária). Esta função obrigatória também deve ser acompanhada de uma disponibilidade de dados históricos, nos quais o backtesting pode ser realizado. Integração com a interface de negociação: o software de negociação algorítmica coloca trades automaticamente com base na ocorrência de um critério desejado. O software deve ter a conectividade necessária para a rede de corretores para colocar o comércio ou uma conectividade direta com a troca para enviar ordens comerciais. Integração Plug-n-play: um comerciante pode estar usando simultaneamente um terminal Bloomberg para sua análise de preços, um terminal de intermediário para fazer negócios e um programa Matlab para análise de tendências. Dependendo das necessidades individuais, o software de negociação algorítmica deve ter integração fácil de plug-n-play e APIs disponíveis em ferramentas de negociação comumente usadas. Isso garante a escalabilidade, bem como a integração. Programação Independente da Plataforma: algumas línguas de programação precisam de plataformas dedicadas. Por exemplo, certas versões do C ++ podem ser executadas somente em sistemas operacionais selecionados, enquanto o Perl pode ser executado em todos os sistemas operacionais. Ao construir ou comprar software de negociação, deve ser dada preferência ao software de negociação que seja independente da plataforma e suporte linguagens independentes da plataforma. Você nunca sabe como sua negociação evoluirá alguns meses abaixo da linha. The Stuff Under the Hood: um ditado comum diz: "Mesmo um macaco pode clicar no botão do mouse para colocar um comércio". Dependência de computadores não deve ser cega. É o comerciante que deve entender o que está indo sob o capô. Ao comprar software de negociação, deve-se pedir e levar tempo para passar pela documentação detalhada que mostra a lógica subjacente de um software de negociação algorítmico particular. Evite qualquer software de negociação que seja uma caixa preta completa e que pretende ser uma máquina de fazer dinheiro secreto.
Ao construir software, seja realista sobre o que você está implementando e seja claro sobre os cenários onde ele pode falhar. Antes de colocá-lo para usar com dinheiro real, faça uma resposta completa.
Por onde começar?
Todo o software de negociação algorítmico pronto geralmente oferece versões de avaliação de funcionalidade limitada gratuita ou períodos de avaliação limitados com funcionalidades completas. Explore-os na íntegra durante esses testes antes de comprar qualquer coisa. Não esqueça de detalhar a documentação disponível.
Para construir um, uma boa fonte gratuita para explorar o comércio algorítmico é a quespian. Ele oferece uma plataforma on-line para testar e desenvolver comércio algorítmico. Os indivíduos podem tentar personalizar qualquer algoritmo existente ou escrever um novo completamente novo. A plataforma também oferece software de negociação algorítmico embutido para ser testado em relação aos dados do mercado.
The Bottom Line.
O software de negociação algorítmica é caro para comprar e é difícil de construir sozinho. Comprar pré-fabricados oferece acesso rápido e atempado, e criar o seu próprio permite flexibilidade total para personalizá-lo às suas necessidades. Antes de se aventurar com dinheiro real, é preciso entender completamente a funcionalidade básica do software de negociação algorítmica comprado ou construído. A falta de fazê-lo pode ser uma perda dispendiosa difícil de recuperar.

Why Python Algorithmic Trading is Preferred Choice Among Traders?
To survive in the age of robots, it is necessary to learn a programming language that makes your trading algorithms smarter and not just faster. Having knowledge of a popular programming language is the building block to becoming a professional algorithmic trader. It is not just enough if a person has a love for numbers. Professionals need to put the logic using numbers into a software program to perform a successful transaction. Programming languages are an important contributing factor for trading systems. To build a concrete trading platform - knowledge of various programming languages is a must as it helps control the volatile and multi-faceted market conditions.
For people who wish to thrive in the competitive market of quantitative trading programming expertise in Python, C++ or Java is a must. The core concepts behind using these programming languages for algorithmic trading are same. If an individual acquires expertise in any one language then switching over to the other programming language for algorithmic trading should not be a tough task.
With rapid advancements in technology every day - it is difficult for programmers to learn all the programming languages. One of the most common questions that we receive at QuantInsti is “Which programming language should I learn for algorithmic trading?” The answer to this question is that there is nothing like a “BEST” language for algorithmic trading. There are many important concepts taken into consideration in the entire trading process before choosing a programming language – cost, performance, resiliency, modularity and various other trading strategy parameters.
Each programming language has its own pros and cons and a balance between the pros and cons based on the requirements of the trading system will affect the choice of programming language an individual might prefer to learn. Every organization has a different programming language based on their business and culture.
What kind of trading system will you use? Are you planning to design an execution based trading system? Are you in need of a high-performance back tester?
Based on answers to all these questions, once can decide on which programming language is the best for algorithmic trading. However, to answer the above questions let’s explore the various programming languages used for algorithmic trading with a brief understanding of the pros and cons of each.
Researchers and Quant traders require a scripting language to build a prototype of the code. Python for trading has huge significance in the overall trading process as it find applications in prototyping quant models particularly in quant trading groups in banks and hedge funds. Most of the quant traders prefer Python algorithmic trading as it helps them build their own data connectors, execution mechanisms, backtesting, risk and order management, walk forward analysis and optimization testing modules.
Algorithmic trading developers are often confused whether to choose an open source technology or a commercial/proprietary technology. Before deciding on this it is important to consider the activity of the community surrounding a particular programming language, the ease of maintenance, ease of installation, documentation of the language and the maintenance costs. Python for trading has become a preferred choice recently as Python is an open source and all the packages are free for commercial use.
Python algorithmic trading has gained traction in the quant finance community as it makes it easy to build intricate statistical models with ease due to the availability of sufficient scientific libraries like Pandas, NumPy, PyAlgoTrade, Pybacktest and more.
Parallelization and huge computational power of Python trading give scalability to the portfolio. Algorithmic trading python makes it easier to write and evaluate algo trading structures because of its functional programming approach. The code can be easily extended to dynamic algorithms for trading. Python can be used to develop some great trading platforms where using C or C++ is a hassle and time-consuming job. Trading with Python is an ideal choice for people who want to become pioneers with dynamic algo trading platforms. For individuals new to algorithmic trading, python code is easily readable and accessible. So, if you are stepping into the world of algorithmic trading then QuantInsti’s executive program will help you implement your strategies in the live environment through Python trading platforms. It is comparatively easier to fix new modules to Python language and make it expansive. The existing modules also make it easier for algo traders to share functionality amongst different programs by decomposing them into individual modules which can be applied to various trading architectures. When using Python for trading it requires fewer lines of code due to the availability of extensive libraries. Quant traders can skip various steps which other languages like C or C++ might require. This brings down the overall cost of maintaining the trading system. With a wide range of scientific libraries in Python, algorithmic traders can perform any kind of data analysis at an execution speed that is comparable to compiled languages like C++.
Drawback of Using Python in Algorithmic Trading.
Just like every coin has two faces, there are some drawbacks of using Python for trading. However, the pros of using python for trading exceed the drawbacks making it a supreme choice of programming language for algorithmic trading platforms.
In python, every variable is considered as an object, so every variable will store unnecessary information like size, value and reference pointer. Usually, the size of python variables is 3 times more than the size of C language variables. When storing millions of variables if memory management is not done effectively, it could lead to memory leaks and performance bottlenecks.
Algorithmic Trading & # 8211; Python vs. C++
A compiled language like C++ is often an ideal programming language choice if the backtesting parameter dimensions are large. However, Python makes use of high-performance libraries like Pandas or NumPy for backtesting to maintain competitiveness with its compiled equivalents. Python or C++ – the language to be used for backtester and research environments will be decided based on the requirements of the algorithm and the available libraries. Choosing C++ or Python will depend on the trading frequency. Python trading language is ideal for 5-minute bars but when moving down time sub-second time frames this might not be an ideal choice. If speed is a distinctive factor to compete with your competent then using C++ is a better choice than using Python for Trading. C++ is complicated language, unlike Python which even beginners can easily read, write and learn.
Trading systems evolve with time and any programming language choices will evolve along with them. If you want to enjoy the best of both the worlds in algorithmic trading i. e. benefits of a general purpose programming language and powerful tools of the scientific stack – choose an algorithmic trading course that introduces python trading platforms.
Seems like there is a lot to be learned. Não é? Get started on your journey and enroll now for our algorithmic trading course ‘Executive Programme in Algorithmic Trading’ to design a masterpiece.
You can also check out our interactive course, ‘Python for Trading‘, you’ll get hands-on experience on Python coding. You’ll get to code your own strategy and backtest it as well plus a joint certification from QuantInsti and MCX.
Posts Relacionados:
4 thoughts on “ Why Python Algorithmic Trading is Preferred Choice Among Traders? "
IMHO Cython is another best choice to replace only that computation hungry parts.
What you’re saying is completely true. I know that everybody must say the same thing, but I just think that you put it in a way that everyone can understand. I’m sure you’ll reach so many people with what you’ve got to say.
Lots of brokers support support C# with an API but the article doesn’t include it in the comparison. IMHO C# contains the best features of both python and C++. It has small memory and fast execution like C++ but is a higher level language like python so fewer lines of code are needed to make useful objects. The author of the article fails to mention that a scripting language relies on a server, thus is slower and has inherent limitations; whereas a compiled program (like C++ or C#) is standalone and more adaptable.
Many brokers now offer Python API and there are many online trading platforms like Quantiacs, Quantopian, Quantconnect which support Python. It is easy to learn and can be used for trading medium frequency strategies. Python does come with certain limitations but given the positive factors, it has become more popular than C# and C++ in recent years for retail trading.

A guide to the popular programming languages used for trading systems.
How an algorithmic trading system will work is dependent on the programming language used, and whether it will work well depends on your understanding of that programming language.
There are a number of programming languages each with there own advantages and disadvantages, and just like any other decision, you will have to weigh the pros and cons of each when deciding which one you would like to learn. A few factors go into what kind of programming languages companies would rather their employees learn. Instead of saying, "well people like Java, I'll go with that," consider the kinds of firms you are applying to, and which language seems best suited for each one's business and culture.
Deciding on a language will depend on determining what kind of trading system you will be using. Do you intend to design an execution based trading system? Will it require a high-performance backtester? Questions like these will eventually lead you to the answer for which programming language will make you seem like a good candidate for hire. But in order to make this decision, you will also need to have a decent understanding of the pros and cons of each one. Read the guide below to learn more about the programming languages that you can use to develop a trading system architecture:
Java has grown extremely popular since it first emerged. The promise behind this particular high-level language is build a program once, and you can run it anywhere – an advantage that has fueled Java's ascent. There are a number of benefits to this language that make it a better option than many others. It is an easy-to-use and reliable language. It can be debugged, written and learned easily, and places much importance on checking for errors. Issues that wouldn't appear until execution time when using other languages are found quickly with Java.
In addition, another major advantage of using Java is the fact that this particular language is platform-independent. The object-oriented language also allows users to create modular programs and reusable codes. Programmers can easily move a program from one platform to another without issue, a massive benefit. It's not just ease of use and versatility that has made Java so popular though. Each component of the language has been designed with security in mind.
Python is another object-oriented language that is quite readable. The easy-to-learn programming language is interactive, as well as portable, which allows it to be handled with ease. Another language that makes technology jobs in the finance sector easier, its structure is well organized, which means that beginners and longtime-coders alike can quickly begin producing programs with Python. In addition, a programmer who is having trouble learning the language can easily find help from the supportive Python community. The language is also versatile like Java, and can be run on multiple platforms without much of a change to its interface. And not only is Python a quick language to learn, it is also fast to code with. Programmers can skip a number of steps that other languages require, which can bring down the cost of system maintenance.
Another advantage to Python is that it is easy to affix new modules to the language, making it quite expansive. A large set of modules for Python is already available. This allows users to share functionality between various programs by deconstructing them into individual modules and applying them to various architectures.
Esta linguagem de propósito geral é tipicamente usada na programação de sistemas, e é bastante popular. C++ is a complicated language that is not for beginners, and works well for object-oriented programming, data abstraction and traditional programming amongst other uses. Microsoft has claimed that almost every world-class software is designed using C++. While this was once the rapidly ascending language, it has largely been replaced by Java, but C++ still has its advantages. For example, Java uses a significant amount of memory, which gives C++ the advantage when being run on some devices. Another advantage that C++ holds over Java is deterministic destruction. When an object is deleted in a C++ environment, the destruction is executed immediately, which allows resources utilized by the object to be released right away.
Each programming language has grown popular due to their particular advantages, and it will be up to you to decide which will make you appealing to hiring managers. Just keep in mind the connection between the companies that you are applying for, and the particular pros and cons of the language that you choose to learn.

No comments:

Post a Comment