Sunday 23 July 2017

C # Trading System Tutorial


Os sistemas de negociação que projetam seu sistema - Parte 1. A seção precedente deste tutorial olhou os elementos que compõem um sistema de troca e discutiu as vantagens e as desvantagens de usar tal sistema em um ambiente de troca vivo Nesta seção, nós fundamos nesse conhecimento Examinando quais os mercados são especialmente bem adaptados para o sistema de negociação Vamos então ter um olhar mais aprofundado sobre os diferentes gêneros de trading systems. Trading em mercados diferentes. Mercado de ações O mercado de ações é provavelmente o mercado mais comum para o comércio, Especialmente entre os novatos Nesta arena, grandes jogadores como Warren Buffett e Merrill Lynch dominam, e valor tradicional e estratégias de investimento de crescimento são de longe o mais comum No entanto, muitas instituições têm investido significativamente na concepção, desenvolvimento e implementação de sistemas de negociação Investidores individuais Estão se juntando a esta tendência, embora lentamente. Aqui estão alguns fatores-chave para se manter em mente quando se utilizam sistemas de negociação no mercado de ações S. A grande quantidade de ações disponíveis permite que os comerciantes para testar sistemas em muitos tipos diferentes de ações - tudo de extremamente volátil over-the-counter stocks OTC para chips blue não-voláteis. A eficácia dos sistemas de negociação pode ser limitada pela baixa liquidez De algumas ações, especialmente OTC e folhas-de-rosa sheet emissões podem comer em lucros gerados por negócios bem sucedidos, e pode aumentar as perdas OTC e pink folha equities freqüentemente incorrer taxas de comissão adicionais. Os principais sistemas de negociação utilizados são aqueles que procuram valor - ou seja, sistemas Que usam parâmetros diferentes para determinar se uma segurança é subvalorizada em comparação com seu desempenho passado, seus pares, ou o mercado em geral. Mercados de câmbio estrangeiros O mercado de câmbio, ou forex é o mercado maior e mais líquido do mundo Os governos do mundo s , Os bancos e outras grandes instituições comércio trilhões de dólares no mercado cambial todos os dias A maioria dos comerciantes institucionais no forex confiar em trad O mesmo vale para os indivíduos no forex, mas alguns com base em relatórios econômicos ou payouts. Here alguns fatores-chave para se manter em mente ao usar sistemas de negociação no mercado forex. A liquidez neste mercado - devido à enorme Por conseguinte, é muito mais fácil fazer muitas transações sem aumentar os custospared à quantidade de ações ou commodities disponíveis, o número de moedas para o comércio é limitado Mas por causa da disponibilidade de pares de moedas exóticas - ou seja, as moedas de países menores - a gama em termos de volatilidade não é necessariamente limitado. Os principais sistemas de negociação utilizados no forex são aqueles que seguem as tendências um ditado popular no mercado é a tendência É seu amigo, ou sistemas que compram ou vendem em fugas Isto é porque os indicadores econômicos causam frequentemente movimentos grandes do preço em um time. Futures equidade, forex, e mercadoria Todos os mercados de oferta de negociação de futuros Este é um veículo popular para o sistema de negociação por causa da maior quantidade de alavancagem disponível e maior liquidez e volatilidade No entanto, esses fatores podem cortar ambas as maneiras que podem ou amplificar seus ganhos ou amplificar suas perdas Por esta razão, O uso de futuros é geralmente reservado para os comerciantes avançados do sistema individual e institucional Isso ocorre porque os sistemas de negociação capazes de capitalizar no mercado de futuros exigem personalização muito maior, usar indicadores mais avançados e demorar muito mais para desenvolver Então, Cada indivíduo tem suas próprias vantagens e desvantagens A maioria das pessoas estão mais familiarizados com os mercados de ações, e esta familiaridade torna o desenvolvimento de um sistema de negociação mais fácil No entanto, forex é comumente pensado para ser a plataforma superior Para operar sistemas de negociação - especialmente entre os comerciantes mais experientes Além disso, se um comerciante decide tapar Italy no aumento da alavancagem e volatilidade, a alternativa de futuros é sempre aberto Finalmente, a escolha está nas mãos do sistema developer. Types of Trading Systems. Trend-Seguindo Sistemas O método mais comum de sistema de negociação é a tendência de seguir o sistema Em sua Forma mais fundamental, este sistema simplesmente espera por um movimento de preços significativos, em seguida, compra ou vende nessa direção Este tipo de bancos de sistema na esperança de que esses movimentos de preços irá manter a tendência. Moving Média Sistemas Freqüentemente utilizado na análise técnica uma média móvel é Um indicador que simplesmente mostra o preço médio de um estoque durante um período de tempo A essência das tendências é derivado desta medida A maneira mais comum de determinar a entrada ea saída é um crossover A lógica por trás disso é simples uma nova tendência é estabelecida quando o preço Cai acima ou abaixo de sua tendência de preço médio histórico Aqui está um gráfico que traça tanto a linha de preço azul ea linha vermelha MA de 20 dias da IBM. Breakout Systems The Conceito fundamental por trás deste tipo de sistema é semelhante ao de um sistema de média móvel A idéia é que, quando um novo alto ou baixo é estabelecido, o movimento de preços é mais provável que continue na direção da fuga Um indicador que pode ser usado em Determinando fugas é uma banda de Bollinger simples Bollinger Bands mostrar médias de preços altos e baixos, e breakouts ocorrem quando o preço atende as bordas das bandas Aqui está um gráfico que traça preço linha azul e Bollinger Bands linhas cinzentas de Microsoft. Disadvantages de Trend - Seguindo Sistemas. Necessidade de Decisão Específica - Ao determinar as tendências, há sempre um elemento empírico para considerar a duração da tendência histórica. Por exemplo, a média móvel pode ser nos últimos 20 dias ou nos últimos cinco anos, de modo que o desenvolvedor Deve determinar qual é o melhor para o sistema Outros fatores a serem determinados são os altos e baixos médios em sistemas breakout. Lagging Nature - médias móveis e sistemas breakout wi Vai sempre estar atrasado Em outras palavras, eles nunca podem atingir o topo exato ou inferior de uma tendência Isso inevitavelmente resulta em uma perda de lucros potenciais, o que às vezes pode ser significativo. Efeito Whipsaw - Entre as forças de mercado que são prejudiciais ao sucesso de O efeito whipsaw ocorre quando a média móvel gera um sinal falso - ou seja, quando a média cai apenas na faixa, em seguida, repentinamente inverte direção Isso pode levar a perdas maciças, a menos que eficaz parar - Perdas e técnicas de gerenciamento de risco são empregados. Mercados de lado - Os sistemas de tendência seguinte são, por natureza, capazes de ganhar dinheiro apenas em mercados que realmente fazem tendência. No entanto, os mercados também se movem de lado permanecendo dentro de um certo intervalo por um longo período de tempo. A volatilidade pode ocorrer - Ocasionalmente, os sistemas que seguem tendências podem experimentar alguma volatilidade extrema, mas o profissional deve ficar com seu sistema. A incapacidade de fazê-lo resultará em Falha garantida. Sistemas de Telecontroles Basicamente, o objetivo com o sistema de contra-tendência é comprar no mais baixo baixo e vender no mais alto alto A principal diferença entre este e o sistema de tendência seguinte é que o sistema de contra-tendência não é auto - , Não há tempo definido para sair de posições, e isso resulta em um potencial downside ilimitado Tipos de sistemas de contra-tendência Muitos tipos diferentes de sistemas são considerados sistemas de contra-tendência A ideia aqui é comprar quando momentum em uma direção começa desvanecendo Isso é mais frequentemente calculado usando Osciladores Por exemplo, um sinal pode ser gerado quando stochastics ou outros indicadores de força relativa caem abaixo de certos pontos Existem outros tipos de sistemas de negociação countertrend, mas todos eles compartilham o mesmo objetivo fundamental - para comprar baixo e vender high. Disadvantages de Countertrend Seguindo Systems. E mpirical Decision-Making Required - Por exemplo, um dos fatores que o desenvolvedor do sistema deve decidir é o ponto Ts em que os indicadores de força relativa fade. Extreme volatilidade pode ocorrer - Estes sistemas também podem experimentar alguma volatilidade extrema, e uma incapacidade de ficar com o sistema, apesar desta volatilidade resultará em falha garantida. Downside ilimitado - Como mencionado anteriormente, há ilimitado Downside potencial, porque o sistema não é auto-corrigir não há tempo definido para sair positions. Conclusion Os principais mercados para os quais os sistemas de negociação são adequados são os mercados de ações, forex e futuros Cada um desses mercados tem suas vantagens e desvantagens Os dois principais gêneros Dos sistemas de negociação são os sistemas de tendência e contra-tendência. Apesar de suas diferenças, ambos os tipos de sistemas, em seus estágios de desenvolvimento, exigem tomada de decisão empírica por parte do desenvolvedor. Além disso, esses sistemas estão sujeitos a extrema volatilidade e isso pode exigir alguns Stamina - é essencial que o comerciante do sistema fique com o seu sistema durante estes tempos No seguinte i Nstallment, vamos dar uma olhada em como projetar um sistema de negociação e discutir alguns dos softwares que os comerciantes do sistema usam para tornar suas vidas mais fáceis. Short Answer Introdução ao Algorithmic Trading com Heikin-Ashi Guia breve que leva você de iniciante a quase Quant Ele fornece um ambiente de desenvolvimento livre, mostra como construir um indicador técnico e como criar uma estratégia de negociação automatizada Neste post Quora eu tenho uma repartição maior de como começar. Resposta mais longa Para se tornar verdadeiramente proficiente no desenvolvimento de estratégias de negociação algorítmica , Você vai precisar de algum conhecimento de fundo Isso pode ser pego ao longo do tempo e não é crucial ter todo o conhecimento do mercado dominado antes de começar. Aprender os Mercados. Há toneladas de recursos para isso, e é precisamente por isso que você deve ser um Pouco cuidado sobre o que os livros que você escolhe para pegar e ler Ajusal s resposta tem uma repartição de alguns grandes bookse Into My Trading Room por Alexander Eldar - Fantástico primeiro livro para ninguém ne W para a negociação Dr. Alexander Elder pontes a lacuna entre os fundamentos do mercado e tornando-se rentável a partir de exploração de indicadores técnicos. Além disso, aqui s uma lista de leitura agregada PDF com uma repartição completa de livros, vídeos, cursos e fóruns de negociação. Learn to Program. I recommend Python ou MATLAB, embora possivelmente Python é mais versátil MATLAB é muito poderoso e usado por lojas de quant para pesquisa e desenvolvimento de estratégias de negociação Também se você está vindo de qualquer tipo de academia, você provavelmente já tem exposição a MATLAB. Learn Python - Python tutorial destinado a qualquer pessoa a aprender a linguagem de programação Live exemplos de código pode ser executado e testado direito em seu browser. MATLAB Guia de Início Rápido - introdução rápida e completa em linha para MATLAB com abundância de exemplos de código para obter o seu pé Mais intuitiva e direta MATLAB Intro available. Get um Trading Platform. I m tendenciosa e eu recomendo Quantiacs, é uma plataforma livre de código aberto para Pyt Hon e MATLAB com dados históricos O tutorial ligado abaixo pressupõe que você estará usando Quantiacs e fornece código construído para ele, mas as lições aprendidas devem ser aplicáveis ​​a qualquer outra plataforma também. Primeiro, primeiro, você vai precisar instalar o Quantiacs Toolbox Este é um processo relativamente simples que só deve levar alguns minutos Você tem a opção de usar Python ou MATLAB, e a menos que você já investiu pesadamente em apenas um eu recomendo baixar e instalar ambos Go instalar a toolbox. Intro para o Quantiacs Toolbox. Tomar um olhar para a estrutura de um sistema de negociação de exemplo aqui em Python e aqui em MATLAB Os principais componentes de qualquer algoritmo Quantiacs são as configurações, mercados e posições Para MATLAB e Python, o seu algoritmo de negociação vive em apenas um arquivo que segue Este modelo geral Para uma repartição da caixa de ferramentas visite aqui Saiba mais sobre a caixa de ferramentas aqui deve ser bastante simples. Este Quora post 1 tem uma detalhada desagregação de Todas as melhores práticas para realmente testar o seu algoritmo após e durante o desenvolvimento Sugestões incluem o uso de análise em andamento, na amostra e fora da amostra de teste, e como medir o desempenho em geral. Em Quora post 2 eu escrevi alguns dos Os desafios que você enfrenta na construção de sistemas de negociação automatizados que geralmente não são explicitamente conhecidos até que você começar Aqueles incluem garantia de borda, como factor de capital e os custos de negociação, e como não ser destruído pelos profissionais de negociação contra os perigos you. The Curve Fitting. Apenas uma nota de lado para alertar sobre a armadilha comum de desenvolvimento de estratégia de quant é overfitting Uma estratégia de ajuste de curva é aquele que foi otimizado tão bem, ele se encaixa perfeitamente o desempenho passado dos mercados O resultado final é que ele vai falhar completamente com o futuro Ação de preço e eventos de mercado Overfitting produzirá backtesting resultados fantásticos de estratégias de negociação irrealistas e não rentáveis. Ele geralmente gira em torno de mudar parâmetros como O período de uma média móvel até que o desempenho do algoritmo de negociação melhora significativamente Embora a otimização de estratégias em si é uma prática válida, ele tem que ser realizado com cuidado para evitar overfitting. Here s que overfitting pode fazer - pode levar esta estratégia de comércio não rentável. Esta estratégia otimizada nunca funcionaria no mundo real. O momento em que a data de início do backtest é transferida para fora por alguns anos, toda a borda do mercado percebida se evapora. Arbitrariamente caça para bons resultados de backtesting é uma prática perigosa e Não produzirá estratégias verdadeiramente lucrativas. Disclaimer Eu trabalho na Quantiacs. Once você está pronto para ganhar dinheiro como um quant, você pode participar o mais recente concurso de negociação Quantiacs automatizado, com um total de 2.250.000 em investimentos disponíveis Você pode competir com os melhores quants.14 6k Views View Upvotes Not for Reprodução. A minha viagem como um quant me levou a ler um vasto número de livros disponíveis sobre este assunto que eu vim para descobrir que, embora haja um monte de bons livros lá fora, que realmente ajudá-lo a obter informações úteis, existem ainda mais livros Que são apenas puro material de marketing do jogo empurrado para baixo as gargantas do leitor ignorante. São minhas recomendações de livros, categorizados com base em diferentes aspectos do negócio que você pode estar interessado em understanding. Basics Para o leigo que é novo para este campo e Quer um headstart 1 Dentro da caixa preta por Rishi Narang - grande livro para um headstart em todos os aspectos diferentes de negociar do quant Muito informação geral, mas escova geralmente através de cada aspecto do negócio 2 Quantitative Trading por Ernie Chan - Livro perfeito para começar em todos os conceitos básicos com detalhes sobre backtesting e algumas estratégias simples para começar em with. Programming Depends, que plataforma você deseja usar Há toneladas de livros e tutoriais on-line disponíveis em cada Linguagem de programação Eu recomendo o seguinte em Python e Java 1 Aprendendo Python por Mark Lutz - Fundamentos básicos de python Bom para você começar 2 Head First Java por Kathy Sierra - Grande livro sobre JAVA, desde o básico até avançado. Microestrutura do mercado Antes de você Aprender mais sobre estratégias de algo, é mais importante entender como negociação funciona e como os diferentes interessados ​​interagem uns com os outros para criar um mercado Trading and Exchanges por Larry Harris - cobre microestrutura de mercado em grave profundidade A deve ler antes de mergulhar em estratégias para obter Uma boa compreensão do markets. Strategies bons livros sobre estratégias de natureza variada Momentum, Tendência seguinte, Pairs Trading, gregos, etc I Também categorizaram esses livros com base no tipo de estratégias que os livros focalizam em 1 Algorithmic Trading por Ernie Chan - Um livro mais avançado por Ernie, com uma série de estratégias interessantes para testar e backtest Lote de boa teoria explicando os conceitos básicos por trás A existência de diferentes tipos de comportamento de mercado e como captá-los. 2 Mechanical Trading Systems por Richard Weissman - Um grande livro para estratégias Abrange uma infinidade de estratégias de reversão de momentum e média em vários quadros de tempo, juntamente com resultados de backtested 3 Next The Trend by Andreas Clenow - Eu considero este livro, um dos melhores lê sobre o tema de tendência seguinte, uma estratégia de negociação muito popular 4 Pairs Trading por Ganapathy Vidyamurthy - Muito bom livro sobre uma estratégia de negociação popular conhecido como Pairs Trading 5 Como ganhar dinheiro em ações por William O Neil - uma leitura excelente em um fundamentos muito interessantes baseou o modelo do quant, chamado CANSLIM. Options estratégias eu cubro estratégias das opções sob um 1 Volatilidade Opções e Preços por Sheldon Natenberg - Um dos melhores livros sobre as opções para um iniciante, trabalhando seu caminho até o básico até o fim até os gregos e negociação de volatilidade 2 A Bíblia de Opções Estratégias por Guy Cohen - Um bom livro para chegar até a velocidade em todas as configurações de opções diferentes e seus gregos específicos 3 Volatilidade Trading por Euan Sinclair - Livro muito avançado e em profundidade sobre o conceito de Volatilidade Trading Eu acredito que seja O melhor sobre este assunto. Gerenciamento de Risco O aspecto mais importante do comércio de quant que muitas vezes é esquecido Posição de dimensionamento por Van Tharp - Uma jóia de um livro que explica a idéia de gestão de risco e gestão de dinheiro usando técnicas diferentes. Meu conselho para um algo budding Comerciante seria a investigação cuidadosamente antes de ir ao vivo com uma estratégia Considere-se um gerente de risco, em vez de um gerente de dinheiro Gerenciando risco vem em primeiro lugar, em seguida, venha retu Rns.23 5k Vistas Ver Upvotes Não para Reproduction. Full Disclaimer Eu não sou um comerciante quanti ou algo eu só tenho ajudado um monte de pessoas para obter melhor em algo comercial engenheiro cliente em Quantopian Aqui sa algumas coisas que eu vi de meu Experience. Read Aqui estão dois livros que eu vi recomendado muito I ll dar-lhe o título ea razão pela qual. Algorithmic Trading estratégias vencedoras e sua fundamentação por Ernie Chan abrange todo o piso térreo desde o início para as estratégias algorítmicas mais avançadas Literalmente , Ele vai levá-lo de Eu não tenho idéia de que tipo de estratégia que eu poderia usar para Okay, eu tenho a escolha entre o momento, par negociação, estratégias de reversão média Qual é o melhor para o meu portfólio e metas agora Eu não estou brincando, isso é Um bom livro introdutório ea bibliografia irá levá-lo onde você precisa ir. Python For Data Analysis Este é menos específico para algo comercial, mas eu estou supondo que você vai estar usando algum tipo de sistema baseado em código e honestamente, Pytho N é a maneira mais fácil e mais simples de ir. Começar a praticar Os melhores comerciantes de algo que eu vi são aqueles que criaram muitos e muitos algoritmos Tinkering, tentando, falhando Estas são todas as coisas que o ajudam a craft suas estratégias da infância a possível Alfa Gerando sistemas Eu conheço principalmente duas fontes onde as pessoas começam a sua prática, mais uma vez, eu trabalho em Quantopian. Zipline, que é um open-source Python Algorithmic Trading Library que qualquer um pode usar Ela também poderes o backtester motor atrás Quantopian que me leva a minha Próximo ponto. Quantopian, que fornece a plataforma, dados e IDE para você testar suas estratégias em Python e executá-lo com dinheiro real, se você acha que tem algo Downside é que você terá que aprender o Quantopian métodos API específicas Upside é que Não há muito a aprender e há uma tonelada de tutoriais para ajudá-lo através dele. Coloque o seu dinheiro por trás Take pequenas somas e realmente colocar alguma pele no jogo Backtesting e tal é bom, mas você l Eu penso diferente uma vez que você tem algo a perder Feynman tem uma boa citação sobre isso. Eu poderia fazer isso, mas eu ganhei t, --que é apenas uma outra maneira de dizer que você pode t - Apenas dizendo o seu algoritmo pode ganhar dinheiro é diferente Do que realmente ganhar dinheiro. Então, se você falhar, aprender com ele e repetir o processo Se você ganhar, ser cauteloso que um dia você poderia falhar. Apenas algumas observações de ver as pessoas passam pelo processo uma e outra vez.18 5k Vistas View Upvotes Não para Reproduction. Justin Medlin comerciante sistemático, membro fundador da. Eu aprecio a A2A, o momento é fortuito. Estamos envolvidos em um provável um tempo de Estratégia de Criação Projeto de Colaboração iniciando 01 de abril de 2017, e ainda têm slots abrir É totalmente gratuito e irá guiá-lo através da configuração de uma plataforma de negociação e feed de dados se você não já fez isso e, em seguida, orientá-lo todo o processo de criação da Estratégia de Negociação Automatizada, do início ao fim, de forma colaborativa. Nós estaremos fornecendo Cipants com ferramentas que podem usar para ajudar a descobrir as condições de saída de entrada mais vantajosas, e estará escolhendo o mais ótima dessas submissões de usuário em cada etapa ao longo do caminho, buscando criar uma estratégia de negociação robusta e totalmente funcional a partir do zero, que Será distribuído a todos os participantes, mesmo aqueles que se sentam à margem um observar no final do processo, que eles podem usar para o comércio em tempo real através de uma conta de simulação de comércio por favor, não viver dinheiro. Mais importante, os usuários serão Capaz de submeter perguntas e receber respostas, à medida que avançamos do estágio de desenvolvimento para o estágio de desenvolvimento, para que todos vejam Nossa esperança é fazer deste um processo de aprendizagem extremamente eficiente para todos os envolvidos e quem sabe, podemos até encontrar alguma força na força de colaboração Da variedade de mentes e do poder de computação coletivo envolvido, e produzir algo impressionante. Uma das razões pelas quais estamos fazendo isso é porque não estamos cientes de mais nada lá fora que Abrange todas as bases, pelo menos, sem cobrança em fazê-lo, embora eu sugiro dar uma olhada no Denis post para uma lista mais abrangente do que está atualmente lá fora, admiravelmente compilado. Eu também recomendaria encontrar um fórum de discussão de qualidade, embora Eles parecem estar em falta Eu sou fã de futuros como ele parece ser bastante ativo, e tem uma base de usuários relativamente competente contribuindo, quase todos os quais são amigáveis, paciente, útil. Como Denis mencionou em sua resposta, é O contexto de conhecimento de fundo que é tudo importante, ea única maneira de cultivar isso é uma combinação de prática deliberada, e tempo para que eu aconselho fortemente apenas mergulhar em uma plataforma Ninjatrader pode ser mais intuitivo, MatLab mais poderoso, e eu acredito Quantiacs para Estar em seus estágios iniciais, mas com um futuro brilhante quase qualquer plataforma popular vai fazer, para os estágios iniciais e ficar sujo as mãos, você vai se surpreender com o quanto você recolher a partir de tal processo, e quão rapidamente o valioso co Eu acho que se o processo é genuinamente interessante e ressoa com você, não se pode ajudar, mas cavar mais fundo e aprender mais, organicamente não se torna mais uma tarefa, ou o menos um pouco tedioso, mas sim algo intelectualmente gratificante e Fascinante e de lá em diante, o aprendizado é fácil. Visualizações View Upvotes Não é para a reprodução. Aqui está a lista de livros. Este livro descreve o ciclo completo de validar uma idéia de negociação, testes, medição, otimização trading strategies. It inclui lotes de Grandes idéias e ponteiros em cada único passo no processo. Eu gostaria de ter lido o livro muito mais cedo, não há muito tempo que eu li alguma coisa lá que eu pensei que eu criei-me E então há sa técnica mais alguns avanços que eu Ve nunca though sobre escrito there. This é um dos primeiros livros que eu li sobre os tópicos, que é simples o suficiente para entender e cobre os pontos mais importantes Muito bom introdutório. Eu li este livro recentemente depois eu ve followin G Ernie in Quora, para ser honesto, eu não li o livro inteiro, mas escolhi aqueles tópicos que eu interessei. É um bom complemento aos dois livros acima, o que explica alguns tópicos melhores do que os dois acima. Se você quiser saber mais Sobre certos tópicos em negociação algorítmica, a minha experiência é que você ve ler vários livros de autor diferentes, mesmo sobre o mesmo tema Não há nenhum livro único que cobrem tudo, mas cada livro dar-lhe algo. Eu tenho uma lista de livros mais longo pendente de escrita , Mas acho que os três acima deve ser mais do que suficiente para você começar com. Só quero adicionar, existem alguns sites e livros sobre esses temas realmente querem vender-lhe serviços ou software, o conteúdo desses livros são apenas marketing Material Mas os livros que eu listei acima são verdadeiramente educativos O autor é tão grande que colocar material de qualidade sobre o livro.3 6k Vistas Ver Upvotes Não para Reprodução. Eu recomendo começar com os conceitos básicos de análise técnica Alguns livros tha T Eu encontrei útil no seguinte ordere em minha sala de negociação Um guia completo para negociação por Alexander Elder - Adequado como um primeiro livro para alguém completamente novo para trading. Technical Análise dos Mercados Financeiros Um Guia Completo de Métodos de Negociação e Aplicações por John J Murphy - Introduz o leitor para uma ampla gama de técnicas utilizadas na análise técnica, um bom ponto de partida antes de escolher a direção. No lado de programação. Eu recomendaria para começar com uma plataforma onde o comerciante pode implementar várias estratégias em um ambiente fornecido Essas plataformas são TradeStation ou NinjaTrader por exemplo. Essas plataformas têm muitos construídos em recursos, por exemplo, gráficos, etc corretor conexões, por isso são relativamente fáceis de aprender e conveniente para use. If alguém chegou a este nível, então eu acredito que ele já é capaz Para decidir se a negociação é para ele ou não e se sim, em seguida, que direção ele pretende tomar. Além disso, será necessário para o comerciante para Cuidadosamente estudar e usar uma linguagem de programação eg C, C, C ou Java para citar alguns. Em seguida, será necessário estabelecer uma metodologias de negociação própria e abordagem, quais técnicas usar, como usá-los e como melhorá-los ainda mais Para estar à frente dos outros Este é um assunto amplo e complexo e todas as técnicas diferentes não podem ser incluídos em um guia único. Se alguém está definitivamente à procura de um guia de um livro, eles podem tentar ir para a Amazônia e tipo de negociação algorítmica A pesquisa Isto trará até um bom poucos livros dedicados ao assunto que eu nunca li qualquer um destes, mas tanto quanto me lembro, com base nos comentários, alguns deles introduzem um determinado método e guiá-lo passo a passo como Implementá-lo. Independentemente do caminho que você tomar, estar preparado para que no final você terá que fazer sua própria pesquisa, implementar suas próprias idéias e colocar no trabalho extra que é preciso para se tornar um comerciante bem sucedido.16 1k Views View Upvotes Not Para a reprodução. Eu o ajudarei a entender Os fundamentos da negociação algorítmica, seus benefícios em comparação com a negociação manual e alguns dos mitos comuns associados com Algorithmic Trading Leia mais abaixo. O que é Algorithmic Trading. Algorithmic Trading é um processo para comprar ou vender uma segurança com base em algum conjunto pré-definido Por exemplo, suponha que você tenha um plano de negociação que você iria comprar um determinado estoque se ele fecha em vermelho por 5 dias consecutivos Você Pode formular essa regra no sistema de negociação algorítmica e até mesmo automatizá-lo para que ordem de compra é colocado automaticamente quando sua condição é cumprida Você pode até mesmo definir seu stoploss, alvo e dimensionamento de posição no algoritmo que faria sua vida de negociação mais fácil. Algorithmic Trading benefícios. É dito que o seu sucesso na negociação depende de 30 análise de mercado, gestão de risco 30, controle de emoção 30 e sorte 10 Se mantivermos a sorte de lado, t Hen Sistemas algorítmicos podem cuidar do resto 90 A maioria dos comerciantes falham quando as emoções intervêm em suas decisões de negociação Mesmo os comerciantes experientes pânico ao pressionar botão Comprar Vender que eventualmente leva à perda Além disso, os comerciantes tendem a ignorar stoploss ou reservar os lucros início que é novamente Uma desvantagem de negociação manual Sistemas algorítmicos vai cuidar de todos esses inconvenientes associados com o comércio manual Além disso, se você estiver ocupado com o seu dia de trabalho e não pode dedicar tempo à negociação, então você pode simplesmente automatizar o seu algoritmo para que seu computador pode negociar em nome De você. Algorithmic Trading vs Manual Trading. Below comparação tabela explicaria claramente as diferenças entre Algorithmic e Manual Trading. Is Algorithmic e automatizado trading similar. This é o mis-concepção mais comum associado Algorithmic Trading Algorithmic e Automated trading não são mesmo Você Sempre tem uma opção para automatizar sua estratégia algorítmica, mas não é necessário Você pode até mesmo negociar manualmente t Através dos sinais gerados através de seu sistema algorítmico Para automatizar sua estratégia algorítmica você tem que obter uma permuta de aprovação para o seu algoritmo Mas isso não é um processo difícil até que seu algoritmo é livre de erros Então, da próxima vez que você se deparar com um sistema de negociação algorítmica, Basta dar uma olhada se ele é automatizado ou manual. Algorithmic Trading Examples. Please referem-se os links abaixo para algumas das configurações rentáveis ​​Algorithmic Estes são construídos em Amibroker ou Excel Sheet. Algorithmic Trading Myths. Below são alguns dos mitos mais comuns associados com Algorithmic Trading. Algorithmic Trading é complexo e requer profundo conhecimento matemático e estatístico. Não, ele não é Você pode até mesmo converter suas regras de negociação simples em Algoritmos e comércio através dele. Algorithmic Trading exige enorme capital. No Você pode até comprar quantidades muito pequenas usando Algorithmic Trading. Algorithmic Trading não é para comerciantes de varejo. É para todos Apenas no caso de você deseja automatizar y Nosso algoritmo você precisaria do terminal do negociante de exchange. Algorithmic Trading exige super computadores rápidos e infrastructure. This pode ser necessária apenas se você estiver fazendo a negociação de alta freqüência usando algoritmos Para qualquer outra coisa o seu PC é suficiente.2 1k Views View Upvotes Não para reprodução. Programadores de software são capazes de ganhar remunerações que são exponencialmente mais elevados do que as de suas outras profissões A escassez de proficiência técnica é alarmante ea ausência de fatores motivacionais é ainda maior O revestimento de prata desta nuvem cinzenta é limitado ao fato de que isso significa que goliath As empresas estão em prowl desesperada para profissionais eficientes com habilidade refinada set. If você está olhando para os salários Tutorials. With livre que variam em qualquer lugar entre Rs 111,389 todo o caminho até Rs 722,959 um pode t ajudar, mas admirar o potencial do mercado para Programadores de software e analisar ainda mais a mesma Análise dos fatores que ajudam a facilitar a transição no mercado of software development, is necessary, for example Become a Master In BIG DATA Click HERE. one must research all the potential courses that will help them approach a wide scope of career opportunities, therefore one must also admire the fact that, programming is the only way forward to develop ones portfolio and therefore further develop ones career. One must also entertain the possibility of taking on an entrepreneurial endeavor today millions of professional and graduates aim to make their way towards the freelance world The fiscal opportunities of which surpass even that of the full time professional contracts Even in consideration of non-technical enterprises, programmers are constantly finding opportunities in organizations that are updating and implementing state-of the art techniques in their operations. After considering this, one can t be oblivious to the benefits of the affiliations to any one of the decades and centuries old organizations, which command their own historical pre sence that provides an individual with a sense of belonging and enhances their importance The software programmers today are finding career opportunities in firms that are making transitions from traditional organizational cultures and environments to that of modernization and globalization This is the reason programmers are taking advance to refine and update their skill-sets In this scenario it is obvious that for programmers, it is and always will be a seller s market, with opportunities at their disposal.766 Views Not for Reproduction. 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 r egarding 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 b ased 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 compon ent 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 int eractive 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 syste ms 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 importa nt part of an algorithmic trading system Risk can come in many forms Increased volatility although this may be seen as desirable for certain strategies , increased correlations between asset classes, counter-party default, server outages, black swan events and undetected bugs in the trading code, to name a few. Risk management components try and anticipate the effects of excessive volatility and correlation between asset classes and their subsequent effect s on trading capital Often this reduces to a set of statistical computations such as Monte Carlo stress tests This is very similar to the computational needs of a derivatives pricing engine and as such will be CPU-bound These simulations are highly parallelisable see below and, to a certain degree, it is possible to throw hardware at the problem. Execution Systems. The job of the execution system is to receive filtered trading signals from the portfolio construction and risk management components and send them on to a brokerage or other means of market access For the majority of retail algorithmic trading strategies this involves an API or FIX connection to a brokerage such as Interactive Brokers The primary considerations when deciding upon a language include quality of the API, language-wrapper availability for an API, execution frequency and the anticipated slippage. The quality of the API refers to how well documented it is, what sort of performance it provides, whether it needs standalone software to be accessed or whether a gateway can be established in a headless fashion i e no GUI In the case of Interactive Brokers, the Trader WorkStation tool needs to be running in a GUI environment in order to access their API I once had to install a Desktop Ubuntu edition onto an Amazon cloud server to access Interactive Brokers remotely, purely for this reason. Most APIs will provide a C and or Java interface It is usually up to the community to develop language-specific wrappers for C , Python, R, Excel and MatLab Note tha t 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 pract ice 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 lang uages to be used in the overall system There is no need to be restricted to a single language if the communication method of the components is language independent This will be the case if they are communicating via TCP IP, ZeroMQ or some other language-independent protocol. As a concrete example, consider the case of a backtesting system being written in C for number crunching performance, while the portfolio manager and execution systems are written in Python using SciPy and IBPy. Performance Considerations. Performance is a significant consideration for most trading strategies For higher frequency strategies it is the most important factor Performance covers a wide range of issues, such as algorithmic execution speed, network latency, bandwidth, data I O, concurrency parallelism and scaling Each of these areas are individually covered by large textbooks, so this article will only scratch the surface of each topic Architecture and language choice will now be discussed in terms of their effects on performance. The prevailing wisdom as stated by Donald Knuth one of the fathers of Computer Science, is that premature optimisation is the root of all evil This is almost always the case - except when building a high frequency trading algorithm For those who are interested in lower frequency strategies, a common approach is to build a system in the simplest way possible and only optimise as bottlenecks begin to appear. Profiling tools are used to determine where bottlenecks arise Profiles can be made for all of the factors listed above, either in a MS Windows or Linux environment There are many operating system and language tools available to do so, as well as third party utilities Language choice will now be discussed in the context of performance. C , Java, Python, R and MatLab all contain high-performance libraries either as part of their standard or externally for basic data structure and algorithmic work C ships with the Standard Template Library, while Python contains Num Py 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 h igh 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 cas es 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 high ly 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, witho ut bottlenecking. While systems must be designed to scale, it is often hard to predict beforehand where a bottleneck will occur Rigourous logging, testing, profiling and monitoring will aid greatly in allowing a system to scale Languages themselves are often described as unscalable This is usually the result of misinformation, rather than hard fact It is the total technology stack that should be ascertained for scalability, not the language Clearly certain languages have greater performance than others in particular use cases, but one language is never better than another in every sense. One means of managing scale is to separate concerns, as stated above In order to further introduce the ability to handle spikes in the system i e sudden volatility which triggers a raft of trades , it is useful to create a message queuing architecture This simply means placing a message queue system between components so that orders are stacked up if a certain component is unable to process many requests. Rather than requests being lost they are simply kept in a stack until the message is handled This is particularly useful for sending trades to an execution engine If the engine is suffering under heavy latency then it will back up trades A queue between the trade signal generator and the execution API will alleviate this issue at the expense of potential trade slippage A well-respected open source message queue broker is RabbitMQ. Hardware and Operating Systems. The hardware running your strategy can have a significant impact on the profitability of your algorithm This is not an issue restricted to high frequency traders either A poor choice in hardware and operating system can lead to a machine crash or reboot at the most inopportune moment Thus it is necessary to consider where your application will reside The choice is generally between a personal desktop machine, a remote server, a cloud provider or an exchange co-located server. Desktop machines are simple to install and administer, especially with newer user friendly operating systems such as Windows 7 8, Mac OSX and Ubuntu Desktop systems do possess some significant drawbacks, however The foremost is that the versions of operating systems designed for desktop machines are likely to require reboots patching and often at the worst of times They also use up more computational resources by the virtue of requiring a graphical user interface GUI. Utilising hardware in a home or local office environment can lead to internet connectivity and power uptime problems The main benefit of a desktop system is that significant computational horsepower can be purchased for the fraction of the cost of a remote dedicated server or cloud based system of comparable speed. A dedicated server or cloud-based machine, while often more expensive than a desktop option, allows for more significant redundancy infrastructure, such as automated data backups, the ability to more straightforwardly ensure uptime and remote monitoring They are har der 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 wi ll 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 wh at 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 Nu mPy 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 There are advantages and disadvantages to both approaches It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensing maintenance costs. The Microsoft stack including Visual C , Visual C and MathWorks MatLab are two of the larger proprietary choices for developing custom algorithmic trading software Both tools have had significant battle testing in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds. Microsoft and MathWorks both provide extensive high qua lity documentation for their products Further, the communities surrounding each tool are very large with active web forums for both The software allows cohesive integration with multiple languages such as C , C and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ MatLab also has many plugins libraries some free, some commercial for nearly any quantitative research domain. There are also drawbacks With either piece of software the costs are not insignificant for a lone trader although Microsoft does provide entry-level version of Visual Studio for free Microsoft tools play well with each other, but integrate less well with external code Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned. MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithm ic 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 developmen t 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 environment s 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, 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 rel ational databases, such as MySQL MySQL C , JDBC Java MatLab , MySQLdb MySQL Python and psychopg2 PostgreSQL Python Python can even communicate with R via the RPy plugin. An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API Most APIs natively support C and Java, but some also support C and Python, either directly or with community-provided wrapper code to the C APIs In particular, Interactive Brokers can be connected to via the IBPy plugin If high-performance is required, brokerages will support the FIX protocol. As is now evident, the choice of programming language s for an algorithmic trading system is not straightforward and requires deep thought The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries. The benefit of a separated architecture is that it allows langua ges 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. Just Getting Started with Quantitative Trading.

No comments:

Post a Comment