Estratégias de negociação quantitativa na r parte 1 de 3


Estratégias Quantitativas de Negociação na Parte R 1 de 3.


Categoria: Documentos.


Financiamento Computacional e Gerenciamento de Riscos mm 40 60 80 100 120 Estratégias Quantitativas de Negociação em R 40 Parte 1 de 3 60 Guy Yollin Consultor Principal, r-programming Professor Visitante, Universidade de Washington 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em Quantstrat R - I 1/72 Contorno mm 40 60 80 100 120 1 O pacote de absorção 40 2 O pacote quantstrat 60 3 Análise de desempenho 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 2/72 Pacotes para desenvolvimento de sistemas de negociação em R mm PerformanceAnalytics: Ferramentas econométricas para análise de desempenho e risco 40 Métricas e gráficos de desempenho 60 80 100 120 quantstrat: modelo de estratégia quantitativa blotter: ferramentas para desenvolvimento de sistemas de negociação orientados a transações 40 Quantitative trading rules e trading quantmod: estrutura de modelagem financeira quantitativa TTR : regras técnicas de negociação 60 Acesso a dados, gráficos, indicadores xts: séries temporais extensíveis 80 zoo: order ob servations Objetos de séries temporais Guy Yollin (Copyright © 2011) Quantitative Trading Strategies in R quantstrat-I 3/72 Sobre blotter e quantstrat mm 40 80 100 Infraestrutura de transação para 60 instrumentos de definição, transações, 120 portfólios e contas para sistemas de negociação e simulação. Fornece suporte de portfólio para portfólios de várias classes de ativos e várias moedas. Ainda em desenvolvimento pesado. O software está em um estágio alfa / beta algumas coisas não são completamente implementadas (ou documentadas) algumas coisas invariavelmente possuem erros que algumas implementações irão mudar no futuro 60 40 O software está em desenvolvimento há vários anos. Fev-2010 Software é usado todos os dias por profissionais que trabalham na gestão de ativos 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 4/72 Referências bibliográficas mm 40 60 100 Página do projeto TradeAnalytics em R-forja: 80 r-forge. r-project / projetos / blotter / documentos e demonstrações para: 40 pacote blotter pacote quantstrat 120 R-SIG-FINANCE: stat. ethz. ch/mailman/listinfo/r-sig-finance 60 Tim Russell Timely Portfólio blog: timelyportfolio. blogspot / exemplo quantstrat de 6 partes 80 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas no R quantstrat-I 5/72 Contorno mm 40 60 80 100 120 1 O pacote de blotter 40 2 O pacote quantstrat 60 3 Analítica de desempenho 80 Guy Yollin ( Copyright © 2011 Estratégias de Negociação Quantitativas em R quantstrat-I 6/72 O pacote de blotter mm 40 60 80 100 120 Descrição Infraestrutura de transação para definir instrumentos, transações, portfólios e contas para sistemas de negociação e simulação. Fornece suporte de portfólio para portfólios de várias classes de ativos e várias moedas. Os principais recursos suportam portfólios de vários ativos. As contas de múltiplos portfólios suportam cálculos e roll-up de P & L. 60 Autores Peter Carl Brian Peterson 80 40 Guy Yollin (Copyright © 2011) Quantitative Trading Strategies in R quantstrat-I 7/72 Fluxo de trabalho de backtesting de estratégia básica para blotter mm 40 60 80 100 120 Inicialização Processamento barra a barra Relatório 40 Inicializar moeda e instrumentos e carregar dados do histórico Inicializar portfólio e conta Verificar preços e indicadores para verificar se Compra ou Venda acionados Atualizar posição e patrimônio Fim de dados Gerar relatórios de desempenho e gráficos 60 80 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 8/72 Principais funções de blotter mmFunction initPortf initAcct 40 40 getPosQty addTxn updatePortf updateAcct updateEndEq getEndEq 60 chart. Posn PortfReturns getAccount getPortfolio getTxns tradeStats 80 60 80 100 Descrição Inicialização inicializa um objeto de portfólio inicializa um objeto de conta Proc essing recupera o valor mais recente da conta de capital obtém posição em Data adiciona transações a um portfólio calcula o resultado para cada símbolo para cada período calcula o patrimônio líquido dos dados do portfólio atualiza o patrimônio líquido para uma conta Dados do mercado do gráfico de análise, tamanho da posição e P & L cumulativo retornos de instrumento de portfólio obter um objeto de conta do ambiente. blotter obter um objeto de portfólio do ambiente. blotter recuperar transações de um portfólio calcular estatísticas de comércio 120 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 9/72 blotter package R Código: mm> biblioteca (blotter)> search () [1] [3] [5] [7] [9] [11] [13] [15] pacote ".GlobalEnv" "package: FinancialInstrument" " : Pacote "40" TTR: pacote "xts": stats "" pacote: grDevices "" pacote: datasets "" Pacotes automáticos "" pacote: blotter "" pacote: quantmod "" pacote: Padrões "" pacote: zoológico "" pacote: gráficos "" pacote: utils "" pacote: métodos "" pacote: base "40 60 80 100 120 6 0 O blotter de carregamento faz com que essas outras bibliotecas sejam carregadas automaticamente Instrumento Quantitative TTR 80 Instrumento Financeiro xts zoo Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 10/72 O ambiente. blotter e. instrument mm 40 60 80 100 120 O pacote blotter cria um ambiente chamado. blotter para armazenamento privado de objetos de portfólio e de conta. Da mesma forma, 40 o pacote FinancialInstrument cria um ambiente chamado instrumento para armazenamento privado de instrumentos definidos (por exemplo, moeda, estoque, futuro, etc.) R Código: 60 ".instrumento"> ls (todos = T) [1] ".blotter" 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 11/72 Fluxo de trabalho de backtesting de estratégia básica para blotter mm 40 60 80 100 120 Inicialização Processamento barra a barra Relatórios 40 Inicializar moeda e instrumentos e carregar dados do histórico Inicializar portfólio e conta Verificar preços e indicadores para ver se Compra ou Venda acionada Atualizar posição e patrimônio Finalizar de Dados Gerar relatórios e gráficos de desempenho 60 80 Guy Yollin (Copyright © 2011) Quantitative Trading Strategies em R quantstrat-I 12/72 Construtores de classe de instrumento O pacote FinancialInstrument oferece a facilidade de lidar com vários tipos de instrumentos e diferentes moedas mm 40 60 80 100 120 R Código: Construtores de instrumentos> função args (currency) (primary_id, currency = NULL, multiplicador = 1, identificadores = NULL,.) 40 NULL> função args (stock) (primary_id, currency = NULL, multiplicador = 1, ti ck_size = 0.01, identificadores = NULL,. ) 60 NULL Argumentos principais: cadeia de caracteres de ID primária fornecendo um ID exclusivo para a moeda do instrumento 80 string descrevendo o multiplicador numérico do multiplicador de ID da moeda (multiplicador × preço = valores nocionais) aumento do tick do preço do instrumento Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 13/72 Inicializar o instrumento monetário R Código:> moeda ("USD") mm 40 60 80 100 120 [1] "USD"> get ("USD", envir =.instrument) $ primary_id [1] "USD" $ currency [1] "USD" $ multiplicador [1] 1 $ tick_size [1] 0.01 $ identificadores NULL 40 60 80 $ tipo [1] "moeda" attr (, "classe") Guy Yollin (Copyright © 2011) Quantitative Trading Strategies na R quantstrat-I 14/72 Initialize the trading instrument R Código:> estoque ("SPY", moeda = "USD", multiplicador = 1) mm 40 60 80 100 120 [1] " SPY "> get (" SPY ", envir =.instrument) $ primary_id [1]" SPY "$ currency [1]" USD "$ multiplicador [1] 1 $ tick_size [1] 0.01 $ lista de identificadores () 40 60 80 $ type [1] "stock" attr (, "classe") Guy Yolli n (Copyright © 2011) Quantitative Trading Strategies em R quantstrat-I 15/72 Buscar dados históricos R Código: mm 40 60 80 100 120> getSymbols ('SPY', de = '1998-01-01', to = '2011 -07-31 ', ajuste = T)> SPY = a. mês (SPY, indexAt =' endof ')> SPY $ SMA10m cauda (SPY) 40 SPY. Open 2011-02-28 128.2641 2011-03-31 132.3362 2011 -04-29 132.7519 2011-05-31 136.3938 2011-06-3060 133.8464 2011-07-29 132.0900 SPY. High 133.4458 132.5031 135.8963 136.5033 134.2544 135.7000 SPY. Low SPY. Fechar SPY. Volume SPY. Adjusted SMA10m 128.1849 131.9201 2846131894 131.92 114.9287 124.1228 131.9359 4825610492 131.94 117.4512 128.8711 135.7570 2826839043 135.76 120.9079 130.7319 134.2345 3354154109 134.23 123.5213 125.6968 131.9700 4723424476 131.97 126.3944 127.9700 129.3300 3840839000 129.33 128.0790 Nota conversão de dados diários para dados mensais usando o último dia de negociação do mês (funcionalidade xts) 80 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativa em R quantstrat-I 16/72 Backtesting de estratégia básica w Fluxo ork para blotter mm 40 60 80 100 120 Inicialização Processamento barra a barra Relatórios 40 Inicializar moeda e instrumentos e carregar dados do histórico Inicializar carteira e conta Verificar preços e indicadores para ver se Buy or Sell triggered Atualizar posição e patrimônio Fim dos dados Gerar relatórios e gráficos de desempenho 60 80 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 17/72 A função initPortf A função initPortf constrói e inicializa um objeto de portfólio, que é usado para conter transações, posições e nível de agregação. valores. 120 mm 40 60 100 R Código: A função initPortf> args (initPortf) function (name = "default", símbolos, initPosQty = 0, initDate = "1950-01-01", 40 currency = "USD",.) NULL Argumentos principais: nome símbolos 60 nome para o objeto de portfólio resultante lista de símbolos a serem incluídos no portfólio initPosQty quantidade de posição inicial initDate 80 data para patrimônio de conta inicial e posição (antes do primeiro preço de fechamento) moeda identificadora Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 18/72 A função initAcct A função initAcct constrói o contêiner de dados usado para armazenar valores calculados de conta como 60 P & L agregado, patrimônio líquido, 100 etc. mm 40 80 R Código: A função initAcct> args (initAcct) function (name = "default", portfólios, initDate = "1950-01-01", 40 initEq = 0, currency = "USD",.) NULL 120 Argumentos principais: nome initDate initEq currency 80 60 nome para o vetor de portfólios de objetos de conta resultante do portfólio de nomenclatura de cadeias de caracteres s incluídos nesta data de conta para o patrimônio da conta inicial e posição (antes do primeiro preço de fechamento) identificador inicial da conta identificada por Guy Yollin (Copyright © 2011) Quantitative Trading Strategies na R quantstrat-I 19/72 Initialize portfolio and account mm R Code :> b. strategy initPortf (b. strategy, 'SPY', initDate = '1997-12-31') 40 [1] "bFaber"> initAcct (b. estratégia, portfolios = b. strategy, initDate = '1997- 12-31 ', initEq = 1e6) [1] "bFaber" 40 60 80 100 120 60 Observe que o initDate é anterior ao início dos dados 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 20 / 72 O ambiente. blotter e. instrument R Código: mm> ls () [1] "SPY"> ls (.blotter) "b. estratégia" 40 60 80 100 120 40 [1] "account. bFaber"> ls (.instrument) [1] "SPY" "USD" "portfolio. bFaber" 60 vários objetos (incluindo o preço histórico xts objeto) armazenados no portfólio de ambiente global e objetos de conta armazenados em. blotter moeda ambiente e instrumento de negociação o objetos armazenados no ambiente. instrument 80 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 21/72 Fluxo de trabalho de backtesting de estratégia básica para blotter mm 40 60 80 100 120 Inicialização Processamento Bar-by-bar Relatórios 40 Inicializar moeda e instrumentos e carregar dados históricos Inicializar portfólio e conta Verificar preços e indicadores para ver se Buy or Sell triggered Atualizar posição e equidade Fim dos dados Gerar relatórios de desempenho e gráficos 60 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 22/72 Inventário mensal SPY e 10 meses SMA mm 40 60 80 100 120 R Código:>>>>>>> tema chart_Posn (b. strategy, Symbol = 'SPY', Datas = '1998 ::')> enredo (add_SMA (n = 10, col = 4, on = 1, lwd = 2)) 60 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 31/72 Performance plot SPY 140 1998−01−30 / 2011−07−29 mm 40 60 80 100 120 130 120 115 140 130 120 110 110 105 100 100 90 40 95 90 85 80 80 75 70 70 1000 800 600 400 200 0 120000 Posicionamento 1000 qqqqqqqq 1000 800 600 400 200 60 qqqqqqq 0 120000 100000 80000 60000 CumPL 98314.97275 100000 80000 60000 40000 20000 0 1998 Jan 1998 Jul 1998 Jan 1999 1999 Jul 1999 Jan 2000 2000 Jul 2000 Jan 2001 2001 Jul 2003 Jan 2002 2002 Jul 2002 Jan 2003 2003 Jul 2003 Jan 2004 2004 Jul 2004 Jan 2005 2005 Jul 2005 Jan 2006 2006 Jul 2006 Jan 2007 2007 Jul 2007 Jan 2008 2008 Jul 2008 Jan 2009 2009 Jul 2009 Jan 2010 2010 Jul 2010 2011 Jan 2011 Jul 2011 80 40000 20000 0 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 32/72 Transações Código R: mm Txn. Qty 1997-12-31 0 1998-10-30 1000 1999-09-3040 -1000 1999-10-29 1000 2000-09-29 -1000 2002-03-28 1000 2002-04-30 -1000 2003-04-30 1000 2004-08-3160 -1000 2004-09-30 1000 2007-12 -31 -1000 2009-06-30 1000 2010-06-30 -1000 2010-07-30 1000 2010-08-3180 -1000 2010-09-30 1000 40 60 80 100 120> getTxns (Portfólio = b. estratégia, Símbolo = "SPY") Txn. Price Txn. Fees Tx n Valor Txn. Avg. Cost Net. Txn. Realized. PL 0,00000 0,00 0,00000 0,000 89,25095 0 89250,95 95,25095 0,000 105,61590 0 -105615,90 105,61590 16364,941 112,38352 0 112383,52 112,38352 0,000 118,98858 0 -118988,58 118,98858 6605,062 96,28988 0 96289,88 96,28988 0,000 90,69007 0 - 90.690,07 90,69007 78,59565 -5599,813 0 78595,65 0,000 78,59565 96,86532 0 -96865,32 96,86532 97,83755 0 18269,669 97837,55 97,83755 0,000 136,15069 0 -136150,69 136,15069 38313,139 88811,19 0 88,81119 88,81119 0,000 101,18979 0 -101189,79 101,18979 12378,598 108,10113 0 108101,13 108,10113 0,000 103,23868 0 -103238,68 103,23868 -4.862,443 112,48419 0 112484.19 112.48419 0,000 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em Quantstrat R I 33/72 Contorno mm 40 60 80 100 120 1 O pacote de absorção 40 2 O pacote quantstrat 60 3 Análise de Desempenho 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 34/72 O pacote quantstrat mm 40 60 80 100 120 Descrição Specif y, construir e fazer back-teste de estratégias quantitativas de negociação e carteira financeira. Os principais recursos suportam estratégias que incluem indicadores, sinais e regras que permitem que as estratégias sejam aplicadas aos portfólios que alavancam o pacote de registros para contabilidade comercial. I 35/72 Fluxo de trabalho de backtesting de estratégia básica para quantstrat mm 40 60 80 100 120 Inicialização Definir estratégia Processamento barra a barra Relatórios de atualização 40 Inicializar moeda e instrumentos e carregar dados históricos Inicializar portfólio, conta, ordens, estratégia Adicionar indicadores, sinais, e regras Aplicar estratégia ao portfólio Atualizar carteira, conta, patrimônio Gerar relatórios de desempenho e gráficos 60 80 Guy Yollin (Copyright © 2011) Quantitativas Estratégias de Negociação em R quantstrat-I 36/72 Principais funções de quantstrat mm Função 40 Iniciativas estratégia 40 add. signal add. rule add. indicator sigComparison sigCrossover 60 sigFormula sigPeak sigThreshold ruleSignal osNoOp 80 applyStrategy 60 80 100 Descrição Inicialização inicializar contêiner de contêineres de pedidos para objeto estratégico Definição de estratégia adicionar um indicador a uma estratégia adicionar um sinal a uma estratégia adicionar uma regra a uma estratégia Funções padrão gerar sinal de comparação gerar um sinal de cruzamento gerar um sinal de uma função de sinal de fórmula sinais de pico / vale geram uma regra padrão de sinal de limiar para gerar uma ordem de negociação em uma função de dimensionamento de ordem padrão de sinal Processamento aplica a estratégia a dados de mercado arbitrários 120 Guy Yollin (Copyright © 2011) Quantitative Trading Strategies in R quantstrat-I 37/72 Basic fluxo de trabalho de backtesting de estratégia para quantstrat mm 40 60 80 100 120 Inicialização Definir estratégia Processamento barra a barra Atualizar relatório 40 Inicializar moeda e instrumentos e carregar dados históricos Inicializar portfólio, conta, ordens, estratégia Adicionar indicadores, sinais e regras Aplicar estratégia a portfólio Atualizar carteira, conta, patrimônio Gerar relatórios de desempenho e gráficos 60 80 G uy Yollin (Copyright © 2011) Quantitative Trading Strategies no R quantstrat-I 38/72 Inicializar portfólio e conta mm R Código:> # inz portfólio, conta e ordens> qs. strategy initPortf (qs. strategy, 'SPY', initDate = '1997-12-31') [1] "qsFaber"> initAcct (qs. strategy, portfolios = qs. strategy, initDate = '1997-12-31', initEq = 1e6) [1] "qsFaber" 40 60 80 100 120 60 Código idêntico usado anteriormente 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 39/72 Inicializar ordens e estratégia mm 40 60 80 100 120 R Código:>>>>> # initialize orders container 40 biblioteca (quantstrat) initOrders (portfolio = qs. strategy, initDate = '1997-12-31') # instanciar uma nova estratégia objeto classe strat (estratégia) [1] "estratégia"> resumo (estratégia) 40 Comprimento nome 1 ativos 0 indicadores 0 sinais 600 regras 1 restrições 0 init 0 wrapup 0 chamada 2 Classe - nenhum-nenhum-nenhum-nenhum-nenhum-nenhum-nenhum-nenhumTipo de caractere lista de lista NULL lista de lista NULL chamada 40 60 80 100 120 80 Guy Yollin (Copyright © 2 011) Estratégias de Negociação Quantitativas em R quantstrat-I 41/72 Fluxo de trabalho de backtesting de estratégia básica para quantstrat mm 40 60 80 100 120 Inicialização Definir estratégia Processamento barra a barra Atualizar Relatório 40 Inicializar moeda e instrumentos e carregar dados históricos Inicializar portfólio, contabilizar , ordens, estratégia Adicionar indicadores, sinais e regras Aplicar estratégia ao portfólio Atualizar carteira, conta, patrimônio Gerar relatórios de desempenho e gráficos 60 80 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 42/72 O add. indicator Os indicadores são tipicamente análises técnicas ou estatísticas padrão. 60 60 120 produtos, como 40 médias móveis, bandas, 80 modelos de preços ou indicadores são aplicados antes de sinais e regras, e a saída de indicadores pode ser usada como insumo para construir sinais ou regras 40 Código R: A função add. indicator> args (add. indicator) (estratégia, nome, argumentos, parâmetros = NULL, label = NULL,. enabled = TRUE, indexnum = NULL, loja = FALSE) NULL 60 Argumentos principais: estratégia estratégia nome do objeto nome do indicador (deve ser uma função R) 80 argumentos argumentos a serem passados ​​para o nome do rótulo da função do indicador para referenciar o indicador Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 43/72 Adicionando um indicador a uma estratégia mm 40 60 80 100 120 adicionar uma média móvel simples de 10 meses R Código:> resumo da estratégia (strat) Nome do comprimento 1 ativos 0 indicadores 1 60 sinais 0 regras 1 restrições 0 init 0 wrapup 0 chamada 2 Classe - nenhum-nenhum-nenhum-nenhum-nenhum-nenhum-nenhum-nenhumTipo de caractere lista de lista NULL lista de lista NULL chamada 80 Guy Yollin (Copyright © 2011 Estratégias de Negociação Quantitativas em R quantstrat-I 44/72 A função add. signals quantstrat suporta os seguintes tipos de sinal: sinal de cruzamento sigCrossover (”gt”, ”lt”, ”eq”, “gte”, ”100 lte”) mm 40 60 80 sinal de comparação sigComparison ("gt", "lt", "eq", "gte" ), lte ”sinal do limiar do limiar do limiar (” gt ”,“ lt ”,“ eq ”,“ gte ”,”) lte ”sinais do pico / vale do sigPeak (“ pico ”,“ fundo ”) 40 sinal sigFormula calculado a partir de uma fórmula R Código: A função add. signals function> args (add. signal) (estratégia, nome, argumentos, parâmetros = NULL, label = NULL, 60. enabled = TRUE, indexnum = NULL, loja = FALSE) NULL 120 Argumentos principais: estratégia 80 nome do objeto de estratégia nome do sinal (um dos 5 sinais suportados) argumentos argumentos a serem passados ​​para a função do indicador Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 45/72 Adicionar sinais a uma estratégia adicionar sinal para cruzar acima do sinal SMA 40 addmm para cruzar abaixo de 60 SMA R Código:> strat strat summary (strat) Comprimento 601 nome ativos 0 indicadores 1 sinais 2 regras 1 restrições 0 800 inicialização wrap 0 chamada 2 Guy Yollin (Copyright 80 100 120 © Classe - none-none-none-none-none-none-none-none2011) Caractere de modo lista de lista de NULL lista de lista de NULL chamada Quantitative Trading Strategies in R quantstrat-I 46/72 A função add. rules A função add. rule adiciona uma regra a uma estratégia mm 40 60 80 R Código: A função add. rule> args (add. rule) function (estratégia, nome, argumentos , parameters = NULL, label = NULL, tipo = 40 c (NULL, "risco", "ordem", "rebalanceamento", "exi t "," enter "),. habilitado = TRUE, indexnum = NULL, path. dep = TRUE, timespan = NULL, store = FALSE) NULL 100 120 Argumentos principais: 60 nome da estratégia argumentos tipo 80 nome do objeto de estratégia da regra (geralmente ruleSignal) argumentos a serem passados ​​para o regra função tipo de regra (”risco”, “ordem”, “reequilíbrio”, “sair” entrar ”,”) Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas na quantia-I R 47/72 A função ruleSignal ruleSignal é a regra padrão para gerar uma ordem de negociação em um sinal Código R: A função ruleSignal> args (ruleSignal) function (dados = mktdata, timestamp, sigco, sigval, orderqty = 0, ordertype, orderside = NULL, threshold = NULL, tmult = FALSE , substituir = TRUE, atraso = 1e-04, osFUN = "osNoOp", preço = c ("mercado", 40 "oposta", "fabricante"), portfólio, símbolo,. ruletype, TxnFees = 0, prefer = NULL, sethold = FALSE) NULL mm 40 60 80 100 120 Argumentos principais: 60 dados um objeto xts contendo dados de mercado (padrão mktdata) sigcol nome da coluna para checar r valor do sinal sigval do sinal para combinar a quantidade do pedido para o pedido ou "tudo", modificado pelo osFUN ordertype80 "mercado" limite "," stoplimit "," stoptrailing "," iceberg "," encomendas "longo”, curto ”ou NULL, função osFUN ou função de dimensionamento de nome do pedido (o padrão é osNoOp) Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 48/72 Adicionar regras a uma estratégia mm 40 60 80 100 120 adicionar regra para entrar quando Cl. gt. SMA é true add rule para sair quando Cl. lt. SMA é true R Code: 40> # go long quando fechar> MA> strat # exit60 quando close strat strat (strat) Comprimento 401 nome ativos 0 indicadores 1 sinais 2 regras 3 restrições 0 600 init wrapup 0 call 2 Classe - none-none-none-none-none-none-none-noneMode character NULL list list list NULL list list call O objeto strategy contém: 1 indicador definido pelo usuário 80 2 user definished signals 2 regras de negociação definidas pelo usuário Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 50/72 Fluxo de trabalho de backtesting de estratégia básica para quantstrat mm 40 60 80 100 120 Inicialização Definir estratégia Processamento barra a barra Atualizar relatório 40 Inicializar moeda e instrumentos e carregar dados históricos Inicializar portfólio, conta, ordens, estratégia Adicionar indicadores, sinais e regras Aplicar estratégia ao portfólio Atualizar carteira, conta, patrimônio Gerar relatórios de desempenho e gráficos 60 80 Guy Yollin (Copyright © 2011) Quantitative Trading Strategies no R quantstrat-I 51/72 A função applyStrategy mm 60 80 100 120 A função applyStrategy 40 aplica o estratégia para dados de mercado arbitrários Código R: A função applyStrategy function> args (applyStrategy) (estratégia, portfolios, mktdata = NULL, parameters = NULL, 40. verbose = TRUE) NULL Principais argumentos: estratégia 60 um objeto do tipo 'estratégia' portfólios parâmetros 80 uma lista de portfólios para aplicar a estratégia à lista nomeada de parâmetros a serem aplicados durante a avaliação da estratégia Guy Yollin (Copyright © 2011) Negociação Quantitativa Estratégias no R quantstrat-I 52/72 Aplicar a estratégia mm R Código:> out nomes (out) 40 60 80 100 120 40 [1] "qsFaber"> nomes (out $ qsFaber) [1] "SPY"> nomes ( out $ qsFaber $ SPY) 60 [1] "indicadores" "sinais" "regras"> classe (out $ qsFaber $ SPY $ indicadores) [1] "xts" "zoo" 80 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação O objeto mktdata é uma variável especial construída durante a execução de mm applyStrategy. É o objeto da série temporal 40 que contém 100 dados históricos dos dados 60 80 120, bem como os indicadores, sinais e regras calculados: Código R:> cauda (mktdata [, - (1: 5)], 12) 40 2010- 08-31 2010-09-30 2010-10-29 2010-11-30 2010-12-31 2011-01-31 2011-02-28 2011-03-31 2011-04-29 2011-05-31 2011- 06-30 2011-07-29 SPY. Adjustado 103,24 112,48 116,78 116,78 124,59 127,49 131,92 131,94 135,76 134,23 131,97 129,33 60 SMA10m 107,7569 108,3360 109,1411 110,3413 111,9953 113,32989 114,9287 117,4512 120,9029 123,5213 126,3944 128,0790 SMA10 Cl. gt. SMA Cl. lt. SMA 107,7569 ND 1 108.3360 1 NA 109.1411 NA NA 110.3413 ND NA 111.9953 NA NA 113.3289 NA NA 114.9287 NA NA 117.4512 NA NA 120.9079 NA NA 123.5213 NA NA 126.3944 NA NA 128.0790 NA NA 80 Inspecionar mktdata pode ser muito útil para entender o processamento e depuração de estratégia de Guy Yollin ( Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 54/72 Fluxo de trabalho de backtesting de estratégia básica para quantstrat mm 40 60 80 100 120 Inicialização D Estratégia efine Processamento barra a barra Relatórios de atualização 40 Inicializar moeda e instrumentos, e carregar dados históricos Inicializar portfólio, conta, ordens, estratégia Adicionar indicadores, sinais e regras Aplicar estratégia ao portfólio Atualizar carteira, conta, patrimônio Gerar relatórios de desempenho e gráficos 60 80 Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas no R quantstrat-I 55/72 atualização P & L mm 40 60 80 100 120 atualiza um intervalo de datas inteiro de uma vez funções devem ser chamadas em ordem Código R: 40> updatePortf (Portfólio = qs. strategy, Datas = paste ('::', as. Date (Sys. time ()), sep = '')) [1] "qsFaber"> updateAcct (nome = qs. strategy, Datas = índice (SPY )) 60 [1] "qsFaber"> dummy chart_Posn (qs. estratégia, símbolo = 'SPY', Datas = '1998 ::')> plot (add_SMA (n = 10, col = 4, on = 1, lwd = 2)) 60 80 Guy Yollin (Copyright © 2011) Quantitativas Estratégias de Negociação em R quantstrat-I 58/72 desempenho do sistema Faber / quanstrat SPY 140 1998-01-30 / 2011−07−29 mm 40 60 80 100 120 130 120 115 140 130 120 110 110 105 100 100 90 40 95 90 85 80 80 75 70 70 1000 800 600 400 200 0 1e + 05 Posicionamento 1000 qqqqqqq 1000 800 600 400 200 60 qqqqqq 0 1e + 05 8e + 04 6e + 04 4e + 04 CumPL 81950.02164 8e + 04 6e + 04 4e + 04 2e + 04 0e + 00 1998 Jan 1998 Jul 1998 Jan 1999 1999 Jul 1999 Jan 2000 2000 Jul 2000 Jan 2001 2001 Jul 2001 Jan 2002 2002 Jul 2002 Jan 2003 2003 Jul 2003 Jan 2004 2004 Jul 2004 Jan 2005 2005 Jul 2005 Jan 2006 2006 Jul 2006 Jan 2007 2007 Jul 2007 Jan 2008 2008 Jul 2008 Jan 2009 2009 Jul 2009 Jan 2010 2010 Jul 2010 2011 Jan 2011 Jul 2011 80 2e + 04 0e + 00 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 59/72 Transações Código R: mm 40 60 80 100 120> getTxns (Portfólio = qs. strategy, Symbol = "SPY") Txn. Qty 1997-12-31 0 1999-10-29 1000 40 2000- 09-29 -1000 2002-03-28 1000 2002-04-30 -1000 2003-04-30 1000 2004-08-31 -1000 2004-09-3060 1000 2007-12-31 -1000 2009-06-30 1000 2010-06-30 -1000 2010-07-30 1000 2010-08-31 -1000 2010-09-3080 1000 Txn. Price Txn. Fees Txn. Value Tx n. Avg. Cost Net. Txn. Realized. PL 0.00000 0 0.00 0.00000 0.000 112.38352 0 112383.52 112.38352 0.000 118.98858 0 -118988.58 118.98858 6605.062 96.28988 0 96289.88 96.28988 0.000 90.69007 0 -90690.07 90.69007 -5599.813 78.59565 0 78595.65 78.59565 0,000 96.86532 0 -96865.32 96.86532 18269.669 97,83755 0 97837,55 97,83755 0,000 136,15069 0 -136150,69 136,15069 38313,139 88,81119 0 88811,19 88,81119 0,000 101,18979 0 -101189,79 101,18979 12378,598 108,10113 0 108101,13 108,10113 0,000 103,23868 0 -103238,68 103,23868 -4862,443 112,48419 0 112484,19 112,48419 0,000 Guy Yollin (Copyright: © 2011) Estratégias de Negociação quantitativos em R quantstrat-I 60/72 Contorno mm 40 60 80 100 120 1 O pacote de absorção 40 2 O pacote quantstrat 60 3 Análise de desempenho 80 Guy Yollin (Copyright © 2011) Quantitativas Estratégias de Negociação em R quantstrat-I 61/72 O portfólio de blotter objeto R Código: mm 40 60 80 100 120> thePortfolio = getPortfolio (b. strategy)> nomes (thePortfolio) [1] "símbolos" "resumo"> nd mes (os $ símbolos do Portfólio) 40 [1] "SPY"> nomes (o Portfólio $ símbolos $ SPY) [1] "txn" "posPL" "posPL. USD" 60> nomes (o Portfólio $ resumo) [1] "Longo. Valor "[5]" Realizado. PL "[9]" Net. Trading. PL ​​"" Short. Value "" Não realizado. PL "" Valor líquido "" Valor bruto "" Gross. Trading. PL ​​"" Txn. Taxas "> biblioteca (treliça) 80> enredo (xyplot (thePortfolio $ summary, xlab =" ", tipo =" h ", col = 4)) Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 62 / 72 Gráfico do resumo da carteira série temporal objeto 2000 −0,4 0,0 0,4 100000 2005 2010 mm Long. Value 40 60 80 Short. Value 100 120 0 Net. Value 100000 Gross. Value 40 Realizado. PL 0 0 100000 Unrealized. PL 0 0 20000 - 10000 0 10000 −10000 0 10000 Gross. Trading. PL ​​−0,4 0,0 0,4−40000 Txn. Fees 60 Net. Trading. PL ​​80 2000 2005 2010 Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 63/72 Blotter account object Código R: mm 40 60 80 100 120> theAccount = getAccount (b. strategy)> nomes (theAccount) [1] "portfólios" "sumar y "> nomes (os portfólios da Conta $) 40 [1]" bFaber "> nomes (a conta $ portfólios $ bFaber) [1]" Long. Value "[5]" Realizado. PL "60 [9]" Net. Trading. PL "" Short. Value "" Unrealized. PL "" Net. Value "" Valor bruto "" Gross. Trading. PL ​​"" Txn. Fees "> nomes (theAccount $ summary) [1]" Adições "[5] "Int. Income" [9] "Advisory. Fees" 80 "Retiradas" "Realizado. PL" "Gross. Trading. PL" "Txn. Fees" "Net. Performance" "End. Eq" "Unrealized. PL" " Net. Trading. PL ​​"Guy Yollin (Copyright © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 64/72 Estatísticas de Comércio mm R Código:> (biblioteca tstats (PerformanceAnalytics)> rets tail (rets, 12) SPY 2010-08- 3140 -4.862443e-03 2010-09-30 0.000000e + 00 2010-10-29 4.297123e-03 2010-11-30 0.000000e + 00 2010-12-31 7.807092e-03 2011-01-31 2.902940- 03 2011-02-28604.428709e-03 2011-03-31 1.584192e-05 2011-04-29 3.821053e-03 2011-05-31 -1.522454e-03 2011-06-30 -2.264505e-03 2011-07 -29 -2.640000e-03> charts. PerformanceSummary (rets, colorset = bluefocus) 80 100 120 80 Guy Yollin (Copyrig © 2011) Estratégias de Negociação Quantitativas em R quantstrat-I 67/72 Retorno cumulativo e rebaixamento Desempenho SPY 0,10 mm 40 60 80 100 120 Retorno acumulado 0,04 0,06 0,08 40 Retorno mensal 0,000 0,00 0 0,010 0,00 0,02 60 0,000 −0,010 Abaixamento −0,010 −0,020 80 Dez 97 Jul 98 Jul 99 Jul 00 Jul 01 Jul 02 Jul 03 Jul 04 Jul 05 Jul 06 Jul 07 Jul 08 Jul 09 Jul 10 Jul 11 ​​Data Guy Yollin (Copyright © 2011) Estratégias Quantitativas de Negociação em R quantstrat-I 68/72 Calcule as estatísticas de retorno mm 40 60 80 100 120 R Código:> PA1.tab PA2.tab tab1 res. tab1 res. tab2 res. tab3 tab2.


Estratégias Quantitativas de Negociação na RPart 1 de 3.


Estratégias Quantitativas de Negociação na Parte R 3 de 3.


Estratégias Quantitativas de Negociação na RPart 3 de 3.


Estratégias Quantitativas de Negociação na R Parte 2 de 3.


Estratégias Quantitativas de Negociação na RPart 2 de 3.


© 2012 Locke em seu sucesso, LLC. Parte 1 de 3, 2/4/12 de John Tradinge Locke em seu sucesso, LLC. Saiba o que você quer, faça isso.


document. write (adsense. get_banner_code (& # 039; 200x90 & # 039;)); Slide 1 © 2012 Locke em seu sucesso, LLC. Butterfly Trading Strategies part 1 of 3, 2/4/12 John Locke Locke…


© 2012 Locke in Your Success, LLC. Butterfly Trading Strategies part 2 of 3, 2/4/12 John Locke Locke in Your Success, LLC. Know what you want, make it.


document. write (adsense. get_banner_code (& # 039; 200x90 & # 039;)); Slide 1 © 2012 Locke in Your Success, LLC. Butterfly Trading Strategies part 2 of 3, 2/4/12 John Locke Locke…


2008 in Pictures - Part 1 of 3.


Encyclopedia of Trading Strategies.


Encyclopedia of Trading Strategies.


Mixed strategies in baseball Part 1.


The Application of Trend Following Strategies in Stock Market Trading.


The Application of Trend Following Strategies in Stock Market Trading Simon Fong, Jackie Tai Department of Computer and Information Science University of Macau, Macao SAR…


Marketing Growth Strategies for Accounting Firms - Marketing Machine Webinar - Part 1 of 3.


Slides from 9 June 2010 webinar, "10 Steps to Building a Marketing Machine for Growing Your Accounting Firm" by Practice Paradox.


© 2009 IBM Corporation 1 Eric Hess, IBM 2008 IBM Power Systems - IBM i High Availability Strategies & Planning for 2012 Part 3 of 3 - Part 3 of 3 - HA.


Slide 1 © 2009 IBM Corporation 1 Eric Hess, IBM 2008 IBM Power Systems - IBM i High Availability Strategies & Planning for 2012 Part 3 of 3 - Part 3 of 3 - HA and DR…


Advanced Trading Strategies in Options.


Overview Advanced Trading Strategies in Options Option or choice is a derivative financial instrument whose market is growing fast. It is a contract between a buyer and a…


The Encyclopedia of Trading Strategies.


THE ENCYCLOPEDIA OF TRADING STRATEGIES JEFFREY OWEN KATZ, Ph. D. DONNA 1. M C CORMICK T R A D E M A R K S A N D S E R V I C E M A R K S Company and product names associated…


Implementing Strategies ( Part 1 )


3 Easy Forex Trading Strategies for Beginners.


Novo no Forex? Click the link to learn more about the truths of the Foreign Exchange Market!


Advances in Quantitative Analysis of Finance and Accounting Vol. 1


5405.tp 1/7/04 3:03 PM Page 1 ADVANCES IN QUANTITATIVE ANALYSIS OF FINANCE AND ACCOUNTING New Series July 13, 2005 13:47 WSPC/B272 fm. tex Advances in Quantitative Analysis…


Quantitative Finance Graduate Level Part 1.


Teaching Materials Useful for Quantitative Risk Management.


Forex Multiplier - The 3 In 1 Trading Software.


The Only Software Suitable For Conservative, Moderate And Aggressive Traders. It Gives Exact Entry Points, Targets And Stop Losses. Professional Copywrite With Video Ad.…


Algorithmic & quantitative trading webinar.


This webinar gives a brief introduction to Algorithmic Trading followed by the changing skill sets that are required in the new age trading business by mapping the required…


Palm Tree of Devorah Part 3 - R. Moses Cordovero.


Palm Tree of Devorah Part 3 - R. Moses Cordovero.


Prof. David R. Jackson Dept. of ECE Notes 6 ECE 5317-6351 Microwave Engineering Fall 2011 Waveguides Part 3: Attenuation 1.


Slide 1 Prof. David R. Jackson Dept. of ECE Notes 6 ECE 5317-6351 Microwave Engineering Fall 2011 Waveguides Part 3: Attenuation 1 Slide 2 For most practical waveguides and…


Gekko Quant - Negociação Quantitativa.


Negociação Quantitativa, Arbitragem Estatística, Aprendizado de Máquina e Opções Binárias.


Pós-navegação.


Hidden Markov Models – Examples In R – Part 3 of 4.


This post will explore how to train hidden markov models in R. The previous posts in this series detailed the maths that power the HMM, fortunately all of this has been implemented for us in the RHmm package. HMMs can be used in two ways for regime detection, the first is to use a single HMM where each state in the HMM is considered a “regime”. The second method is to have multiple HMMs each designed to model an individual regime, the task is then to chose between models by looking at which is the most likely to have generated the data. I will explore both methods.


Method One – Single HMM Each State is a Regime.


The credit for this section must go to the fantastic Systematic Investor blog systematicinvestor. wordpress/2012/11/01/regime-detection/. The code is well commented and should be self explanatory. Essentially two markets regimes (bull and bear) are simulated, a 2 state HMM is then trained on the data. The forward backward algorithm is then used to calculate the probability of being in a given state at any given time.


Method Two – Multiple HMMs with multiple states – Each HMM a regime.


Three market regimes are simulated; bull, bear and a sideways market. Three different 2 stage HMM models are trained on each regime. Model 1 is the HMM for the bull market, Model 2 is the HMM for the bear market, and Model 3 is the HMM for a side ways market. A rolling window of 50 days worth of data is passed into each HMM and a log likelihood score produced. The higher the log likelihood the more likely it is that the model generated the observed data.


As can be seen in the above chart, the log likelihood is fairly decent for determining the difference between the bull and bear markets. Sadly the side ways model seems very likely in both the bull and bear cases, it’s log likelihood is fairly stable and doesn’t change per regime.


Successful Backtesting of Algorithmic Trading Strategies, Part 1.


This article continues the series on quantitative trading, which started with the Beginner’s Guide and Strategy Identification. Both of these longer, more involved articles have been very popular so I’ll continue in this vein and provide detail on the topic of strategy backtesting . O backtesting algorítmico requer conhecimento de muitas áreas, incluindo psicologia, matemática, estatística, desenvolvimento de software e microestrutura de mercado / troca. I couldn’t hope to cover all of those topics in one article, so I’m going to split them into two or three smaller pieces. O que vamos discutir nesta seção? I’ll begin by defining backtesting and then I will describe the basics of how it is carried out. Then I will elucidate upon the biases we touched upon in the Beginner’s Guide to Quantitative Trading. A seguir, apresentarei uma comparação das várias opções de software de backtesting disponíveis. Nos artigos subseqüentes, veremos os detalhes das implementações de estratégia que são mal mencionadas ou ignoradas. Também vamos considerar como tornar o processo de backtesting mais realista, incluindo as idiossincrasias de uma bolsa de valores. Em seguida, discutiremos os custos de transação e como modelá-los corretamente em uma configuração de backtest. Terminaremos com uma discussão sobre o desempenho de nossos backtests e, finalmente, forneceremos um exemplo de uma estratégia comum de quant, conhecida como um comércio de pares que reverte a média. Let’s begin by discussing what backtesting is and why we should carry it out in our algorithmic trading.


O que é o backtesting?


A negociação algorítmica se diferencia de outros tipos de classes de investimento, porque podemos fornecer expectativas mais confiáveis ​​sobre o desempenho futuro do desempenho passado, como consequência da disponibilidade abundante de dados. O processo pelo qual isso é realizado é conhecido como backtesting. Em termos simples, o backtesting é realizado expondo seu algoritmo de estratégia particular a um fluxo de dados financeiros históricos, o que leva a um conjunto de sinais de negociação. Cada negociação (que vamos querer dizer aqui como uma ida e volta de dois sinais) terá um lucro ou prejuízo associado. The accumulation of this profit/loss over the duration of your strategy backtest will lead to the total profit and loss (also known as the ‘P&L’ or ‘PnL’). That is the essence of the idea, although of course the “devil is always in the details”! Quais são as principais razões para fazer backtesting de uma estratégia algorítmica?


Filtration – If you recall from the article on Strategy Identification, our goal at the initial research stage was to set up a strategy pipeline and then filter out any strategy that did not meet certain criteria. O backtesting nos fornece outro mecanismo de filtragem, pois podemos eliminar estratégias que não atendem às nossas necessidades de desempenho. Modelling – Backtesting allows us to (safely!) test new models of certain market phenomena, such as transaction costs, order routing, latency, liquidity or other market microstructure issues. Optimisation – Although strategy optimisation is fraught with biases, backtesting allows us to increase the performance of a strategy by modifying the quantity or values of the parameters associated with that strategy and recalculating its performance. Verification – Our strategies are often sourced externally, via our strategy pipeline . O backtesting de uma estratégia garante que ela não tenha sido implementada incorretamente. Embora raramente tenhamos acesso aos sinais gerados por estratégias externas, muitas vezes teremos acesso às métricas de desempenho, como as características de Sharpe Ratio e Drawdown. Assim, podemos compará-los com nossa própria implementação.


Backtesting fornece uma série de vantagens para negociação algorítmica. No entanto, nem sempre é possível fazer backtest diretamente de uma estratégia. Em geral, à medida que a frequência da estratégia aumenta, torna-se mais difícil modelar corretamente os efeitos de microestrutura do mercado e das trocas. Isso leva a backtests menos confiáveis ​​e, portanto, uma avaliação mais complicada de uma estratégia escolhida. Este é um problema particular em que o sistema de execução é a chave para o desempenho da estratégia, como acontece com os algoritmos de freqüência ultra-alta. Infelizmente, o backtesting é repleto de preconceitos de todos os tipos. Nós abordamos algumas dessas questões em artigos anteriores, mas vamos agora discuti-las em profundidade.


Vieses que afetam os backtests de estratégia.


Existem muitos vieses que podem afetar o desempenho de uma estratégia de backtested. Infelizmente, esses vieses tendem a inflar o desempenho em vez de prejudicá-lo. Assim, você deve sempre considerar um backtest como um limite superior idealizado no desempenho real da estratégia. É quase impossível eliminar os vieses do comércio algorítmico, por isso é nosso trabalho minimizá-los da melhor maneira possível, a fim de tomar decisões informadas sobre nossas estratégias algorítmicas. There are four major biases that I wish to discuss: Optimisation Bias, Look-Ahead Bias, Survivorship Bias and Psychological Tolerance Bias .


Viés de otimização.


Este é provavelmente o mais insidioso de todos os preconceitos de backtest. Isso envolve o ajuste ou a introdução de parâmetros de negociação adicionais até que o desempenho da estratégia no conjunto de dados de backtest seja muito atraente. No entanto, uma vez que viver, o desempenho da estratégia pode ser muito diferente. Another name for this bias is “curve fitting” or “data-snooping bias”. O viés de otimização é difícil de eliminar, pois as estratégias algorítmicas geralmente envolvem muitos parâmetros. “Parameters” in this instance might be the entry/exit criteria, look-back periods, averaging periods (i. e the moving average smoothing parameter) or volatility measurement frequency. O viés de otimização pode ser minimizado mantendo o número de parâmetros no mínimo e aumentando a quantidade de pontos de dados no conjunto de treinamento. De fato, também é preciso ter cuidado com este último, pois os pontos de treinamento mais antigos podem estar sujeitos a um regime anterior (como um ambiente regulatório) e, portanto, podem não ser relevantes para sua estratégia atual. Um método para ajudar a atenuar esse viés é realizar uma análise de sensibilidade. This means varying the parameters incrementally and plotting a “surface” of performance. O raciocínio sólido e fundamental para as escolhas de parâmetros deve, com todos os outros fatores considerados, levar a uma superfície de parâmetro mais suave. Se você tem uma superfície de desempenho muito agitada, isso geralmente significa que um parâmetro não está refletindo um fenômeno e é um artefato dos dados de teste. Existe uma vasta literatura sobre algoritmos de otimização multidimensional e é uma área altamente ativa de pesquisa. I won’t dwell on it here, but keep it in the back of your mind when you find a strategy with a fantastic backtest!


Tendência de Look-Ahead.


O viés de antecipação é introduzido em um sistema de backtesting quando dados futuros são acidentalmente incluídos em um ponto da simulação onde esses dados não estariam disponíveis. If we are running the backtest chronologically and we reach time point N , then look-ahead bias occurs if data is included for any point N + k , where k > 0 Erros de polarização antecipada podem ser incrivelmente sutis. Aqui estão três exemplos de como o viés de look-ahead pode ser introduzido:


Technical Bugs – Arrays/vectors in code often have iterators or index variables. Incorrect offsets of these indices can lead to a look-ahead bias by incorporating data at N + k for non-zero k . Parameter Calculation – Another common example of look-ahead bias occurs when calculating optimal strategy parameters, such as with linear regressions between two time series. Se todo o conjunto de dados (incluindo dados futuros) for usado para calcular os coeficientes de regressão e, portanto, aplicado retroativamente a uma estratégia de negociação para fins de otimização, os dados futuros serão incorporados e haverá um viés de antecipação. Maxima/Minima – Certain trading strategies make use of extreme values in any time period, such as incorporating the high or low prices in OHLC data. No entanto, como esses valores máximos / mínimos só podem ser calculados no final de um período de tempo, um viés de antecipação é introduzido se esses valores forem usados ​​durante o período atual. É sempre necessário atrasar valores altos / baixos em pelo menos um período em qualquer estratégia de negociação fazendo uso deles.


Viés de sobrevivência.


O viés de sobrevivência é um fenômeno particularmente perigoso e pode levar a um desempenho significativamente inflacionado para certos tipos de estratégia. It occurs when strategies are tested on datasets that do not include the full universe of prior assets that may have been chosen at a particular point in time, but only consider those that have “survived” to the current time. Como exemplo, considere testar uma estratégia em uma seleção aleatória de ações antes e depois do crash do mercado de 2001. Algumas ações da tecnologia faliram, enquanto outras conseguiram se manter à tona e até prosperaram. Se tivéssemos restringido essa estratégia apenas às ações que passaram pelo período de rebaixamento do mercado, estaríamos introduzindo um viés de sobrevivência, porque eles já demonstraram seu sucesso para nós. Na verdade, este é apenas mais um caso específico de viés de antecipação, já que informações futuras estão sendo incorporadas à análise passada. Existem duas maneiras principais de atenuar o viés de sobrevivência em seus backtests de estratégia:


Survivorship Bias Free Datasets – In the case of equity data it is possible to purchase datasets that include delisted entities, although they are not cheap and only tend to be utilised by institutional firms. Em particular, os dados do Yahoo Finance NÃO são livres de viés de sobrevivência, e isso é comumente usado por muitos traders de algoritmos de varejo. Também é possível negociar em classes de ativos que não são propensas ao viés de sobrevivência, como certas commodities (e seus futuros derivativos). Use More Recent Data – In the case of equities, utilising a more recent data set mitigates the possibility that the stock selection chosen is weighted to “survivors”, simply as there is less likelihood of overall stock delisting in shorter time periods. Também é possível começar a criar um conjunto de dados pessoal livre de viés de sobrevivência, coletando dados do ponto atual em diante. Depois de 3 a 4 anos, você terá um sólido conjunto de dados de equidade livres de viés de sobrevivência, com o qual será feito backtest de estratégias adicionais. Consideraremos agora certos fenômenos psicológicos que podem influenciar seu desempenho comercial.


Consideraremos agora certos fenômenos psicológicos que podem influenciar seu desempenho comercial.


Tendência da Tolerância Psicológica.


Este fenómeno em particular não é frequentemente discutido no contexto do comércio quantitativo. No entanto, é discutido extensivamente em relação a métodos de negociação mais discricionários. It has various names, but I’ve decided to call it “psychological tolerance bias” because it captures the essence of the problem. Ao criar backtests durante um período de 5 anos ou mais, é fácil olhar para uma curva de capital de tendência ascendente, calcular o retorno anual composto, o índice de Sharpe e até as características de rebaixamento e ficar satisfeito com os resultados. Como exemplo, a estratégia pode possuir um rebaixamento relativo máximo de 25% e uma duração máxima de rebaixamento de 4 meses. Isso não seria atípico para uma estratégia momentânea. É fácil convencer-se de que é fácil tolerar esses períodos de perdas porque o quadro geral é otimista. No entanto, na prática, é muito mais difícil! Se rebotes históricos de 25% ou mais ocorrerem nos backtests, então, com toda a probabilidade, você verá períodos de rebaixamento similar em negociações ao vivo. Estes períodos de abandono são psicologicamente difíceis de suportar. I have observed first hand what an extended drawdown can be like, in an institutional setting, and it is not pleasant – even if the backtests suggest such periods will occur. The reason I have termed it a “bias” is that often a strategy which would otherwise be successful is stopped from trading during times of extended drawdown and thus will lead to significant underperformance compared to a backtest. Assim, embora a estratégia seja de natureza algorítmica, os fatores psicológicos ainda podem ter uma forte influência na lucratividade. O objetivo é assegurar que, se você vir perdas de uma certa porcentagem e duração nos backtests, então você deve esperar que elas ocorram em ambientes de negociação ao vivo e que precisem perseverar para alcançar a lucratividade mais uma vez.


Pacotes de software para backtesting.


O cenário de software para backtesting de estratégia é vasto. Solutions range from fully-integrated institutional grade sophisticated software through to programming languages such as C++, Python and R where nearly everything must be written from scratch (or suitable ‘plugins’ obtained). As quant traders we are interested in the balance of being able to “own” our trading technology stack versus the speed and reliability of our development methodology. Aqui estão as principais considerações para a escolha de software:


Programming Skill – The choice of environment will in a large part come down to your ability to program software. I would argue that being in control of the total stack will have a greater effect on your long term P&L than outsourcing as much as possible to vendor software. This is due to the downside risk of having external bugs or idiosyncrasies that you are unable to fix in vendor software, which would otherwise be easily remedied if you had more control over your “tech stack”. Você também quer um ambiente que encontre o equilíbrio certo entre produtividade, disponibilidade de biblioteca e velocidade de execução. Eu faço minha própria recomendação pessoal abaixo. Execution Capability/Broker Interaction – Certain backtesting software, such as Tradestation, ties in directly with a brokerage. Eu não sou fã dessa abordagem, já que reduzir os custos de transação é muitas vezes um grande componente para obter um índice maior de Sharpe. If you’re tied into a particular broker (and Tradestation “forces” you to do this), then you will have a harder time transitioning to new software (or a new broker) if the need arises. Os Interactive Brokers fornecem uma API robusta, embora com uma interface ligeiramente obtusa. Customisation – An environment like MATLAB or Python gives you a great deal of flexibility when creating algo strategies as they provide fantastic libraries for nearly any mathematical operation imaginable, but also allow extensive customisation where necessary. Strategy Complexity – Certain software just isn’t cut out for heavy number crunching or mathematical complexity. O Excel é um desses softwares. Embora seja bom para estratégias mais simples, ele não pode realmente lidar com numerosos ativos ou algoritmos mais complicados, em velocidade. Bias Minimisation – Does a particular piece of software or data lend itself more to trading biases? You need to make sure that if you want to create all the functionality yourself, that you don’t introduce bugs which can lead to biases. Speed of Development – One shouldn’t have to spend months and months implementing a backtest engine. A prototipagem deve levar apenas algumas semanas. Certifique-se de que seu software não está atrapalhando o seu progresso em grande medida, apenas para pegar alguns pontos percentuais extras de velocidade de execução. C++ is the “elephant in the room” here! Speed of Execution – If your strategy is completely dependent upon execution timeliness (as in HFT/UHFT) then a language such as C or C++ will be necessary. No entanto, você estará se aproximando da otimização do kernel do Linux e do uso do FPGA para esses domínios, o que está fora do escopo deste artigo! Custo & # 8211; Many of the software environments that you can program algorithmic trading strategies with are completely free and open source. Na verdade, muitos fundos de hedge fazem uso de software de código aberto para todas as suas pilhas de negociação de algoritmos. Além disso, o Excel e o MATLAB são relativamente baratos e existem alternativas gratuitas para cada um deles.


Now that we have listed the criteria with which we need to choose our software infrastructure, I want to run through some of the more popular packages and how they compare: Note: I am only going to include software that is available to most retail practitioners and software developers, as this is the readership of the site. Enquanto outros softwares estão disponíveis, tais como as ferramentas mais institucionais, eu sinto que são muito caras para serem efetivamente usadas em um ambiente de varejo e eu pessoalmente não tenho nenhuma experiência com elas.


Description : WYSIWYG (what-you-see-is-what-you-get) spreadsheet software. Extremely widespread in the financial industry. Data and algorithm are tightly coupled. Execution : Yes, Excel can be tied into most brokerages. Customisation : VBA macros allow more advanced functionality at the expense of hiding implementation. Strategy Complexity : More advanced statistical tools are harder to implement as are strategies with many hundreds of assets. Bias Minimisation : Look-ahead bias is easy to detect via cell-highlighting functionality (assuming no VBA). Development Speed : Quick to implement basic strategies. Execution Speed : Slow execution speed – suitable only for lower-frequency strategies. Cost : Cheap or free (depending upon license). Alternatives : OpenOffice.


Description : Programming environment originally designed for computational mathematics, physics and engineering. Very well suited to vectorised operations and those involving numerical linear algebra. Provides a wide array of plugins for quant trading. In widespread use in quantitative hedge funds. Execution : No native execution capability, MATLAB requires a separate execution system. Customisation : Huge array of community plugins for nearly all areas of computational mathematics. Strategy Complexity : Many advanced statistical methods already available and well-tested. Bias Minimisation : Harder to detect look-ahead bias, requires extensive testing. Development Speed : Short scripts can create sophisticated backtests easily. Execution Speed : Assuming a vectorised/parallelised algorithm, MATLAB is highly optimised. Poor for traditional iterated loops. Cost :


Description : High-level language designed for speed of development. Wide array of libraries for nearly any programmatic task imaginable. Gaining wider acceptance in hedge fund and investment bank community. Not quite as fast as C/C++ for execution speed. Execution : Python plugins exist for larger brokers, such as Interactive Brokers. Hence backtest and execution system can all be part of the same “tech stack”. Customisation : Python has a very healthy development community and is a mature language. NumPy/SciPy provide fast scientific computing and statistical analysis tools relevant for quant trading. Strategy Complexity: Many plugins exist for the main algorithms, but not quite as big a quant community as exists for MATLAB. Bias Minimisation : Same bias minimisation problems exist as for any high level language. Need to be extremely careful about testing. Development Speed : Pythons main advantage is development speed, with robust in built in testing capabilities. Execution Speed : Not quite as fast as C++, but scientific computing components are optimised and Python can talk to native C code with certain plugins. Cost : Free/Open Source Alternatives : Ruby, Erlang, Haskell.


Description : Environment designed for advanced statistical methods and time series analysis. Wide array of specific statistical, econometric and native graphing toolsets. Large developer community. Execution : R possesses plugins to some brokers, in particular Interactive Brokers. Thus an end-to-end system can written entirely in R. Customisation : R can be customised with any package, but its strengths lie in statistical/econometric domains. Strategy Complexity : Mostly useful if performing econometric, statistical or machine-learning strategies due to available plugins. Bias Minimisation : Similar level of bias possibility for any high-level language such as Python or C++. Thus testing must be carried out. Development Speed : R is rapid for writing strategies based on statistical methods. Execution Speed : R is slower than C++, but remains relatively optimised for vectorised operations (as with MATLAB). Cost : Free/Open Source Alternatives : SPSS, Stata.


Description : Mature, high-level language designed for speed of execution. Wide array of quantitative finance and numerical libraries. Harder to debug and often takes longer to implement than Python or MATLAB. Extremely prevalent in both the buy - and sell-side. Execution : Most brokerage APIs are written in C++ and Java. Thus many plugins exist. Customisation : C/C++ allows direct access to underlying memory, hence ultra-high frequency strategies can be implemented. Strategy Complexity : C++ STL provides wide array of optimised algorithms. Nearly any specialised mathematical algorithm possesses a free, open-source C/C++ implementation on the web. Bias Minimisation : Look-ahead bias can be tricky to eliminate, but no harder than other high-level language. Good debugging tools, but one must be careful when dealing with underlying memory. Development Speed : C++ is quite verbose compared to Python or MATLAB for the same algorithmm. More lines-of-code (LOC) often leads to greater likelihood of bugs. Execution Speed : C/C++ has extremely fast execution speed and can be well optimised for specific computational architectures. This is the main reason to utilise it. Cost : Various compilers: Linux/GCC is free, MS Visual Studio has differing licenses. Alternatives : C#, Java, Scala Different strategies will require different software packages. HFT and UHFT strategies will be written in C/C++ (these days they are often carried out on GPUs and FPGAs), whereas low-frequency directional equity strategies are easy to implement in TradeStation, due to the “all in one” nature of the software/brokerage. My personal preference is for Python as it provides the right degree of customisation, speed of development, testing capability and execution speed for my needs and strategies. If I need anything faster, I can “drop in” to C++ directly from my Python programs. One method favoured by many quant traders is to prototype their strategies in Python and then convert the slower execution sections to C++ in an iterative manner. Eventually the entire algo is written in C++ and can be “left alone to trade”! In the next few articles on backtesting we will take a look at some particular issues surrounding the implementation of an algorithmic trading backtesting system, as well as how to incorporate the effects of trading exchanges. We will discuss strategy performance measurement and finally conclude with an example strategy.


About the Author Mike Halls-Moore.


Michael graduated with a MMath in Mathematics from the University of Warwick, gained a PhD from Imperial College London in Fluid Dynamics, and was working in a hedge fund as a quantitative trading developer for the last few years in Mayfair, London. He now spends time on research, development, backtesting and implementation of intraday algorithmic trading strategies.


O Trader R.


Usando R e ferramentas relacionadas em Finanças Quantitativas.


Archive for the ‘Trading Strategies’ Categoria.


Linking R to IQFeed with the QuantTools package.


IQFeed provides streaming data services and trading solutions that cover the Agricultural, Energy and Financial marketplace. It is a well known and recognized data feed provider geared toward retail users and small institutions. The subscription price starts at around $80/month.


Stanislav Kovalevsky has developed a package called QuantTools. It is an all in one package designed to enhance quantitative trading modelling. It allows to download and organize historical market data from multiple sources like Yahoo, Google, Finam, MOEX and IQFeed. The feature that interests me the most is the ability to link IQFeed to R. I’ve been using IQFeed for a few years and I’m happy with it (I’m not affiliated to the company in any way). More information can be found here. I’ve been looking for an integration within R for a while and here it is. As a result, after I ran a few tests, I moved my code that was still in Python into R. Just for completeness, here’s a link that explains how to download historical data from IQFeed using Python.


QuantTools offers four main functionalities: Get market data, Store/Retrieve market data, Plot time series data and Back testing.


First make sure that IQfeed is open. You can either download daily or intraday data. The below code downloads daily prices (Open, High, Low, Close) for SPY from 1st Jan 2017 to 1st June 2017.


The below code downloads intraday data from 1st May 2017 to 3rd May 2017.


Note the period parameter. It can take any of the following values: tick, 1min, 5min, 10min, 15min, 30min, hour, day, week, month, depending on the frequency you need.


QuantTools makes the process of managing and storing tick market data easy. You just setup storage parameters and you are ready to go. The parameters are where, since what date and which symbols you would like to be stored. Any time you can add more symbols and if they are not present in a storage, QuantTools tries to get the data from specified start date. The code below will save the data in the following directory: “C:/Users/Arnaud/Documents/Market Data/iqfeed”. There is one sub folder by instrument and the data is aved in. rds files.


You can also store data between specific dates. Replace the last line of code above with one of the below.


Now should you want to get back some of the data you stored, just run something like:


Note that only ticks are supported in local storage so period must be ‘tick’


QuantTools provides plot_ts function to plot time series data without weekend, holidays and overnight gaps. In the example below, I first retrieve the data stored above, then select the first 100 price observations and finally draw the chart.


Two things to notice: First spy is a data. table object hence the syntax above. To get a quick overview of data. table capabilities have a look at this excellent cheat sheet from DataCamp. Second the local parameter is TRUE as the data is retrieved from internal storage.


QuantTools allows to write your own trading strategy using its C++ API. I’m not going to elaborate on this as this is basically C++ code. You can refer to the Examples section on QuantTools website.


Overall I find the package extremely useful and well documented. The only missing bit is the live feed between R and IQFeed which will make the package a real end to end solution.


As usual any comments welcome.


BERT: a newcomer in the R Excel connection.


A few months ago a reader point me out this new way of connecting R and Excel. I don’t know for how long this has been around, but I never came across it and I’ve never seen any blog post or article about it. So I decided to write a post as the tool is really worth it and before anyone asks, I’m not related to the company in any way.


BERT stands for Basic Excel R Toolkit. It’s free (licensed under the GPL v2) and it has been developed by Structured Data LLC. At the time of writing the current version of BERT is 1.07. More information can be found here. From a more technical perspective, BERT is designed to support running R functions from Excel spreadsheet cells. In Excel terms, it’s for writing User-Defined Functions (UDFs) in R.


In this post I’m not going to show you how R and Excel interact via BERT. There are very good tutorials here, here and here. Instead I want to show you how I used BERT to build a “control tower” for my trading.


My trading signals are generated using a long list of R files but I need the flexibility of Excel to display results quickly and efficiently. As shown above BERT can do this for me but I also want to tailor the application to my needs. By combining the power of XML, VBA, R and BERT I can create a good looking yet powerful application in the form of an Excel file with minimum VBA code. Ultimately I have a single Excel file gathering all the necessary tasks to manage my portfolio: database update, signal generation, orders submission etc… My approach could be broken down in the 3 steps below:


Use XML to build user defined menus and buttons in an Excel file. The above menus and buttons are essentially calls to VBA functions. Those VBA functions are wrapup around R functions defined using BERT.


With this approach I can keep a clear distinction between the core of my code kept in R, SQL and Python and everything used to display and format results kept in Excel, VBA & XML. In the next sections I present the prerequisite to developed such an approach and a step by step guide that explains how BERT could be used for simply passing data from R to Excel with minimal VBA code.


1 & # 8211; Download and install BERT from this link . Once the installation has completed you should have a new Add-Ins menu in Excel with the buttons as shown below. This is how BERT materialized in Excel.


2 & # 8211; Download and install Custom UI editor : The Custom UI Editor allows to create user defined menus and buttons in Excel ribbon. A step by step procedure is available here.


1 & # 8211; R Code: The below R function is a very simple piece of code for illustration purposes only. It calculates and return the residuals from a linear regression. This is what we want to retrieve in Excel. Save this in a file called myRCode. R (any other name is fine) in a directory of your choice.


2 & # 8211; functions. R in BERT : From Excel select Add-Ins -> Home Directory and open the file called functions. R . In this file paste the following code. Make sure you insert the correct path.


This is just sourcing into BERT the R file you created above. Then save and close the file functions. R. Should you want to make any change to the R file created in step 1 you will have to reload it using the BERT button “Reload Startup File” from the Add-Ins menu in Excel.


3 & # 8211; In Excel: Create and save a file called myFile. xslm (any other name is fine). This is a macro-enabled file that you save in the directory of your choice. Once the file is saved close it.


4 & # 8211; Open the file created above in Custom UI editor : Once the file is open, paste the below code.


You should have something like this in the XML editor:


Essentially this piece of XML code creates an additional menu (RTrader), a new group (My Group) and a user defined button (New Button) in the Excel ribbon. Once you’re done, open myFile. xslm in Excel and close the Custom UI Editor. You should see something like this.


5 & ​​# 8211; Open VBA editor : In myFile. xlsm insert a new module. Paste the code below in the newly created module.


This erases previous results in the worksheet prior to coping new ones.


6 & # 8211; Click New Button : Now go back to the spreadsheet and in the RTrader menu click the “New Button” botão. You should see something like the below appearing.


The guide above is a very basic version of what can be achieved using BERT but it shows you how to combine the power of several specific tools to build your own custom application. From my perspective the interest of such an approach is the ability to glue together R and Excel obviously but also to include via XML (and batch) pieces of code from Python, SQL and more. This is exactly what I needed. Finally I would be curious to know if anyone has any experience with BERT?


Trading strategy: Making the most of the out of sample data.


When testing trading strategies a common approach is to divide the initial data set into in sample data: the part of the data designed to calibrate the model and out of sample data: the part of the data used to validate the calibration and ensure that the performance created in sample will be reflected in the real world. As a rule of thumb around 70% of the initial data can be used for calibration (i. e. in sample) and 30% for validation (i. e. out of sample). Then a comparison of the in and out of sample data help to decide whether the model is robust enough. This post aims at going a step further and provides a statistical method to decide whether the out of sample data is in line with what was created in sample.


In the chart below the blue area represents the out of sample performance for one of my strategies.


A simple visual inspection reveals a good fit between the in and out of sample performance but what degree of confidence do I have in this? At this stage not much and this is the issue. What is truly needed is a measure of similarity between the in and out of sample data sets. In statistical terms this could be translated as the likelihood that the in and out of sample performance figures coming from the same distribution. There is a non-parametric statistical test that does exactly this: the Kruskall-Wallis Test . A good definition of this test could be found on R-Tutor “A collection of data samples are independent if they come from unrelated populations and the samples do not affect each other. Using the Kruskal-Wallis Test , we can decide whether the population distributions are identical without assuming them to follow the normal distribution.” The added benefit of this test is not assuming a normal distribution.


It exists other tests of the same nature that could fit into that framework. The Mann-Whitney-Wilcoxon test or the Kolmogorov-Smirnov tests would perfectly suits the framework describes here however this is beyond the scope of this article to discuss the pros and cons of each of these tests. A good description along with R examples can be found here.


Here’s the code used to generate the chart above and the analysis:


In the example above the in sample period is longer than the out of sample period therefore I randomly created 1000 subsets of the in sample data each of them having the same length as the out of sample data. Then I tested each in sample subset against the out of sample data and I recorded the p-values. This process creates not a single p-value for the Kruskall-Wallis test but a distribution making the analysis more robust. In this example the mean of the p-values is well above zero (0.478) indicating that the null hypothesis should be accepted: there are strong evidences that the in and out of sample data is coming from the same distribution.


As usual what is presented in this post is a toy example that only scratches the surface of the problem and should be tailored to individual needs. However I think it proposes an interesting and rational statistical framework to evaluate out of sample results.


This post is inspired by the following two papers:


Vigier Alexandre, Chmil Swann (2007), “Effects of Various Optimization Functions on the Out of Sample Performance of Genetically Evolved Trading Strategies”, Forecasting Financial Markets Conference.


Vigier Alexandre, Chmil Swann (2010), « An optimization process to improve in/out of sample consistency, a Stock Market case», JP Morgan Cazenove Equity Quantitative Conference, London October 2010.


Introducing fidlr: FInancial Data LoadeR.


fidlr is an RStudio addin designed to simplify the financial data downloading process from various providers. This initial version is a wrapper around the getSymbols function in the quantmod package and only Yahoo, Google, FRED and Oanda are supported. I will probably add functionalities over time. As usual with those things just a kind reminder: “THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND…”


How to install and use fidlr?


You can get the addin/package from its Github repository here (I will register it on CRAN later on) Install the addin. There is an excellent tutorial to install RStudio Addins here. Once the addin is installed it should appear in the Addin menu. Just chose fidlr in the menu and a window as pictured below should appear. Choose a data provider from the the Source dropdown menu. Select a date range from the Date menu Enter the symbol you wish to download in the instrument text box. To download several symbols just enter the symbols separated by commas. Use the Radio buttons to choose whether you want to download the instrument in a csv file or in the global environment. The csv file will be saved in the working directory and there will be one csv file per instrument. Press Run to get the data or Close to close down the addin.


Error messages and warnings are handled by the underlying packages (quantmod and Shiny) and can be read from the console.


This is a very first version of the project so do not expect perfection but hopefully it will get better over time. Please report any comment, suggestion, bug etc… to: thertrader@gmail.


Maintaining a database of price files in R.


Doing quantitative research implies a lot of data crunching and one needs clean and reliable data to achieve this. What is really needed is clean data that is easily accessible (even without an internet connection). The most efficient way to do this for me has been to maintain a set of csv files. Obviously this process can be handled in many ways but I found very efficient and simple overtime to maintain a directory where I store and update csv files. I have one csv file per instrument and each file is named after the instrument it contains. The reason I do so is twofold: First, I don’t want to download (price) data from Yahoo, Google etc… every time I want to test a new idea but more importantly once I identified and fixed a problem, I don’t want to have to do it again the next time I need the same instrument. Simple yet very efficient so far. The process is summarized in the chart below.


In everything that follows, I assume that data is coming from Yahoo. The code will have to be amended for data from Google, Quandl etc… In addition I present the process of updating daily price data. The setup will be different for higher frequency data and other type of dataset (i. e. different from prices).


1 & # 8211; Initial data downloading (listOfInstruments. R & historicalData. R)


The file listOfInstruments. R is a file containing only the list of all instruments.


If an instrument isn’t part of my list (i. e. no csv file in my data folder) or if you do it for the very first time you have to download the initial historical data set. The example below downloads a set of ETFs daily prices from Yahoo Finance back to January 2000 and store the data in a csv file.


2 & # 8211; Update existing data (updateData. R)


The below code starts from existing files in the dedicated folder and updates all of them one after the other. I usually run this process everyday except when I’m on holiday. To add a new instrument, simply run step 1 above for this instrument alone.


3 & # 8211; Create a batch file (updateDailyPrices. bat)


Another important part of the job is creating a batch file that automates the updating process above (I’m a Windows user). This avoids opening R/RStudio and run the code from there. The code below is placed on a. bat file (the path has to be amended with the reader’s setup). Note that I added an output file (updateLog. txt) to track the execution.


The process above is extremely simple because it only describes how to update daily price data. I’ve been using this for a while and it has been working very smoothly for me so far. For more advanced data and/or higher frequencies, things can get much trickier.


As usual any comments welcome.


Factor Evaluation in Quantitative Portfolio Management.


When it comes to managing a portfolio of stocks versus a benchmark the problem is very different from defining an absolute return strategy. In the former one has to hold more stocks than in the later where no stocks at all can be held if there is not good enough opportunity. The reason for that is the tracking error . This is defined as the standard deviation of the portfolio return minus the benchmark return. The less stocks is held vs. a benchmark the higher the tracking error (e. g higher risk).


The analysis that follows is largely inspired by the book “Active Portfolio Management” by Grinold & Kahn. This is the bible for anyone interested in running a portfolio against a benchmark. I strongly encourage anyone with an interest in the topic to read the book from the beginning to the end. It’s very well written and lays the foundations of systematic active portfolio management (I have no affiliation to the editor or the authors).


Here we’re trying to rank as accurately as possible the stocks in the investment universe on a forward return basis. Many people came up with many tools and countless variant of those tools have been developed to achieve this. In this post I focus on two simple and widely used metrics: Information Coefficient (IC) and Quantiles Return (QR).


The IC gives an overview of the factor forecasting ability. More precisely, this is a measure of how well the factor ranks the stocks on a forward return basis. The IC is defined as the rank correlation ( ρ ) between the metric (e. g. factor) and the forward return. In statistical terms the rank correlation is a nonparametric measure of dependance between two variables. For a sample of size n , the n raw scores are converted to ranks , and ρ is computed from:


The horizon for the forward return has to be defined by the analyst and it’s a function of the strategy’s turnover and the alpha decay (this has been the subject of extensive research). Obviously ICs must be as high as possible in absolute terms.


For the keen reader, in the book by Grinold & Kahn a formula linking Information Ratio (IR) and IC is given: with breadth being the number of independent bets (trades). This formula is known as the fundamental law of active management . The problem is that often, defining breadth accurately is not as easy as it sounds.


In order to have a more accurate estimate of the factor predictive power it’s necessary to go a step further and group stocks by quantile of factor values then analyse the average forward return (or any other central tendency metric) of each of those quantiles. The usefulness of this tool is straightforward. A factor can have a good IC but its predictive power might be limited to a small number of stocks. This is not good as a portfolio manager will have to pick stocks within the entire universe in order to meet its tracking error constraint. Good quantiles return are characterised by a monotonous relationship between the individual quantiles and forward returns.


All the stocks in the S&P500 index (at the time of writing). Obviously there is a survival ship bias: the list of stocks in the index has changed significantly between the start and the end of the sample period, however it’s good enough for illustration purposes only.


The code below downloads individual stock prices in the S&P500 between Jan 2005 and today (it takes a while) and turns the raw prices into return over the last 12 months and the last month. The former is our factor, the latter will be used as the forward return measure.


Below is the code to compute Information Coefficient and Quantiles Return. Note that I used quintiles in this example but any other grouping method (terciles, deciles etc…) can be used. it really depends on the sample size, what you want to capture and wether you want to have a broad overview or focus on distribution tails. For estimating returns within each quintile, median has been used as the central tendency estimator. This measure is much less sensitive to outliers than arithmetic mean.


And finally the code to produce the Quantiles Return chart.


3 & # 8211; How to exploit the information above?


In the chart above Q1 is lowest past 12 months return and Q5 highest. There is an almost monotonic increase in the quantiles return between Q1 and Q5 which clearly indicates that stocks falling into Q5 outperform those falling into Q1 by about 1% per month. This is very significant and powerful for such a simple factor (not really a surprise though…). Therefore there are greater chances to beat the index by overweighting the stocks falling into Q5 and underweighting those falling into Q1 relative to the benchmark.


An IC of 0.0206 might not mean a great deal in itself but it’s significantly different from 0 and indicates a good predictive power of the past 12 months return overall. Formal significance tests can be evaluated but this is beyond the scope of this article.


The above framework is excellent for evaluating investments factor’s quality however there are a number of practical limitations that have to be addressed for real life implementation:


Rebalancing : In the description above, it’s assumed that at the end of each month the portfolio is fully rebalanced. This means all stocks falling in Q1 are underweight and all stocks falling in Q5 are overweight relative to the benchmark. This is not always possible for practical reasons: some stocks might be excluded from the investment universe, there are constraints on industry or sector weight, there are constraints on turnover etc… Transaction Costs : This has not be taken into account in the analysis above and this is a serious brake to real life implementation. Turnover considerations are usually implemented in real life in a form of penalty on factor quality. Transfer coefficient : This is an extension of the fundamental law of active management and it relaxes the assumption of Grinold’s model that managers face no constraints which preclude them from translating their investments insights directly into portfolio bets.


And finally, I’m amazed by what can be achieved in less than 80 lines of code with R…


As usual any comments welcome.


Risk as a “Survival Variable”


I come across a lot of strategies on the blogosphere some are interesting some are a complete waste of time but most share a common feature: people developing those strategies do their homework in term of analyzing the return but much less attention is paid to the risk side its random nature. I’ve seen comment like “a 25% drawdown in 2011 but excellent return overall”. Well my bet is that no one on earth will let you experience a 25% loss with their money (unless special agreements are in place). In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so for a few months before you gain a bit of credibility.


First let’s say you have a bad start and you lose money at the beginning. With a 10% drawdown you’re most certainly out but even with a 5% drawdown the chances of seeing your allocation reduced are very high. This has significant implications on your strategies. Let’s assume that if you lose 5% your allocation is divided by 2 and you come back to your initial allocation only when you passed the high water mark again (e. g. the drawdown comes back to 0). In the chart below I simulated the experiment with one of my strategies.


You start trading in 1st June 2003 and all goes well until 23rd Jul. 2003 where your drawdown curve hits the -5% threshold (**1**). Your allocation is cut by 50% and you don’t cross back the high water mark level until 05th Dec. 2003 (**3**). If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. 2003 (**2**) and by the end of the year you would have made more money.


But let’s push the reasoning a bit further. Still on the chart above, assume you get really unlucky and you start trading toward mid-June 2003. You hit the 10% drawdown limit by the beginning of August and you’re most likely out of the game. You would have started in early August your allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date….


The trading success of any individual has some form of path dependency and there is not much you can do about it. However you can control the size of a strategy’s drawdown and this should be addressed with great care. A portfolio should be diversified in every possible dimension: asset classes, investment strategies, trading frequencies etc…. From that perspective risk is your “survival variable”. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. Otherwise you won’t be there next month to see what happens.


As usual any comments welcome.


A Simple Shiny App for Monitoring Trading Strategies – Parte II.


This is a follow up on my previous post “A Simple Shiny App for Monitoring Trading Strategies“. I added a few improvements that make the app a bit better (at least for me!). Below is the list of new features :


A sample. csv file (the one that contains the raw data) A “EndDate” drop down box allowing to specify the end of the period. A “Risk” page containing a VaR analysis and a chart of worst performance over various horizons A “How To” page explaining how to use and tailor the app to individual needs.


I also made the app totally self contained. It is now available as a stand alone product and there is no need to have R/RStudio installed on your computer to run it. It can be downloaded from the R Trader Google drive account. This version of the app runs using portable R and portable Chrome. For the keen reader, this link explains in full details how to package a Shiny app into a desktop app (Windows only for now).


1 & # 8211; How to install & run the app on your computer.


Create a specific folder Unzip the contain of the. zip file onto that new folder. Change the paths in the runShinyApp file to match your setings To run the app, you just have launch the run. vbs file. I also included an icon (RTraderTradingApp. ico) should you want to create a shortcut on your desktop.


ui. R: controls the layout and appearance of the app server. R: contains the instructions needed to build the app. You can load as much strategies as you want as long as the corresponding csv file has the right format (see below). shinyStrategyGeneral. R: loads the required packages and launches the app.


3 & # 8211; How to add a trading strategy?


Create the corresponding. csv file in the right directory Create a new input in the data reactive function (within the server. R file) Add an extra element to the choice parameter in the first selectInput in the sidebarPanel (within the ui. R file). The element’s name should match the name of the new input above.


Remove the input in the data reactive function corresponding to the strategy you want to remove (within the server. R file) Remove the element in the choice parameter in the first selectInput in the sidebarPanel corresponding to the strategy you want to remove (within the ui. R file).


Please feel free to get in touch should you have any suggestion.


A Simple Shiny App for Monitoring Trading Strategies.


In a previous post I showed how to use R, Knitr and LaTeX to build a template strategy report. This post goes a step further by making the analysis interactive. Besides the interactivity, the Shiny App also solves two problems :


I can now access all my trading strategies from a single point regardless of the instrument traded. Coupled with the Shiny interactivity, it allows easier comparison. I can focus on a specific time period.


The code used in this post is available on a Gist/Github repository. There are essentially 3 files.


ui. R : controls the layout and appearance of the app. server. R : contains the instructions needed to build the app. It loads the data and format it. There is one csv file per strategy each containing at least two columns: date and return with the following format: (“2010-12-22″,”0.04%” ). You can load as much strategies as you want as long as they have the right format. shinyStrategyG eneral. R : loads the required packages and launches the app.


This app is probably far from perfect and I will certainly improve it in the future. Feel free to get in touch should you have any suggestion.


A big thank you to the RStudio/Shiny team for such a great tool.


Using Genetic Algorithms in Quantitative Trading.


The question one should always asked him/herself when using technical indicators is what would be an objective criteria to select indicators parameters (e. g., why using a 14 days RSI rather than 15 or 20 days?). Genetic algorithms (GA) are well suited tools to answer that question. In this post I’ll show you how to set up the problem in R. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. It’s not a finished strategy either but a research idea that needs to be further researched, developed and tailored to individual needs.


What are genetic algorithms?


The best description of GA I came across comes from Cybernatic Trading a book by Murray A. Ruggiero. “Genetic Algorithms were invented by John Holland in the mid-1970 to solve hard optimisation problems. This method uses natural selection, survival of the fittest”. The general process follows the steps below:


Encode the problem into chromosomes Using the encoding, develop a fitness function for use in evaluating each chromosome’s value in solving a given problem Initialize a population of chromosomes Evaluate each chromosome in the population Create new chromosomes by mating two chromosomes. This is done by muting and recombining two parents to form two children (parents are selected randomly but biased by their fitness) Evaluate the new chromosome Delete a member of the population that is less fit than the new chromosome and insert the new chromosome in the population. If the stop criteria is reached (maximum number of generations, fitness criteria is good enough…) then return the best chromosome alternatively go to step 4.


From a trading perspective GA are very useful because they are good at dealing with highly nonlinear problems. However they exhibit some nasty features that are worth mentioning:


Over fitting: This is the main problem and it’s down to the analyst to set up the problem in a way that minimises this risk. Computing time : If the problem isn’t properly defined, it can be extremely long to reach a decent solution and the complexity increases exponentially with the number of variables. Hence the necessity to carefully select the parameters.


There are several R packages dealing with GA, I chose to use the most common one: rgenoud.


Daily closing prices for most liquid ETFs from Yahoo finance going back to January 2000. The in sample period goes from January 2000 to December 2010. The Out of sample period starts on January 2011.


The logic is as following: the fitness function is optimised over the in sample period to obtain a set of optimal parameters for the selected technical indicators. The performance of those indicators is then evaluated in the out of sample period. But before doing so the technical indicators have to be selected.


The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: moving averages cross over and RSI. This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes . The other key element is the fitness function . We might want to use something like: maximum return or Sharpe ratio or minimum average Drawdown. In what follows, I chose to maximise the Sharpe ratio.


The R implementation is a set of 3 functions:


fitnessFunction : defines the fitness function (e. g., maximum Sharpe ratio) to be used within the GA engine tradingStatistics : summary of trading statistics for the in and out of sample periods for comparison purposes genoud : the GA engine from the rgenoud package.


The genoud function is rather complex but I’m not going to explain what each parameter means as I want to keep this post short (and the documentation is really good).


In the table below I present for each instrument the optimal parameters (RSI look-back period, RSI threshold, Short Term Moving Average, and Long Term Moving Average) along with the in and out of sample trading statistics.


LearnDataSci.


Home »Python for Finance, Parte 2: Introdução às Estratégias Quantitativas de Negociação.


Python for Finance, Parte 2: Introdução às Estratégias Quantitativas de Negociação.


Python for Finance, Parte 2: Introdução às Estratégias Quantitativas de Negociação.


Idioma: Bibliotecas do Python 3.5: pandas, numpy e matplotlib iPython notebook: disponível no GitHub.


Em Python for Finance, Parte I, nos concentramos em usar Python e Pandas para.


recuperar séries temporais financeiras de fontes on-line gratuitas (Yahoo), formatar os dados preenchendo observações ausentes e alinhá-las, calcular alguns indicadores simples, como calcular as médias móveis e visualizar as séries temporais finais.


Como um lembrete, o dataframe contendo os três & # 8220; limpos & # 8221; preço timeeries tem o seguinte formato:


Também calculamos as médias móveis contínuas dessas três séries temporais da seguinte maneira. Observe que, ao calcular a média móvel de $ M $ dias, os primeiros $ M-1 $ não são válidos, pois os preços $ M $ são necessários para o primeiro ponto de dados da média móvel.


Com base nesses resultados, nosso objetivo final será criar uma estratégia comercial simples, porém realista. No entanto, primeiro precisamos passar por alguns dos conceitos básicos relacionados a estratégias quantitativas de negociação, bem como as ferramentas e técnicas no processo.


Considerações gerais sobre estratégias de negociação.


Existem várias maneiras de se fazer uma estratégia de negociação a ser desenvolvida. Uma abordagem seria usar o preço série de tempo diretamente e trabalhar com números que correspondam a algum valor monetário. Por exemplo, um pesquisador poderia estar trabalhando com séries temporais expressando o preço de um determinado estoque, como as séries temporais usadas no artigo anterior. Da mesma forma, se estiver trabalhando com instrumentos de renda fixa, por exemplo títulos, pode-se usar uma série temporal expressando o preço do título como uma porcentagem de um determinado valor de referência, neste caso o valor nominal do título. Trabalhar com esse tipo de série temporal pode ser mais intuitivo, já que as pessoas estão acostumadas a pensar em termos de preços. No entanto, as séries temporais de preços têm algumas desvantagens. Os preços geralmente são positivos, o que dificulta o uso de modelos e abordagens que exigem ou produzem números negativos. Além disso, as séries temporais de preços são geralmente não estacionárias, ou seja, suas propriedades estatísticas são menos estáveis ​​ao longo do tempo.


Uma abordagem alternativa é usar séries temporais que correspondam não a valores reais, mas a alterações no valor monetário do ativo. Estas séries temporais podem e assumem valores negativos e também, suas propriedades estatísticas são geralmente mais estáveis ​​do que as de séries temporais de preços. Os formulários usados ​​com mais frequência são retornos relativos definidos como.


e retornos de log definidos como.


onde $ p \ left (t \ right) $ é o preço do ativo no momento $ t $. Por exemplo, se $ p \ left (t \ right) = 101 $ e $ p \ left (t-1 \ right) = 100 $ então $ r_> \ left (t \ right) = \ frac = 1 \% $ .


Existem várias razões pelas quais os retornos de registros estão sendo usados ​​na indústria e alguns deles estão relacionados a hipóteses de longa data sobre o comportamento dos retornos de ativos e estão fora do nosso escopo. No entanto, o que precisamos salientar são duas propriedades bastante interessantes. Log-retornos são aditivos e isso facilita o tratamento de nossas séries temporais, retornos relativos não são. Podemos ver a aditividade de log-retornos na seguinte equação.


que é simplesmente o log-retorno de $ t_0 $ a $ t_2 $. Em segundo lugar, os retornos de log são aproximadamente iguais aos retornos relativos para valores de $ \ frac $ suficientemente próximos de $ 1 $. Tomando a primeira ordem de expansão de Taylor $ \ log \ left (\ frac \ right) $ em torno de $ 1 $, conseguimos.


Ambos são calculados trivialmente usando Pandas como:

Комментарии

Популярные сообщения из этого блога

Dahabshiil forex bureau quénia

Banco do estado da índia forex taxas hoje

100 bônus de boas-vindas forex