пятница, 11 мая 2018 г.

Sistemas de negociação de codificação fze


Codificação de Sistemas de Negociação.


Por Justin Kuepper.


Como os sistemas de negociação automatizados são criados?


Este tutorial se concentrará na segunda e na terceira partes deste processo, onde suas regras são convertidas em um código que seu software de negociação pode entender e usar.


Vantagens e desvantagens.


Um sistema automatizado tira a emoção e o trabalho ocupado da negociação, o que permite que você se concentre em melhorar suas regras de estratégia e gerenciamento de dinheiro. Uma vez que um sistema lucrativo é desenvolvido, ele não requer nenhum trabalho de sua parte até que ele quebre, ou as condições do mercado exigem uma mudança. Desvantagens:


Se o sistema não for devidamente codificado e testado, grandes perdas podem ocorrer muito rapidamente. Às vezes é impossível colocar certas regras no código, o que dificulta o desenvolvimento de um sistema de negociação automatizado. Neste tutorial, você aprenderá como planejar e projetar um sistema de negociação automatizado, como converter esse design em código que seu computador entenderá, como testar seu plano para garantir o desempenho ideal e, finalmente, como colocar seu sistema em uso.


Codificação de Sistemas de Negociação: Design de Sistema.


Por Justin Kuepper.


Etapa 1: Crie suas regras do sistema de negociação.


O primeiro passo ao projetar um sistema de negociação é simplesmente criar as regras pelas quais seu sistema irá operar. Deve haver quatro regras básicas para cada sistema de negociação:


Comprar - Identifique quando você quer comprar uma posição. Vender - Identifique quando você quer vender uma posição. Pare - Identifique quando você quer reduzir suas perdas. Alvo - Identifique quando você quer reservar um ganho. Então, por exemplo:


Comprar - Quando a média móvel de 30 dias (MA) ultrapassar a MA de 60 dias - Quando o MA de 30 dias cruzar abaixo do MA de 60 dias - Perda máxima de 10 unidades Alvo - Meta de 10 unidades Este exemplo de sistema comprará e venderá com base nas médias móveis de 30 e 60 dias e contabilizará automaticamente os ganhos após um lucro de 10 unidades ou venderá com prejuízo após um movimento de 10 unidades na direção oposta.


Agora que temos nossas regras, precisamos identificar os componentes envolvidos em cada regra. Cada componente deve conter dois elementos:


O indicador ou estudo usado As configurações para o indicador ou estudo Esses componentes devem ser construídos digitando-se o nome abreviado do estudo, seguido das configurações entre parênteses. Essas configurações entre parênteses são chamadas de "parâmetros" do indicador ou estudo. Ocasionalmente, um estudo pode ter vários parâmetros, em cujo caso você simplesmente os separa com vírgulas.


MA (25) - Média móvel de 25 dias RSI (25) - Índice de força relativa de 25 dias MACD (Close (0), 5,5) - Conjunto de divergência de convergência média móvel baseado no fechamento de hoje, com uma duração rápida de cinco dias e uma duração lenta de cinco dias Se você não tiver certeza de quantos parâmetros um determinado componente requer, basta consultar a documentação do seu programa comercial, que lista esses componentes junto com os valores que precisam ser preenchidos. Por exemplo, podemos ver que a Tradecision nos diz que precisamos de três parâmetros com o MACD:


Então, para o exemplo mencionado na primeira etapa, usaríamos:


MA (30) - Significado média móvel de 30 dias MA (60) - Significado média móvel de 60 dias Etapa 3: Adicionando Ação.


Agora vamos adicionar ações às nossas regras. Cada ação segue o seguinte formato básico:


Normalmente, a condição consistirá dos componentes e parâmetros criados acima, enquanto a ação consistirá em comprar ou vender. As condições também podem consistir em inglês simples se nenhum componente estiver presente. Observe que o componente "while" é opcional.


Se MA (30) Cruza Acima MA (60) ENTÃO COMPRE SE MA (30) Cruza Abaixo MA (60) ENQUANTO Volume (20.000) ENTRADA Vende Se EMA (25) É Maior Que MA (5) ENTÃO Vende IF RSI (20) É igual a 50 THEN Buy Então, pelo exemplo que estamos usando, nós simplesmente listamos:


SE MA (30) Cruza Acima MA (60) ENTÃO COMPRE SE MA (30) Cruza Abaixo MA (60) ENTÃO Venda SE a nossa negociação tiver 10 unidades de lucro ENTÃO Venda Se a nossa negociação tiver 10 unidades de perda ENTÃO Vender O que vem a seguir?


Em seguida, vamos dar uma olhada em converter essas regras em um código que seu computador possa entender!


Melhor Linguagem de Programação para Sistemas de Negociação Algorítmica?


Melhor Linguagem de Programação para Sistemas de Negociação Algorítmica?


Uma das perguntas mais frequentes que recebo no mailbag do QS é "Qual é a melhor linguagem de programação para negociação algorítmica?". A resposta curta é que não há "melhor" linguagem. Parâmetros de estratégia, desempenho, modularidade, desenvolvimento, resiliência e custo devem ser considerados. Este artigo descreverá os componentes necessários de uma arquitetura de sistema de comércio algorítmico e como as decisões relativas à implementação afetam a escolha da linguagem.


Primeiramente, os principais componentes de um sistema de negociação algorítmica serão considerados, como as ferramentas de pesquisa, o otimizador de portfólio, o gerenciador de risco e o mecanismo de execução. Posteriormente, diferentes estratégias de negociação serão examinadas e como elas afetam o design do sistema. Em particular, a frequência de negociação e o volume de negociação provável serão ambos discutidos.


Uma vez que a estratégia de negociação tenha sido selecionada, é necessário arquitetar todo o sistema. Isso inclui a escolha de hardware, o sistema operacional e a resiliência do sistema contra eventos raros e potencialmente catastróficos. Enquanto a arquitetura está sendo considerada, a devida atenção deve ser dada ao desempenho - tanto para as ferramentas de pesquisa quanto para o ambiente de execução ao vivo.


Qual é o sistema de negociação tentando fazer?


Antes de decidir sobre a "melhor" linguagem com a 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 de construção de portfólio? O sistema exigirá um backtester de alto desempenho? Para a maioria das estratégias, o sistema de negociação pode ser dividido em duas categorias: Pesquisa e geração de sinais.


A pesquisa está preocupada com a avaliação de um desempenho da estratégia em relação aos dados históricos. O processo de avaliação de uma estratégia de negociação sobre dados de mercado anteriores é conhecido como backtesting. O tamanho dos dados e a complexidade algorítmica terão um grande impacto na intensidade computacional do backtester. A velocidade e a simultaneidade da CPU costumam ser os fatores limitantes na otimização da velocidade de execução da pesquisa.


A geração de sinais preocupa-se em gerar um conjunto de sinais de negociação de um algoritmo e enviar esses pedidos ao mercado, geralmente por meio de uma corretora. Para determinadas estratégias, é necessário um alto nível de desempenho. Problemas de E / S, como largura de banda de rede e latência, são muitas vezes o fator limitante na otimização de sistemas de execução. Assim, a escolha de idiomas para cada componente de todo o seu sistema pode ser bem 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 que estão sendo negociados, a conectividade com fornecedores de dados externos, a frequência e o volume da estratégia, o tradeoff entre facilidade de desenvolvimento e otimização de desempenho, bem como qualquer hardware personalizado, incluindo customização co-localizada servidores, GPUs ou FPGAs que possam ser necessários.


As escolhas tecnológicas para uma estratégia de ações norte-americanas de baixa frequência serão muito diferentes daquelas de uma negociação de estratégia de arbitragem estatística de alta frequência no mercado de futuros. Antes da escolha da linguagem, muitos fornecedores de dados devem ser avaliados quanto à estratégia em questão.


Será necessário considerar a conectividade com o fornecedor, a estrutura de quaisquer APIs, a pontualidade dos dados, os requisitos de armazenamento e a resiliência em face de um fornecedor ficar off-line. Também é aconselhável ter acesso rápido a vários fornecedores! Vários instrumentos têm suas próprias peculiaridades de armazenamento, exemplos dos quais incluem vários símbolos de ticker para ações e datas de vencimento para futuros (para não mencionar quaisquer dados OTC específicos). Isso precisa ser levado em conta no design da plataforma.


A frequência da estratégia é provavelmente um dos maiores impulsionadores 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 consideração significativa com relação ao desempenho.


Uma estratégia que excede as segundas barras (isto é, dados de ticks) leva a um design orientado pelo desempenho como o requisito primário. Para estratégias de alta frequência, uma quantidade substancial de dados de mercado precisará ser armazenada e avaliada. Softwares como HDF5 ou kdb + são comumente usados ​​para essas funções.


Para processar os volumes extensos de dados necessários para aplicativos HFT, um backtester e um sistema de execução extensivamente otimizados devem ser usados. C / C ++ (possivelmente com algum montador) é provável que seja o candidato a idioma mais forte. Estratégias de frequência ultra-alta quase certamente exigirão hardware customizado, como FPGAs, co-location de troca e ajuste de interface de rede / kernal.


Sistemas de pesquisa.


Os sistemas de pesquisa geralmente envolvem uma mistura de desenvolvimento interativo e scripts automatizados. O primeiro ocorre com frequência dentro de um IDE, como o Visual Studio, o MatLab ou o R Studio. Este último envolve extensos cálculos numéricos sobre numerosos parâmetros e pontos de dados. Isso leva a uma escolha de idioma que fornece um ambiente simples para testar o código, mas também fornece desempenho suficiente para avaliar estratégias em várias dimensões de parâmetro.


IDEs típicos nesse espaço incluem o 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 simples da pilha inteira do projeto (via banco de dados ORM, LINQ); MatLab, que é projetado para extensa álgebra linear numérica e operações vetorizadas, mas de uma forma de console interativo; R Studio, que envolve o console de linguagem estatística R em um IDE completo; Eclipse IDE para Linux Java e C ++; e IDEs semi-proprietários como o Enthought Canopy for Python, que incluem bibliotecas de análise de dados como NumPy, SciPy, scikit-learn e pandas em um único ambiente interativo (console).


Para backtesting numérico, todos os idiomas acima são adequados, embora não seja necessário utilizar uma GUI / IDE, pois o código será executado "em segundo plano". A consideração principal neste estágio é a velocidade de execução. Uma linguagem compilada (como C ++) é geralmente útil se as dimensões do parâmetro de backtesting forem grandes. Lembre-se que é necessário ter cuidado com esses sistemas, se for esse o caso!


Linguagens interpretadas, como Python, geralmente usam bibliotecas de alto desempenho como o NumPy / pandas para a etapa de backtesting, a fim de manter um grau razoável de competitividade com equivalentes compilados. Em última análise, a linguagem escolhida para o backtesting será determinada por necessidades algorítmicas específicas, bem como o leque de bibliotecas disponíveis na linguagem (mais sobre isso abaixo). No entanto, a linguagem usada para os ambientes de backtester e de pesquisa pode ser completamente independente daquelas usadas nos componentes de construção de portfólio, gerenciamento de risco e execução, como será visto.


Construção de Carteira e Gestão de Risco.


Os componentes de gerenciamento de risco e de construção de portfólio são frequentemente ignorados pelos traders algorítmicos de varejo. Isso é quase sempre um erro. Essas ferramentas fornecem o mecanismo pelo qual o capital será preservado. Eles não apenas tentam aliviar o número de apostas "arriscadas", mas também minimizam a rotatividade dos 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. É fácil criar uma estratégia estável, pois o mecanismo de construção de portfólio e o gerenciador de risco podem ser facilmente modificados para lidar com vários sistemas. Assim, eles devem ser considerados componentes essenciais no início do projeto de um sistema de negociação algorítmica.


O trabalho do sistema de construção de portfólio é pegar um conjunto de negócios desejados e produzir o conjunto de negociações 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 de portfólio geralmente se reduz a um problema de álgebra linear (como uma fatoração de matriz) e, portanto, o desempenho é altamente dependente da eficácia da implementação da á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. O Python utiliza o NumPy / SciPy para tais cálculos. Um portfólio freqüentemente reequilibrado exigirá uma biblioteca matricial compilada (e bem otimizada!) Para realizar este passo, de modo a não afunilar o sistema de negociação.


O gerenciamento de riscos é outra parte extremamente importante de um sistema de negociação algorítmica. 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, inadimplência de terceiros, interrupções de servidores, eventos "black swan" e erros não detectados no código de negociação. para nomear alguns.


Os componentes de gerenciamento de risco tentam antecipar os efeitos da volatilidade excessiva e correlação entre as classes de ativos e seus efeitos subsequentes sobre o capital comercial. Muitas vezes, isso reduz a um conjunto de cálculos estatísticos, como os "testes de estresse" de Monte Carlo. Isso é muito semelhante às necessidades computacionais de um mecanismo de precificação de derivativos e, como tal, será vinculado à CPU. Estas simulações são altamente paralelizáveis ​​(veja abaixo) e, até certo ponto, é possível "lançar hardware no problema".


Sistemas de Execução.


O trabalho do sistema de execução é receber sinais de negociação filtrados dos componentes de construção de carteira e gestão de risco 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 a Interactive Brokers. As principais considerações ao decidir sobre uma linguagem incluem a qualidade da API, a disponibilidade do wrapper de idioma para uma API, a frequência de execução e o escorregamento previsto.


A "qualidade" da API refere-se a quão bem documentada ela é, que tipo de desempenho ela fornece, se precisa de software independente para ser acessado ou se um gateway pode ser estabelecido de maneira sem cabeça (ou seja, sem GUI). No caso dos Interactive Brokers, a ferramenta Trader WorkStation precisa estar em execução em um ambiente GUI para acessar sua API. Certa vez, tive que instalar uma edição Ubuntu Desktop em um servidor de nuvem da Amazon para acessar remotamente o Interactive Brokers, puramente por esse motivo!


A maioria das APIs fornecerá uma interface C ++ e / ou Java. Geralmente, cabe à comunidade desenvolver wrappers específicos de linguagem para C #, Python, R, Excel e MatLab. Observe que, com cada plug-in adicional utilizado (especialmente os wrappers de APIs), há escopo para os bugs se infiltrarem no sistema. Sempre teste plugins desse tipo e garanta que eles sejam ativamente mantidos. Um indicador que vale a pena é ver quantas novas atualizações foram feitas em uma base de código nos últimos meses.


Freqüência de execução é da maior importância no algoritmo de execução. Observe que centenas de pedidos podem ser enviados a cada minuto e, como tal, o desempenho é crítico. A derrapagem será incorrida através de um sistema de execução com péssimo desempenho e isso terá um impacto dramático na lucratividade.


As linguagens com tipagem estática (veja abaixo) como C ++ / Java são geralmente ótimas para execução, mas há um compromisso em tempo de desenvolvimento, teste e facilidade de manutenção. Linguagens dinamicamente tipificadas, como Python e Perl, são geralmente "rápidas o suficiente". Certifique-se sempre de que os componentes são projetados de maneira modular (veja abaixo) para que possam ser "trocados" conforme o sistema é dimensionado.


Planejamento arquitetônico e processo de desenvolvimento.


Os componentes de um sistema de negociação, seus requisitos de frequência e volume foram discutidos acima, mas a infra-estrutura do sistema ainda não foi coberta. Aqueles que atuam como comerciantes de varejo ou que trabalham em um fundo pequeno provavelmente estarão "usando muitos chapéus". Será necessário estar cobrindo o modelo alfa, os parâmetros de gerenciamento de risco e execução, e também a implementação final do sistema. Antes de aprofundar em 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 de negociação. No desenvolvimento de software, isso significa essencialmente dividir os diferentes aspectos do sistema de negociação em componentes modulares separados.


Ao expor interfaces em cada um dos componentes, é fácil trocar partes do sistema por outras versões que auxiliem o desempenho, a confiabilidade ou a manutenção, sem modificar nenhum código de dependência externo. Essa é a "melhor prática" para esses sistemas. Para estratégias em freqüências mais baixas, tais práticas são recomendadas. Para negociação de ultra alta frequência, o livro de regras pode ter que ser ignorado em detrimento do ajuste do sistema para um desempenho ainda maior. Um sistema mais fortemente acoplado pode ser desejável.


Criar um mapa de componentes de um sistema de negociação algorítmica vale um artigo em si. No entanto, uma abordagem ideal é garantir que haja componentes separados para as entradas de dados de mercado históricas e em tempo real, armazenamento de dados, API de acesso a dados, backtester, parâmetros estratégicos, construção de portfólio, gerenciamento de risco e sistemas automatizados de execução.


Por exemplo, se o armazenamento de dados em uso estiver atualmente com baixo desempenho, mesmo em níveis significativos de otimização, ele poderá ser substituído com reescritas mínimas para a API de acesso a dados ou acesso a dados. Tanto quanto o backtester e componentes subseqüentes estão em causa, não há diferença.


Outro benefício dos componentes separados é que ele permite que uma variedade de linguagens de programação seja usada no sistema geral. Não há necessidade de se restringir a um único idioma se o método de comunicação dos componentes for independente de idioma. Este será o caso se eles estiverem se comunicando via TCP / IP, Zero ou algum outro protocolo independente de linguagem.


Como um exemplo concreto, considere o caso de um sistema de backtesting sendo escrito em C ++ para desempenho "processamento de números", enquanto o gerenciador de portfólio e sistemas de execução são escritos em Python usando SciPy e IBPy.


Considerações de desempenho.


O desempenho é uma consideração significativa para a maioria das estratégias de negociação. Para estratégias de maior frequência, é o fator mais importante. "Desempenho" abrange uma ampla variedade 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 arquitetura e a escolha de idiomas serão agora discutidas em termos de seus efeitos no desempenho.


A sabedoria predominante, como afirma Donald Knuth, um dos pais da Ciência da Computação, é que "a otimização prematura é a raiz de todo o mal". Isso é quase sempre o caso - exceto quando se constrói um algoritmo de negociação de alta frequência! Para aqueles que estão interessados ​​em estratégias de baixa frequência, uma abordagem comum é construir um sistema da maneira mais simples possível e apenas otimizar à medida que os gargalos começam a aparecer.


As ferramentas de criação de perfil são usadas para determinar onde os gargalos surgem. Os perfis podem ser feitos para todos os fatores listados acima, seja em um ambiente MS Windows ou Linux. Existem muitas ferramentas de sistema operacional e idioma disponíveis para isso, bem como utilitários de terceiros. A escolha da língua será agora discutida no contexto do desempenho.


C ++, Java, Python, R e MatLab contêm bibliotecas de alto desempenho (como parte de seus padrões ou externamente) para estrutura de dados básica e trabalho algorítmico. O C ++ é fornecido com a Biblioteca de Modelos Padrão, enquanto o Python contém o NumPy / SciPy. Tarefas matemáticas comuns são encontradas nessas bibliotecas e raramente é benéfico escrever uma nova implementação.


Uma exceção é se a arquitetura de hardware altamente personalizada for necessária e um algoritmo estiver fazendo uso extensivo de extensões proprietárias (como caches personalizados). No entanto, muitas vezes a "reinvenção da roda" desperdiça tempo que poderia ser mais bem gasto desenvolvendo e otimizando outras partes da infraestrutura de negociação. O tempo de desenvolvimento é extremamente precioso, especialmente no contexto de desenvolvedores únicos.


A latência é frequentemente uma questão do sistema de execução, pois as ferramentas de pesquisa geralmente estão situadas 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 do sistema de mensagens kernal), sinais comerciais enviados (latência NIC) e pedidos processados ​​(latência interna dos sistemas de troca).


Para operações de freqüência mais alta, é necessário tornar-se intimamente familiarizado com a otimização do kernal, bem como com a otimização da transmissão da rede. Esta é uma área profunda e está significativamente além do escopo do artigo, mas se um algoritmo UHFT for desejado, esteja ciente da profundidade do conhecimento necessário!


O cache é muito útil no kit de ferramentas de um desenvolvedor de comércio quantitativo. O armazenamento em cache se refere ao conceito de armazenamento de dados acessados ​​com frequência de uma maneira que permite acesso de maior desempenho, em detrimento do possível enfraquecimento dos dados. Um caso de uso comum ocorre no desenvolvimento da Web ao obter dados de um banco de dados relacional baseado em disco e colocá-lo na memória. Quaisquer solicitações subsequentes para os dados não precisam "atingir o banco de dados" e, portanto, os ganhos de desempenho podem ser significativos.


Para situações de negociação, o armazenamento em cache pode ser extremamente benéfico. Por exemplo, o estado atual de um portfólio de estratégias pode ser armazenado em um cache até que ele seja reequilibrado, de modo que a lista não precise ser regenerada em cada loop do algoritmo de negociação. Essa regeneração provavelmente será uma operação alta de CPU ou E / S de disco.


No entanto, o armazenamento em cache não é isento de seus próprios problemas. A regeneração dos dados em cache de uma só vez, devido à natureza volátil do armazenamento em cache, pode colocar uma demanda significativa na infraestrutura. Outro problema é o empilhamento de cães, em que 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.


Alocação de memória dinâmica é uma operação cara na execução de software. Assim, é imperativo que os aplicativos de negociação de desempenho mais alto conheçam bem como a memória está sendo alocada e desalocada durante o fluxo do programa. Novos padrões de linguagem, como Java, C # e Python, executam a coleta de lixo automática, que se refere à desalocação da memória alocada dinamicamente quando os objetos saem do escopo.


A coleta de lixo é extremamente útil durante o desenvolvimento, pois reduz os erros e ajuda na legibilidade. No entanto, muitas vezes é sub-ótimo para certas estratégias de negociação de alta frequência. A coleta de lixo personalizada é geralmente desejada para esses casos. Em Java, por exemplo, ajustando o coletor de lixo e a configuração de heap, é possível obter alto desempenho para estratégias de HFT.


O C ++ não fornece um coletor de lixo nativo e, portanto, é necessário manipular toda alocação / desalocação de memória como parte da implementação de um objeto. Embora potencialmente sujeito a erros (potencialmente levando a ponteiros pendentes), é extremamente útil ter um controle refinado de como os objetos aparecem no heap para determinados aplicativos. Ao escolher um idioma, certifique-se de estudar como o coletor de lixo funciona e se ele pode ser modificado para otimizar um determinado caso de uso.


Muitas operações em sistemas de negociação algorítmica são passíveis de paralelização. Isto refere-se ao conceito de realizar múltiplas operações programáticas ao mesmo tempo, isto é, em "paralelo". Os chamados algoritmos "embarassingly parallel" incluem etapas que podem ser calculadas de forma totalmente independente de outras etapas. Certas operações estatísticas, como as simulações de Monte Carlo, são um bom exemplo de algoritmos embarassingly paralelos, já que cada sorteio aleatório e a subsequente operação de caminho podem ser computadas sem o conhecimento de outros caminhos.


Outros algoritmos são apenas parcialmente paralelizáveis. Simulações de dinâmica de fluidos são um exemplo, onde o domínio de computação pode ser subdividido, mas, em última instância, esses domínios devem se comunicar entre si e, assim, as operações são parcialmente sequenciais. Os algoritmos paralelizá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 por $ N $ (por exemplo, em um núcleo ou encadeamento da CPU).


A paralelização tornou-se cada vez mais importante como um meio de otimização, uma vez que as velocidades de clock do processador estagnaram, pois os processadores mais recentes contêm muitos núcleos com os quais executar cálculos paralelos. O aumento do hardware gráfico do consumidor (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. Essas GPUs agora são muito acessíveis. Estruturas de alto nível, como o CUDA da Nvidia, levaram à adoção generalizada na academia e nas finanças.


Esse hardware GPU geralmente é adequado apenas para o aspecto de pesquisa de finanças quantitativas, enquanto outros hardwares mais especializados (incluindo Field-Programmable Gate Arrays - FPGAs) são usados ​​para (U) HFT. Atualmente, os idiomas mais modernos suportam um grau de simultaneidade / multithreading. Assim, é fácil otimizar um backtester, já que todos os cálculos são geralmente independentes dos demais.


O dimensionamento em engenharia de software e operações refere-se à capacidade do sistema de manipular cargas crescentes consistentemente na forma de solicitações maiores, maior uso do processador e mais alocação de memória. No comércio algorítmico, uma estratégia é capaz de escalonar se puder aceitar maiores quantidades de capital e ainda produzir retornos consistentes. A pilha de tecnologia de negociação é dimensionada se puder suportar maiores volumes de negócios e maior latência, sem gargalos.


Embora os sistemas devam ser projetados para escalar, muitas vezes é difícil prever antecipadamente onde ocorrerá um gargalo. Registro, testes, criação de perfil e monitoramento rigorosos ajudarão muito a permitir que um sistema seja dimensionado. Os próprios idiomas são geralmente descritos como "não escaláveis". Isso geralmente é resultado de desinformação, e não de fatos concretos. É a pilha total de tecnologia que deve ser verificada para escalabilidade, não para o idioma. É claro que certas linguagens têm um desempenho maior do que outras em casos de uso específicos, mas uma linguagem nunca é "melhor" que outra em todos os sentidos.


Um meio de administrar escala é separar as preocupações, como dito acima. De modo a introduzir ainda a capacidade de lidar com "picos" no sistema (isto é, volatilidade súbita que desencadeia uma série de operações), é útil criar uma "arquitectura de fila de mensagens". Isso significa simplesmente colocar um sistema de fila de mensagens entre os componentes para que os pedidos sejam "empilhados" se um determinado componente não puder processar muitas solicitações.


Em vez de solicitações serem perdidas, elas são simplesmente mantidas em uma pilha até que a mensagem seja manipulada. Isso é particularmente útil para enviar negociações para um mecanismo de execução. Se o motor estiver sofrendo sob latência pesada, ele fará o backup dos negócios. Uma fila entre o gerador de sinais de negociação e a API de execução aliviará essa questão às custas do escorregamento comercial em potencial. Um corretor de fila de mensagens de código aberto bem respeitado é o Rabbit.


Hardware e Sistemas Operacionais.


O hardware que executa sua estratégia pode ter um impacto significativo na lucratividade de seu algoritmo. Este não é um problema restrito a operadores de alta frequência. Uma má escolha em hardware e sistema operacional pode levar a uma falha da máquina ou reinicializar no momento mais inoportuno. Assim, é necessário considerar onde seu aplicativo irá residir. A escolha é geralmente entre uma máquina desktop pessoal, um servidor remoto, um provedor "nuvem" ou um servidor co-localizado em troca.


As máquinas desktop são simples de instalar e administrar, especialmente com sistemas operacionais mais novos e amigáveis ​​ao usuário, como o Windows 7/8, o Mac OSX e o Ubuntu. Sistemas de desktop possuem algumas desvantagens significativas, no entanto. O principal é que as versões dos sistemas operacionais projetados para máquinas de mesa provavelmente exigirão reinicializações / patches (e geralmente no pior dos casos!). Eles também usam mais recursos computacionais pela necessidade de uma interface gráfica de usuário (GUI).


Utilizar hardware em um ambiente doméstico (ou escritório local) pode levar a problemas de conectividade à Internet e de tempo de atividade. O principal benefício de um sistema de desktop é que a potência computacional significativa pode ser adquirida pela fração do custo de um servidor dedicado remoto (ou sistema baseado em nuvem) de velocidade comparável.


Um servidor dedicado ou uma máquina baseada na nuvem, embora frequentemente mais caro do que uma opção de desktop, permite uma infraestrutura de redundância mais significativa, como backups automáticos de dados, a capacidade de garantir mais tempo de atividade e monitoramento remoto. Eles são mais difíceis de administrar, pois exigem a capacidade de usar os recursos de login remoto do sistema operacional.


No Windows, isso geralmente é feito através do protocolo RDP (Remote Desktop Protocol) da GUI. Em sistemas baseados em Unix, a linha de comando Secure SHell (SSH) é usada. A infra-estrutura de servidor baseada em Unix é quase sempre baseada em linha de comando, o que imediatamente torna as ferramentas de programação baseadas em GUI (como MatLab ou Excel) inutilizáveis.


Um servidor co-localizado, como a frase é usada no mercado de capitais, é simplesmente um servidor dedicado que reside dentro de uma troca a fim de reduzir a latência do algoritmo de negociação. Isso é absolutamente necessário para certas estratégias de negociação de alta frequência, que dependem de baixa latência para gerar alfa.


O aspecto final da escolha de hardware e a escolha da linguagem de programação é a independência de plataforma. Existe a necessidade de o código ser executado em vários sistemas operacionais diferentes? O código foi projetado para ser executado em um tipo específico de arquitetura de processador, como o Intel x86 / x64 ou será possível executar em processadores RISC, como os fabricados pela ARM? Essas questões serão altamente dependentes da frequência e do tipo de estratégia que está sendo implementada.


Resiliência e Teste.


Uma das melhores maneiras de perder muito dinheiro em negociações algorítmicas é criar um sistema sem resiliência. Isso se refere à durabilidade do sistema quando sujeito a eventos raros, como falências de corretagem, volatilidade excessiva súbita, tempo de inatividade em toda a região para um provedor de servidor em nuvem ou a exclusão acidental de um banco de dados comercial inteiro. Anos de lucros podem ser eliminados em segundos com uma arquitetura mal projetada. É absolutamente essencial considerar problemas como depuração, teste, registro, backups, alta disponibilidade e monitoramento como componentes principais de seu sistema.


É provável que, em qualquer aplicação de negociação quantitativa personalizada razoavelmente complicada, pelo menos 50% do tempo de desenvolvimento seja gasto em depuração, teste e manutenção.


Quase todas as linguagens de programação vêm com um depurador associado ou possuem alternativas de terceiros bem respeitadas. Em essência, um depurador permite a execução de um programa com a inserção de pontos de interrupção arbitrários no caminho do código, que interrompem temporariamente a execução para investigar o estado do sistema. O principal benefício da depuração é que é possível investigar o comportamento do código antes de um ponto de falha conhecido.


A depuração é um componente essencial na caixa de ferramentas para analisar erros de programação. No entanto, eles são mais amplamente usados ​​em linguagens compiladas, como C ++ ou Java, já que linguagens interpretadas, como Python, geralmente são mais fáceis de depurar devido a menos instruções LOC e menos detalhadas. Apesar dessa tendência, o Python vem com o pdb, que é uma ferramenta sofisticada de depuração. O Microsoft Visual C ++ IDE possui extensos utilitários de depuração de GUI, enquanto para o programador Linux C ++ de linha de comando, existe o depurador gdb.


Testes em desenvolvimento de software referem-se ao processo de aplicar parâmetros e resultados conhecidos a funções, métodos e objetos específicos dentro de uma base de código, para simular comportamento e avaliar múltiplos caminhos de código, ajudando a garantir que um sistema se comporta como deveria. Um paradigma mais recente é conhecido como Test Driven Development (TDD), em que o código de teste é desenvolvido em relação a uma interface especificada sem implementação. Antes da conclusão da base de código real, todos os testes falharão. Como o código é escrito para "preencher os espaços em branco", os testes acabarão por passar, ponto em que o desenvolvimento deve cessar.


O TDD requer um design de especificação inicial extenso, bem como um grau saudável de disciplina, a fim de realizar com sucesso. Em C ++, o Boost fornece uma estrutura de teste de unidade. Em Java, a biblioteca JUnit existe para cumprir o mesmo propósito. O Python também possui o módulo unittest como parte da biblioteca padrão. Muitas outras linguagens possuem estruturas de teste de unidade e muitas vezes há várias opções.


Em um ambiente de produção, o registro sofisticado é absolutamente essencial. O registro refere-se ao processo de saída de mensagens, com vários graus de gravidade, em relação ao comportamento de execução de um sistema para um arquivo ou banco de dados simples. Os logs são uma "primeira linha de ataque" ao procurar um comportamento inesperado do tempo de execução do programa. Infelizmente, as deficiências de um sistema de extração de madeira tendem a ser descobertas após o fato! Como com os backups discutidos abaixo, um sistema de registro deve ser considerado antes de um sistema ser projetado.


Tanto o Microsoft Windows quanto o Linux vêm com um amplo recurso de registro do sistema, e as linguagens de programação tendem a ser fornecidas com bibliotecas de registro padrão que cobrem a maioria dos casos de uso. É sempre aconselhável centralizar as informações de registro para analisá-las em uma data posterior, pois elas podem levar a idéias sobre como melhorar o desempenho ou a redução de erros, o que quase certamente terá um impacto positivo em seus retornos de negociação.


Embora o registro de um sistema forneça informações sobre o que aconteceu no passado, o monitoramento de um aplicativo fornecerá informações sobre o que está acontecendo no momento. Todos os aspectos do sistema devem ser considerados para monitoramento. Métricas no nível do sistema, como uso do disco, memória disponível, largura de banda da rede e uso da CPU, fornecem informações básicas sobre carga.


Métricas de negociação, como preços / volume anormais, levantamentos repentinos rápidos e exposição de contas para diferentes setores / mercados também devem ser continuamente monitorados. Além disso, deve ser instigado um sistema de limite que forneça notificação quando certas métricas forem violadas, elevando o método de notificação (email, SMS, chamada telefônica automatizada), dependendo da gravidade da métrica.


O monitoramento do sistema é geralmente o domínio do administrador do sistema ou do gerenciador de operações. No entanto, como um desenvolvedor comercial exclusivo, essas métricas devem ser estabelecidas como parte do design maior. Existem muitas soluções para monitoramento: proprietárias, hospedadas e de código aberto, que permitem a personalização extensiva de métricas para um caso de uso específico.


Backups e alta disponibilidade devem ser as principais preocupações de um sistema de negociação. 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. NET 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. NET 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.


Participe do portal de associação da Quantcademy que atende à crescente comunidade de traders de quantificação de varejo e aprenda como aumentar a lucratividade de sua estratégia.


Negociação Algorítmica Bem Sucedida.


Como encontrar novas ideias de estratégia de negociação e avaliá-las objetivamente para o seu portfólio usando um mecanismo de backtesting personalizado no Python.


Comércio Algorítmico Avançado.


Como implementar estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas Bayesianas com R e Python.


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".


Sistemas de Execução.


The job of the execution system is to receive filtered trading signals from the portfolio construction and risk management components and send them on to a brokerage or other means of market access. For the majority of retail algorithmic trading strategies this involves an API or FIX connection to a brokerage such as Interactive Brokers. The primary considerations when deciding upon a language include quality of the API, language-wrapper availability for an API, execution frequency and the anticipated slippage.


The "quality" of the API refers to how well documented it is, what sort of performance it provides, whether it needs standalone software to be accessed or whether a gateway can be established in a headless fashion (i. e. no GUI). In the case of Interactive Brokers, the Trader WorkStation tool needs to be running in a GUI environment in order to access their API. I once had to install a Desktop Ubuntu edition onto an Amazon cloud server to access Interactive Brokers remotely, purely for this reason!


Most APIs will provide a C++ and/or Java interface. It is usually up to the community to develop language-specific wrappers for C#, Python, R, Excel and MatLab. Note that with every additional plugin utilised (especially API wrappers) there is scope for bugs to creep into the system. Always test plugins of this sort and ensure they are actively maintained. A worthwhile gauge is to see how many new updates to a codebase have been made in recent months.


Execution frequency is of the utmost importance in the execution algorithm. Note that hundreds of orders may be sent every minute and as such performance is critical. Slippage will be incurred through a badly-performing execution system and this will have a dramatic impact on profitability.


Statically-typed languages (see below) such as C++/Java are generally optimal for execution but there is a trade-off in development time, testing and ease of maintenance. Dynamically-typed languages, such as Python and Perl are now generally "fast enough". Always make sure the components are designed in a modular fashion (see below) so that they can be "swapped out" out as the system scales.


Architectural Planning and Development Process.


The components of a trading system, its frequency and volume requirements have been discussed above, but system infrastructure has yet to be covered. Those acting as a retail trader or working in a small fund will likely be "wearing many hats". It will be necessary to be covering the alpha model, risk management and execution parameters, and also the final implementation of the system. Before delving into specific languages the design of an optimal system architecture will be discussed.


Separation of Concerns.


One of the most important decisions that must be made at the outset is how to "separate the concerns" of a trading system. 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, Zero 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 Rabbit.


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. NET 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. NET 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.


Participe do portal de associação da Quantcademy que atende à crescente comunidade de traders de quantificação de varejo e aprenda como aumentar a lucratividade de sua estratégia.


Negociação Algorítmica Bem Sucedida.


Como encontrar novas ideias de estratégia de negociação e avaliá-las objetivamente para o seu portfólio usando um mecanismo de backtesting personalizado no Python.


Comércio Algorítmico Avançado.


Como implementar estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas Bayesianas com R e Python.


Trading software for building.


stock, futures, index and forex trading systems.


using technical analysis indicators and neural networks.


NeuroShell Trader is software for building trading systems. It is not a trading system in its own right, it is a toolkit of both traditional and Artificial Intelligence (AI) technues you can combine to form computerized trading systems.


NeuroShell Trader will build trading systems for stocks, FOREX, futures, commodities, options, indexes and more. You can build trading systems for exchanges all over the world, like the NYSE, AMEX, FTSE, DAX, ASX, TSX, SFE, and many more.


The trading systems can consist of standard technical analysis indicators and rules like traders have used for years, artificial intelligence technues like neural networks, or hybrids of both. The trading systems you build will automatically back-test, and continue to give signals into the future as new data arrives.


Trading models generally are built using technical analysis indicators based upon the raw data and other instrument data. Let's say you believe that the following indicators will be useful in models that will produce stock market trading signals:


The spread between each target stock and INTC The relative strength between each target stock and $DJUCR A stochastic %k indicator applied to each target stock.


Therefore, the next thing you might do is insert the indicators above into your chart using the Indicator Wizard. The Indicator Wizard contains over 800 standard indicators from which to choose.


Trading and Prediction Systems.


Easy to build rule based trading systems, advanced neural network predictive trading models or hybrid systems that combine both.


Neural Networks.


Find patterns in your data to predict future values or other data streams.


Why use a neural network? If you have a set of favorite indicators but don’t have a set of trading rules to create a profitable trading system, neural networks can build the trading rules for you. Neural networks can help you find patterns in your data. They are an indispensable tool for predicting and forecasting future values.


We do our own neural network research. Our newest neural network type, Turboprop 2, is probably the best neural network on the planet. It is very fast. Most neural networks train in 5-20 seconds. No neural network based on the now very old backprop paradigm can come close to our neural networks. Why is speed important? Because when you are optimizing, you may be training hundreds or even thousands of neural networks, which would literally be impossible with the old backpropagation neural network algorithm.


The Turboprop 2 neural network is very accurate (assuming you have relevant inputs of course), and it gives you a numeric contribution value for each input, so you can intelligently decide amongst inputs. Our genetic algorithm optimizer will also help you decide. Turboprop 2 also has mechanisms to help prevent overfitting. You don't need a "test" set plus a "validation" or "evaluation" set to prevent overfitting with the Turboprop 2 neural network. Turboprop 2 can also train on the basis of increasing profit as well as reducing error.


Turboprop 2 has no parameters whatsoever to tweak to make the neural network run. No need to be a neural network expert; inserting a neural network prediction or forecast is as easy as inserting an indicator.


Algorítmos genéticos.


Faster optimization of predictions, trading systems and technical indicators.


Today's markets are tougher than ever to analyze. NeuroShell Trader gives you an edge with three different genetic algorithm based optimizers to fine tune YOUR trading ideas. You can optimize your trading systems to maximize profit, minimize drawdown, or choose from the more than 30 other objectives.


Speed is essential when you’re evaluating a large number of trading systems. Our Genetic Algorithm, Evolution Strategy and Swarm Optimization technues are all capable of fine tuning a large number of trading system variables in far less time than traditional brute force optimizers (also included) that try every possible combination. The genetic algorithm based optimizers can find the time periods for indicators and at the same time determine which rules should be used in the trading strategy. The Trader can also search for optimal stop and limit prices for your trading systems.


Charts are the major component of NeuroShell. You may open many charts at one time, either new ones or ones you have previously built and saved. When you create a new chart, you specify their periodicity with which you want to see and process the data, as well as how far back in time you want to load the data. Next you specify the related instruments whose historical data should be loaded into the chart. They are the target instruments for which you wish to create trading signals.


Multiple instruments in the chart show up in their own chart page. For example, let's say you load IBM, DELL, HPQ, and AAPL as your target instruments. (They don't have to be stocks; they can be FOREX pairs, commodities, E-minis, options, etc). Note that you can insert several different models in a chart. Once you insert a model, it automatically applies to all chart pages.


Chart B ased.


Upgrades to the NeuroShell Trader Power User and NeuroShell DayTrader Power User versions are available which allow the software to distribute the optimization processing of complex financial models over your local area network. The result is a significant decrease in the amount of time it takes to create and update trading systems as market conditions change.


Let’s say your local network has three computers attached, a 12 core machine and two quad core machines. That is a total of 20 cores, all of which can be searching for your optimum trading model simultaneously. The faster computers will handle a higher share of the load. You have control over which of the computers on the network you want to participate, and which you do not want to participate.


Choose from three different network versions of NeuroShell Trader depending on the power and speed you require:


Network Distributed Optimization.


Even faster optimization of large complex models with distributed processing across multiple computers.


Once the chart loads up with the requested data, you are ready to define one or more models in the chart. Any model that you build in the chart automatically applies to all instruments in the chart. Your model can be optimized the same for all chart pages, or custom optimized for each chart page. Models can be either Trading Strategies or Predictions. Note that you can insert several models in a chart. Once you insert a model, it automatically applies to all chart pages.


You may or may not have a clue about how the indicators you have chosen work. If you do, you probably have some idea about how they would be used to generate trading signals, rules like "Buy when the relative strength between the stock and the $DJUCR is high, and the spread with INTC is low." In this case you will want your model(s) to be Trading Strategies, even if you are unsure what values should be considered high and low above. The genetic optimizer will find the values for you. If you either have no clue about how the indicators work, or no clue about appropriate rules for them, you will probably want to build a Prediction with a neural net for your model(s), because neural nets find their own rules.


Indicadores de Análise Técnica.


Over 800 indicators.


Trading Strategy Wizard.


Prediction Wizard.


The Trading Strategy Wizard is a fast mechanism for entering trading rules without having to type messy formulas or write in some algorithmic programming-like language.


The Wizard is all point and click. You just list the rules for long entry, long exit, short entry, and short exit (cover). Each of these rules is in fact an indicator you build just like any other indicator - with the Indicator Wizard. You can also enter indicators for stop and limit price levels, including trailing stops.


If you want to optimize your trading strategies, the genetic optimizer will do these things for you:


Find which of the rules you have listed should be used in combination Find out what the parameters of the indicators in your rules should be set to Perform both of the above at the same time (we call this full optimization) Even your stops and limits can be optimized.


When the Trading Strategy is complete, it will show you historical buy and sell signals. As new data is added to the chart, those buy and sell signals will continue to appear with each new bar. You can insert a variety of indicators to plot how your profit is growing.


Predictions are neural nets made with the Prediction Wizard. That's what our standard neural nets do, they make predictions about the future value of a data stream, usually a price or change in price, but any data stream can be predicted. Here is basically all you have to do to make a prediction model:


Choose some inputs - data streams, usually indicators, that you believe are leading indicators of the market Decide what you want to predict, usually change or percent change of the open or close Decide how much historical data will be used to train the neural net Decide how much historical data you want to use to test how well the neural net has learned.


If you want to optimize your prediction, the genetic optimizer will do these things for you:


Find which inputs you listed should be used in combination Find which indicator parameters values should be set to Perform both of the above at the same time Find neural network thresholds for trading.


When the prediction is complete, it will show you historical buy and sell signals. As new data arrives in the future, those buy and sell signals will continue to appear with each new bar. You can insert a variety of indicators to plot how your profit is growing.


Sometimes when you build traditional trading systems, neural network models, or optimized models of any type, it is possible to make a model so good that it does not hold up with future market conditions. This is called overfitting. NeuroShell lets you hold some data outside of the system building process (called out-of-sample data). Therefore, NeuroShell contains facilities that will automatically backtest with out-of-sample data for you, so you can gain confidence that your model will hold up in the future.


Our optimizer also works in a mode we call "paper trading". In this mode, the optimizer keeps the trading system that works better in a period of time after the optimization period, rather than the optimal (peak) model. Paper trading automatically gives you a trading system that is less likely to be overfit, and more likely to work well into the future.


Out-of-Sample Backtesting.


Determine if your trading system holds up in future trading before risking real money.


Trader Power User and Trader Professional allow you to create end of day charts with daily, weekly, and monthly charts.


DayTrader Power User and DayTrader Professional works with both end of day, weekly and monthly charts and intra day charts that have hour, minute, second, volume and range bars.


End of Day and Intra Day Charts.


NeuroShell lets you take almost any condition, not just trading signals, and define an alert to let you know when that condition has just occurred.


Visual and sound notification of important events.


Once you have developed a model that you are happy with, you can specify that trades be sent to your broker’s account for execution, with the fill price being returned to NeuroShell. The trades can be sent automatically, or only after you approve them. As an alternative, NeuroShell will email your trades to email addresses of your choice.


Currently NeuroShell Trader has Interactive Brokers, FXCM and TradeStation integrated and other brokers are available from ZagTrader. Direct connections to more brokers are being developed.


Integrated Trading.


Automatically send trades to your favorite brokerage while you’re out on the golf course.


Your charts can mix and match multiple time frames in data streams, indicators, predictions, and trading strategies as well as other instrument data. The NeuroShell Trader Power User mixes daily, weekly, and monthly timeframes, while the NeuroShell DayTrader Power User can include multiple intraday timeframes as well. For example, the Trader Power User lets you combine daily and weekly bars in the same trading system. The DayTrader Power User version can create a single trading system with minute, hour, and range bars. Think of the possibilities.


Análise de múltiplos períodos de tempo.


Combine different timeframes of data, indicators, predictions, and trading strategies into one chart or analysis.


You can select from over fifteen different sizing methods. If you don’t know how many shares, contracts, or units to buy with each trade, let the optimizer decide the most profitable method.


Gerenciamento Avançado de Dinheiro.


Control the money allocated to each trade.


Fixed Size Fixed Dollar Percent of Account Fixed Leverage Fixed Fractional Kelly formula Optimal f.


Secure f Profit Risk Volatility Risk Fixed Ratio Margin + Drawdown Sizing Fixed Dollar Amount per Unit Fixed Dollar Fixed Dollar Risk.


Pyramiding and scaling options add the ability to either enter or exit trades with more than one order. If you’re uncertain which of the pyramiding or position sizing methods to use, the Trader’s optimizer can assist in your decision process.


Pyramiding and Position Scaling.


Enter or exit trades with multiple orders.


If you want to evaluate your model’s performance on a Trading Strategy that is re-optimized regularly on newer data, and then applied to out-of-sample data, you can use the Walk Forward Optimization feature.


For example, you can backtest reoptimizing a Trading Strategy every week for the past 10 weeks. After each reoptimization, the Trading Strategy is applied to data for the following week. The NeuroShell Trader Power User will perform 11 total optimizations in this case, each shifted by one week. Ten of those optimizations will show the “actual” trading results had you traded the reoptimized model for the week following the optimization period. The final optimization is optimized up to the very last date so you can go forward into the future trading a model that has been optimized on the very latest data in the same manner as the prior 10 simulated optimizations.


This feature can also be applied to intraday bars if you own the NeuroShell DayTrader Power User version.


Caminhar em frente Otimização.


Evaluate performance on systems that re-optimized regularly on newer data, and then applied to out-of-sample data.


The Power User versions include a “batch” mode of reoptimizing and backtesting models you’ve created previously.


Simply save the model as a chart template. Save templates for ALL of the models you wish to incorporate in this batch process. To begin the batch process, simply select all of the templates you wish to include in the batch on the first page of the Trading Strategy wizard. You’ll have the option to modify the dates, costs, and optimization parameters that you wish to use during optimization of all of the templates. You DO NOT have to rebuild each model.


After the models are backtested and you have analyzed the results, you can check the templates you wish to see displayed in a chart.


Batch Processing.


Optimize and back test multiple trading strategy templates on multiple instruments in one continuous process.


NeuroShell Trader allows you to distribute optimization processing across multiple computer cores and multiple hyper threads on a single computer.


As an example, if you have an Intel Core i7 processor, which has 4 processing cores each with the ability to process two simultaneous hyper threads, the NeuroShell Trader optimization processing could be spread out to 8 different threads. Theoretically, you could realize up to an 8x speed increase in optimization on a Core i7 computer, however due to the overhead of controlling, setup, and communication with each distributed thread, the speed increase may approach, but will never reach 8x. (You also have options to limit the number of cores/hyperthreads utilized during optimization if you want to use other programs during optimization without any processor sharing.)


For even faster optimization, see Network Distributed Optimization described below.


Multicore Distributed Optimization.


Lightning fast optimization of complex models with distributed processing across multiple cores of a single computer.


COMBINE RULES AND NEURAL NETS - You can build hybrid trading systems that involve neural network predictions as well as standard rules.


HYBRID MODELS - Since everything in NeuroShell is a data stream, there are many ways to build hybrid models by feeding the results of one wizard into another wizard. Indicators can go into other indicators, predictions and trading rules can go into indicators, trading signals can go into other trading rules, etc., etc.


PANEL OF EXPERTS - You can build a "panel of experts" - a strategy that consults several other strategies or neural networks to see what the majority predicts.


PAIRS TRADING - You can build pairs trading models and even optimize them.


PORTFOLIO MODELS - You can build portfolio models, where the model looks at a basket of stocks and takes a position in one or more of them based upon their relative position in the basket (relative position can be based upon one or more indicators or neural nets.) These portfolio models can be hedged to be market neutral, so that at a given time there are an equal number of long and short positions.


CROSS MARKET OPTIMIZATION - You can optimize each instrument in the chart individually, or do one general optimization that results in the same model for all instruments in the chart.


INTRADAY MODELS - You can build intraday models with the NeuroShell DayTrader Professional to make decisions about direction of the market at specified times of the day.


DATA EXPORTING - You can export data, indicators, signals, equity curves, etc. from NeuroShell into text files for processing in Excel, statistical programs, or other trading systems.


DATA IMPORTING - You can load text files of indicators or signals from other programs into NeuroShell in many cases.


CUSTOM INDICATOR API - Sometimes you may have in mind indicators that are too complex even for our Indicator Wizard to construct. In that case, you can program your own in standard languages like C++, Power Basic, and other languages capable of creating dynamic link libraries.


CUSTOM BROKERAGE API - If you don't want to use our connected brokers and have another broker you'd rather send trades to automatically, you or your programmers may be able to use our programmable "Trade Pump" to program your own custom brokerage interface.


CUSTOM DATA FEED API - We also have a programmable interface called the "Data Pump" which may allow you or your programmer to build a custom data interface to an intraday data provider not already supported by NeuroShell.


Use YOUR rules, indicators, and formulas to analyze today’s volatile markets, without writing any code. Instead, use our point and click “wizards” for indicators, predictions, and trading systems. For example, create multiple variations of the same indicator, such as 9 and 13 period moving averages, in one pass through the indicator wizard.


The indicator wizard allows you to build complex indicators by combining a number of the 800 included indicators. You can save these “custom” indicators for use in other trading systems. The prediction and trading strategy wizards also allow entire systems to be combined, so you can build “ensemble” systems with more power to find profitable trades. Save your favorites as templates for later use.

Комментариев нет:

Отправить комментарий