Tuesday 11 July 2017

Movendo Média Pylab


Spyder - o Python IDE Seg 16 setembro 2013 Hans Fangohr. University of Southampton, Reino Unido, 2013 Spyder desenvolveu-se em uma ferramenta bastante madura e muito produtiva aqui eu tento fornecer um tutorial. Esta documentação é motivada por cursos de treinamento em Python e modelagem computacional para estudantes da Universidade de Southampton (ver nota histórica para mais detalhes). Esta entrada de blog foi integrada no Spyder como o Tutorial. Uma vez que o Spyder tenha iniciado, a versão mais atualizada deste tutorial pode ser encontrada no tutorial do Help - gt Spyder. Obtenha o arquivo hello world na janela do editor do Spyder, baixando hello. py e salve como hello. py. (Faça o download do arquivo clicando com o botão direito do mouse no link no seu navegador e selecione Salvar destino como ou Salvar download como) e abra o arquivo hello. py no menu Arquivo e selecione Abrir. Expressamos isso como Arquivo - gt Open em suma. Clique em hello. py para ver o código fonte no webbrowser, em seguida, copie o código inteiro navegar para a janela do editor no spyder e cole o código. Em seguida, salve o arquivo como hello. py. Para executar o programa, selecione Run - gt Run (ou pressione F5) e confirme as configurações de Run, se necessário. Você deve ver a saída como: ou (o caminho específico dependerá de onde você salvou o arquivo, mas isso é inserido pelo Spyder automaticamente): Se assim for, então você acabou de executar o seu primeiro programa Python - bem feito. Antes de prosseguir, por favor O console IPython pode fazer um pouco mais do que o console padrão do Python, e sugerimos usá-lo como o console padrão aqui. Na sessão do interpretador IPython que acabamos de iniciar, você pode usar Run-gtRun (como antes) para executar hello. py e você deve ver: Python lê o arquivo linha por linha, ignorando comentários quando ele vem através da palavra-chave def, ele Sabe que uma função é DEFINIDA nesta e na próxima (uma ou mais) linhas. No arquivo hello. py, o Python cria um objeto de função com o nome hello. Todas as linhas recuadas após def hello (): pertencem ao corpo da função. Observe que o objeto de função é criado apenas neste ponto no arquivo, mas a função ainda não é chamada (ou seja, não executada). Quando Python se deparar com comandos (que não def. E algumas outras palavras-chave) que são escritos na coluna mais à esquerda, ele irá executá-los imediatamente. No arquivo hello. py esta é apenas a linha de leitura hello () que realmente chamará (ou seja, executar) a função com o nome hello. Se você remover a linha hello () do programa e executar o arquivo inteiro novamente (pressionando F5, ou selecionando executar - gt executar), nada será impresso (porque a função hello é definida, mas não chamado, ou seja, não executado) . Agora você deve saber como executar um programa Python que você tem na janela do editor no Spyder usando o Python Console eo Console IPython mais sofisticado. Se você está apenas começando a aprender Python, este é provavelmente um bom ponto para retornar ao seu curso livro de texto e olhar para mais exemplos básicos. A próxima seção fornece informações mais detalhadas sobre como executar partes do código no editor no console do Python e, assim, atualizar partes de suas definições no editor. Esta é uma técnica mais avançada, mas pode ser muito útil. (Você também pode estar interessado na opção de executar pedaços (chamados quotcellsquot) de código que são separados por delimitadores - veja atalhos para funções úteis.) Depois de ter executado o hello. py programa, o objeto função hello é definido E conhecido no prompt do Python. Podemos chamar a função a partir do prompt Python: Chame a função hello () do prompt Python, ie digite hello () na janela Python Shell (o prompt do Python mostra como gtgtgt. Ou como In se usarmos a sessão IPython onde O ponto de interrogação pode ser qualquer número inteiro positivo.), E pressione a tecla de retorno. Você deve achar que a função hello () é executada novamente, ou seja, Hello World é impresso novamente. Sua chamada de função no prompt do Python juntamente com a saída deve ser assim: Você pode ver como isso difere de executar todo o programa novamente Quando executamos todo o programa (pressionando F5), Python passa pelo arquivo, cria a função hello Objeto (substituindo o objeto anterior), atinge o programa principal e chama a função. Quando chamamos hello () do prompt Python, chamamos somente os objetos de função hello que foram definidos no console (I) Python quando executamos o arquivo hello. py inteiro mais cedo (pressionando F5). Isso se tornará mais claro ao longo do tempo e também quando trabalharmos com exemplos um pouco maiores. Você pode querer retornar a este tutorial em um estágio um pouco mais tarde. O Python fornece uma função que exibe todos os objetos conhecidos (no espaço de nome atual). É chamado dir (). Quando você digita dir () no prompt, você obtém uma lista de objetos conhecidos. Ignore tudo começando com um sublinhado por enquanto. Você pode ver Olá na lista (Se você receber uma longa lista de objetos definidos, então o Spyder pode ter feito algumas conveniências de importação para você já. Para resolver isso, você pode querer: Em seguida, execute dir () como sugerido acima. Objeto é visível no espaço de nome atual (como é hello neste exemplo), podemos usar a função de ajuda da seguinte forma para aprender sobre ele: Digite help (hello) no prompt de Python, você deve ver a saída como este: Onde Python Tomar as informações de alguns deles (como o número de argumentos de entrada e nomes dessas variáveis ​​aqui não temos argumentos de entrada) Python pode encontrar através de inspecionar seus objetos, informações adicionais vem da seqüência de documentação fornecida para o objeto função hello. A string de documentação é a primeira string imediatamente abaixo da linha def hello ():. O ambiente do Spyder também fornece um painel no canto superior direito (por padrão), que é o Inspetor de objetos. Se você digitar hello na linha vazia na janela Inspetor de objetos, também fornecerá a seqüência de ajuda. Na janela Editor, altere a função hello para que imprima Good Bye World em vez de Hello World. Pressione F5 (para executar todo o programa) e verifique se a saída do programa está agora: O que aconteceu quando você pressionou F5 é isto: Python passou pelo arquivo hello. py e criou um novo objeto de função hello (substituindo a função Objeto hello que tínhamos definido antes) e, em seguida, executou a função. Temos de começar com um estado claramente definido. Para fazer isso, altere a função hello () de volta para que ela imprima Hello World (ou seja, use o arquivo hello. py original), então pressione F5 para executar todo o programa e verifique se ele imprime Hello World. Chame a função hello () a partir do prompt de comando (conforme descrito em Chamar objetos de função existentes a partir da linha de comando). Você deve ver o Hello World impresso. Agora altere a definição da função para que ela imprima Laters World. E salve o arquivo (mas NÃO execute o programa, ou seja, não pressione F5 ainda). Chamar a função hello () a partir da linha de comandos novamente. Você deve achar que o texto impresso lê Hello World. Como aqui Por que isso é assim Porque o objeto de função hello no interpretador Python é o antigo que imprime Hello World. Até agora, alteramos o arquivo hello. py (e substituímos Hello World por Laters World) no editor, mas isso não afetou os objetos que foram criados anteriormente no interpretador Python. Aqui estão duas possibilidades de usar a nossa versão modificada da função hello: Opção 1: executar o arquivo inteiro hello. py novamente pressionando F5: isso cria um novo objeto função hello (e substitui o antigo). Você deve descobrir que se você pressionar F5 e, em seguida, chamar hello () no prompt, o novo texto Laters World é impresso. Opção 2: selecione a região que você alterou (neste caso, a função inteira hello. a partir da linha def hello (): para baixo para retornar None e selecione Run - gt Run seleção. Isto atualizará o objeto hello no interpretador Sem ter que executar todo o arquivo hello. py: Se nós agora digitar hello (). Vemos a resposta de atualização: A capacidade de executar partes do código para atualizar alguns objetos no interpretador (no exemplo acima, nós atualizamos a função Objeto hello), é de grande utilidade ao desenvolver e depurar códigos mais complexos, e ao criar objectsdata na sessão de intérprete levar tempo. Por exemplo, ao modificar apenas as funções (ou objetos de classes, etc) que estamos realmente desenvolvendo ou depuração, nós Podemos continuar a reutilizar as estruturas de dados, etc, que são definidas na sessão de interpretação. Para ensinar programação Python e modelagem computacional, recomendamos (i) usar IPython em vez do intérprete Python normal e (ii) não usar qualquer conveniência importações. Seu IPython aceita como o padrão de facto e ajuda a compreender melhor namespaces. O Spyder tenta ajudar usuários mais avançados ao importar um número de módulos para o espaço de nome principal. Digite scientific no prompt de comando para ver os detalhes. Esse comportamento pode mudar nas versões futuras do Spyder. Embora essas importações de conveniência sejam muito úteis para programadores mais experientes, elas podem ser confusas (se não enganosas) para iniciantes. Recomendamos, portanto, desfazer essas importações para que atendam aos nossos requisitos acima e (i) mudar para um console IPython. E (ii) emitir o comando reset para redefinir o espaço de nomes. Ambas as etapas são explicadas com mais detalhes na próxima seção. Na janela de console (canto inferior direito por padrão), você verá por padrão um prompt com três sinais maiores do que, ou seja, gtgtgt. Isso mostra que estamos usando o console - basicamente uma sessão de interpretador Python normal (com algumas funcionalidades adicionais do Spyder). Em vez disso, gostaríamos de usar um shell Interactive Python, um IPython curto do projeto ipython. Para fazer isso, selecione Interpreters - gt Abra um console IPython. Você deve ver na janela consolse um novo shell aparecendo, eo prompt IPython In 1: deve ser exibido. O espaço de nomes pode ser limpo no IPython usando o comando reset. Digite reset e pressione return e confirme com y: Discutimos isto um pouco mais, mas você pode ignorar o seguinte se você não estiver interessado: Depois de emitir o comando reset, devemos ter apenas alguns objetos definidos no namespace daquela sessão . Podemos listar todos eles usando o comando dir (): Finalmente, se você quiser ignorar a etapa de confirmação do comando reset, use pode usar reset - f em vez de reset. Além da Sintaxe que é aplicada pelo Python, existem convenções adicionais sobre o layout do código fonte, em particular o Guia de Estilo para o código fonte Python sabe como quotPEP8quot. Um monte de comportamento Spyders pode ser configurado através de suas preferências. Onde está localizado no menu depende do seu sistema operacional: No Windows e Linux, vá para Ferramentas - gt Preferências No Mac OS, vá para Python - gt Preferências Ir para Preferências - gt IPython console - gt Inicialização e selecione a caixa de seleção ao lado de Abra um console IPython na inicialização. Em seguida, clique no botão OK. A próxima vez que o Spyder for iniciado, ele mostrará o console IPython automaticamente. Vá para Preferences - gt Editor - gt Code IntrospectionAnalysis e selecione a caixa de seleção ao lado de Style analysis (PEP8) Para evitar qualquer magia quando o console é iniciado, vá para Preferências - gt Console - gt Configurações Avançadas - gt PYTHONSTARTUP substituição e selecione Default PYTHONSTARTUP script (E reinicie o Spyder). (Essa mágica, entre outras coisas, executa o comando de divisão de importação do futuro.) As configurações padrão podem mudar para isso na próxima versão principal. Para evitar a importação de todos os objetos de pylab e numpy para o espaço de nome atual no Console IPython, vá para Preferências - gt Console IPython - gt Graphics e desmarque a caixa de seleção ao lado de Carregar automaticamente módulos Pylab e NumPy e também desmarque Ativar suporte. As configurações padrão podem mudar para isso na próxima versão principal. Através de Preferências - gt IPython console - gt Configurações Avançadas - gt Use matemática simbólica podemos ativar o modo python simbólico de IPythons. Isso permitirá que a saída do sympy seja bem renderizada (estilo látex) e também importe alguns objetos sympy automaticamente quando o console IPython for iniciado e relata o que ele fez. Podemos então usar as variáveis ​​x. Y. Por exemplo: F5 executa o buffer atual F9 executa o bloco de código atualmente destacado: isso é muito útil para atualizar definições de funções (digamos) na sessão do interpretador sem precisar executar o arquivo inteiro novamente CTRL ltRETURNgt executa a célula atual No menu Executar - gt Executar célula). Uma célula é definida como o código entre duas linhas que começam com a tag acordada. SHIFT ltRETURNgt executa a célula atual e avança o cursor para a próxima célula (entrada de menu Executar - gt Executar célula e avançar). As células são úteis para executar um grande segmento de filecode em unidades menores. (É um pouco como uma célula em um notebook IPython, em que pedaços de código pode ser executado independentemente.) ALT ltCURSOR UPgt move a linha atual para cima. Se várias linhas forem destacadas, elas serão movidas para cima. ALTltCURSOR DOWNgt trabalha correspondentemente com a (s) linha (s) em movimento para baixo. Clicando com o botão direito em um método de função na fonte, abre-se um novo editor de janelas mostrando a definição dessa função. SHIFTCTRLALTM maximiza a janela atual (ou muda o tamanho de volta ao normal se pressionado em uma janela maximizada) SHIFTCTRLF ativa a pesquisa em todos os arquivos. No Mac OS X: CMD irá aumentar o tamanho da fonte no editor, CMD - diminuir. Também funciona no Console IPython. O tamanho da fonte para o explorador de objetos, o console Python etc pode ser definido individualmente através de Preferências - gt Object explorer etc Eu não poderia encontrar uma maneira de mudar o tamanho da fonte no explorador de variáveis. CTRLSPACE autocompletes comandos, nomes de função, nomes de variáveis, métodos muito úteis. CMDs (no Mac OS X) e CTRLs (caso contrário) na janela do editor salva o arquivo atualmente sendo editado. Isso também força vários triângulos de aviso na coluna esquerda do editor a serem atualizados (caso contrário, eles são atualizados a cada 2 a 3 segundos por padrão). CMDs (no Mac OS X) e CTRLs (caso contrário) na janela do console IPython salva a sessão IPython atual como um arquivo HTML, incluindo quaisquer figuras que podem ser exibidas inline. Isso é útil como uma maneira rápida de gravar o que foi feito em uma sessão. CMDi (no Mac OS X) e CTRLi (caso contrário) quando pressionado enquanto o cursor está em um objeto (não é possível carregar este registro salvo na sessão - se você precisar de uma funcionalidade como esta, procure o IPython Notebook. , Abre a documentação para esse objeto no inspector de objetos. Estas são as configurações que definem como o código no editor é executado se selecionarmos Executar - gt Run ou pressione F5. Por padrão, a caixa de configurações será exibida na primeira vez que tentar executar um arquivo. Se quisermos alterar as configurações em qualquer outro momento, elas podem ser encontradas em Run - gt Configure ou pressionando F6. Há três escolhas para o intérprete usar, de que eu discuto os dois primeiros. Vamos supor que temos um programa hello. py no editor que lê Esta é a sugestão padrão, e também geralmente uma boa escolha. Escolhendo Executar na configuração atual do interpretador Python ou IPython em Executar - gt Configure significa que Quando a execução de hello. py é concluída, podemos interagir com o interpretador no qual o programa foi executado e podemos usar o conveniente intérprete IPython para isso Que o interpretador Python padrão). Podemos inspecionar e interagir com objetos que a execução de nosso programa criou, como i e hello (). Isso geralmente é muito útil para a codificação incremental, testes e depuração: podemos chamar hello () diretamente do prompt do interpretador, e não precisa executar todo o hello. py para isso (embora se mudar a função hello (). Para executar o buffer, ou pelo menos a definição da função, para tornar a nova versão do hello () visível no intérprete executando o buffer inteiro ou via Run - gt Run Selection.) No entanto, executando o código no editor no Interpretador atual também significa que o código que executa pode ver outros objetos (globais) que foram definidos na sessão de interpretador. Esta persistência de objetos é facilmente esquecida e geralmente não é necessária quando se trabalha em pequenos programas (embora possa ser de grande valor ocasionalmente). Esses objetos podem vir de execução anterior do código, do trabalho interativo no interpretador ou de importações de conveniência, como da importação do pylab (o Spyder pode fazer algumas dessas importações de conveniência automaticamente). Essa visibilidade de objetos no espaço de nome global do interpretador para o código que executamos também pode resultar em erros de codificação se o código invoca inadvertidamente esses objetos. Aqui está um exemplo: imagine que executamos o código hello. py. Posteriormente, a variável i é conhecida no interpretador como uma variável global. Editamos a fonte hello. py e apagamos acidentalmente a linha i 42 executamos o buffer contendo hello. py novamente. Neste ponto, a chamada de hello (i) não falhará porque o interpretador tem um objeto de nome i definido, embora isso não esteja definido na fonte de hello. py. Neste ponto, poderíamos salvar o hello. py e (falsamente) pensar que ele seria executado corretamente. No entanto, executá-lo em uma nova sessão de interpretador python (ou via python hello. py. Say) resultaria em um erro, porque i não está definido. O problema surge porque o código faz uso de um objeto (aqui i) sem criá-lo. Isso também afeta a importação de módulos: se tivéssemos importado o pylab no prompt do IPython, então o nosso programa verá isso quando executado nesta sessão do interpretador IPython. Para saber como podemos verificar se o nosso código não depende desses objetos existentes, consulte Como verificar se o seu código é executado corretamente quotone seu próprio. Escolhendo Executar no novo intérprete Python dedicado em Executar - gt Configure iniciará um novo interpretador Python toda vez que o programa hello. py for executado. A principal vantagem deste modo sobre Executar no atual interpretador Python ou IPython é que podemos ter certeza de que não há objetos globais definidos neste intérprete que se originam de depuração e execução repetida do nosso código: cada vez que executamos o código no editor , O interpretador python no qual o código é executado é reiniciado. Esta é uma opção segura, mas fornece menos flexibilidade e não pode usar o interpretador IPyton. Supondo que você escolheu para o seu código para executar no atual interpretador Python ou IPython. Então você duas opções para verificar se o nosso código funciona por conta própria (isto é, não depende de variáveis ​​indefinidas, módulos não-importados e comandos etc) Alternativamente, se você quiser ficar com o interpretador IPython atual, você pode usar IPythons magic reset Comando que removerá todos os objetos (como i no exemplo acima) do espaço de nome atual e, em seguida, executar o código no editor. Depois de ter concluído um pedaço de código, verifique novamente que ele executa de forma independente usando uma das opções explicadas em Como verificar o seu código duplo executa corretamente quoton seu próprio. Quando vários arquivos são abertos no editor, as guias correspondentes na parte superior da área da janela são organizadas em ordem alfabética do nome do arquivo da esquerda para a direita. À esquerda das guias, há como ícone que mostra as guias Procurar se o mouse paira sobre ele. É útil para saltar para um determinado arquivo diretamente, se muitos arquivos estão abertos. As variáveis ​​de ambiente podem ser exibidas a partir da janela do Console (janela inferior direita no layout padrão). Clique no ícone Opções (a dica de ferramenta é Opções) e, em seguida, selecione Variáveis ​​de ambiente. Toda a personalização salva em disco pode ser redefinida chamando spyder da linha de comando com o switch --reset. Isto é, um comando como spyder --reset. Clicar com o botão direito do mouse em arrays no explorador de variáveis ​​oferece opções para plotar e analisar mais detalhadamente. Clicar duas vezes em um objeto de dicionário abre uma nova janela que exibe o dicionário corretamente. Presumivelmente há outra capacidade oculta para alguns outros tipos de dados. Existem algumas convenções assumidas sobre cadeias de documentação escritas em texto reestruturado. Se seguimos essas diretrizes, podemos obter seqüências de documentação formadas em Spyder. Por exemplo, para obter a nossa função average () semelhante a esta no Spyder Object explorer: Precisamos formatar a seqüência de documentação como segue O que importa aqui, é que a palavra Parâmetros é usado, e sublinhado. A linha a. Número mostra-nos que o tipo do parâmetro a é número. Na próxima linha, que está recuado, podemos escrever uma explicação mais extensa o que esta variável representa, quais condições os tipos permitidos têm de cumprir, etc. O mesmo para todos os Parâmetros e também para o valor retornado. Muitas vezes é uma boa idéia incluir um exemplo como mostrado. A ativação do modo de depuração (Debug - gt Debug) inicia o depurador IPython (ipdb) no console IPython. Isso é operado normalmente, mas a janela de exibição do editor destaca a linha que está prestes a ser executada eo explorador de variáveis ​​exibe variáveis ​​no contexto atual do ponto de execução do programa. (Exibe apenas variáveis ​​numéricas, ou seja, não objetos de função, etc.) Os comandos de chave dentro do depurador IPython são teclas individuais: s para Passo para a instrução atual. Se esta for uma chamada de função, entre nessa função. N mover para a instrução Next. Se a instrução atual for uma função, não entre nessa função, mas execute-a completamente antes de retornar o controle para o prompt do depurador interativo. R completar todas as instruções na função atual e retornar a partir dessa função antes de retornar o controle. P Print permite exibir valores de variáveis, por exemplo, p x imprimirá o valor da variável x. Observe que no ipdb, você também pode alterar os valores da variável. Por exemplo, para modificar um x válido. Você pode dizer ipdb gt x 42 e o depurador continuará com x sendo vinculado a 42. Você também pode chamar funções, e fazer muitas outras coisas. Para sair do modo de depuração, você pode digitar exit ou selecionar no menu Debug - gt Debugging Control - gt Exit No console IPython, podemos chamar debug logo após uma exceção ter sido levantada: isso vai iniciar o modo de depuração do IPython e permite Inspeção das variáveis ​​locais no ponto em que ocorreu a exceção conforme descrito acima. Isso é muito mais eficiente do que adicionar instruções de impressão ao código e executá-lo novamente. Se você usar isso, você também pode querer usar os comandos para cima e para baixo que navegam o ponto de inspeção para cima e para baixo da pilha. Assumindo que usamos um console IPython com a versão gt 1.0.0, podemos decidir se as figuras criadas com o matplotlibpylab serão mostradas inline. (Acima da pilha significa para as funções que chamaram a função atual para baixo é a direção oposta. Dentro do console IPython, ou se devem aparecer dentro de uma nova janela. A opção 1 é conveniente para salvar um registro da sessão interativa (seção Atalhos para funções úteis lista um atalho para salvar o console IPython em um arquivo html). Opção 2 permite zoom interativo na figura, manipulá-lo um pouco, e salvar a figura para diferentes formatos de arquivo através do menu. O comando para obter as figuras para aparecer inline no console IPython é matplotlib inline. O comando para obter figuras aparecem em sua própria janela (que tecnicamente é um QT windown) é matplotlib qt. As preferências do Spyder podem ser usadas para personalizar o comportamento padrão (em particular Preferências - gt IPython Console - gt Graphics - gt Ativar Suporte para alternar para plotagem em linha). Recent Posts CategoriesRelease Notes 8 de setembro de 2016 Aprimoramentos Adiciona tabelas de checkpoint de preenchimento avançado para o carregador do núcleo do blaze. Isso permite que o carregador para enviar mais eficientemente preencher os dados, limitando a data mais baixa deve procurar para quando consultar dados. Os postos de controle devem ter novos deltas aplicados (1276). Atualizado VagrantFile para incluir todos os requisitos dev e usar uma imagem mais recente (1310). Permitir que as correlações e regressões sejam calculadas entre dois fatores 2D fazendo cálculos ativos-sábios (1307). Filtros foram feitos windowsafe por padrão. Agora eles podem ser passados ​​como argumentos para outros Filtros, Fatores e Classificadores (1338). Adicionado um parâmetro groupby opcional para classificar (). topo(). E inferior (). (1349). Adicionado novos filtros de pipeline, All and Any. Que recebe outro filtro e retorna True se um ativo produziu um True para todos os dias nos dias anteriores do windowlength (1358). Adicionado novo filtro de pipeline AtLeastN. Que recebe outro filtro e um int N e retorna True se um ativo produziu um True em N ou mais dias nos dias windowlength anteriores (1367). Use biblioteca externa empírico para cálculos de risco. Empírico unifica cálculos métricos de risco entre carteira e tirolesa. Empírico adiciona opções personalizadas de anualização para retornos de freqüências personalizadas. (855) Adicionar fator Aroon. (1258) Adicionar fator de oscilador estocástico rápido. (1255) Adicione um Dockerfile. (1254) Novo calendário comercial que suporta sessões que abrangem toda a noite, por ex. 24 horas 6:01 PM-6:00PM sessões para negociação de futuros. Zipline. utils. tradingcalendar agora está desativado. (1138) (1312) Permitir cortar uma única coluna de um FactorFilterClassifier. (1267) Fornecer o fator Ichimoku Cloud (1263) Permitir parâmetros padrão nos termos Pipeline. (1263) Fornecer taxa de fator de porcentagem de mudança. (1324) Fornecer fator de média móvel ponderada linear. (1325) Adicionar NotNullFilter. (1345) Permitir que as alterações de capital sejam definidas por um valor-alvo. (1337) Adicione o fator TrueRange. (1348) Adiciona pesquisas ponto a ponto em assets. db. (1361) Faça cantrade ciente da troca de asset8217s. (1346) Adicione o método downsample a todos os termos computáveis. (1394) Adicionar QuantopianUSFuturesCalendar. (1414) Ative a publicação de versões antigas do assets. db. (1430) Habilitar a função de programação para o calendário de negociação de futuros. (1442) Proibir regressões de comprimento 1. (1466) Experimental Adicionar suporte para janelas Futureled e Equity história, e permitir outro acesso de dados Futuro via portal de dados. (1435) (1432) Correções de Bugs Mudanças AverageDollarFator incorporado de volume para tratar valores de fechamento ou volume ausentes como 0. Anteriormente, os NaNs foram simplesmente descartados antes da média, dando aos demais valores muito peso (1309). Remova a taxa livre de risco do cálculo da relação de sharpe. A relação é agora a média dos retornos ajustados ao risco sobre a volatilidade dos retornos ajustados. (853) A razão Sortino retornará o cálculo em vez de np. nan quando os retornos exigidos forem iguais a zero. A relação agora retorna a média dos retornos ajustados ao risco sobre o risco de queda. Corrigido mislabeled API convertendo mar para downsiderisk. (747) Risco de desvantagem agora retorna a raiz quadrada da média dos quadrados de diferença negativa. (747) Rácio de informação actualizado para retorno da média dos retornos ajustados ao risco sobre o desvio padrão dos retornos ajustados ao risco. (1322) As relações alfa e sharpe são agora anualizadas. (1322) Fixar unidades durante a leitura e escrita do atributo firsttradingday da barra diária. (1245) Os módulos de despacho opcionais, quando em falta, deixam de causar um NameError. (1246) Trate o argumento de função de programação como uma regra de tempo quando uma regra de tempo, mas nenhuma regra de data é fornecida. (1221) Proteja contra condições de fronteira no início e no final do dia de negociação na função de programação. (1226) Aplique ajustes ao dia anterior ao usar o histórico com uma frequência de 1d. (1256) Falha rápida em colunas de pipeline inválidas, em vez de tentar acessar a coluna inexistente. (1280) Correção MédiaDollarVolume NaN manipulação. (1309) Melhorias de desempenho para chama carregador núcleo. (1227) Permitir consultas de chama concorrentes. (1323) Impedir que os dados de minutos bcolz levando ausentes de fazer repetidas pesquisas desnecessárias. (1451) Cache futuras pesquisas de cadeia. (1455) Manutenção e Refactorings Removido restante mentions de addhistory. (1287) Documentação Adicionar dispositivo de teste que origina dados de precificação diária de fixtures de dados de preços minuciosos. (1243) Alterações de formato de dados BcolzDailyBarReader e BcolzDailyBarWriter usam instância do calendário de negociação, em vez de dias de negociação serializados para JSON. (1330) Muda o formato de assets. db para pesquisas de ponto a ponto de suporte. (1361) Alterar BcolzMinuteBarReader e BcolzMinuteBarWriter para suportar tamanhos de carrapatos variados. (1428) Release 1.0.1 Esta é uma versão de bug-fix menor de 1.0.0 e inclui um pequeno número de correções de bugs e melhorias de documentação. Aprimoramentos Adicionado suporte para modelos de comissão definidos pelo usuário. Consulte a classe zipline. financemissionmissionModel para obter mais detalhes sobre a implementação de um modelo de comissão. (1213) Adicionado suporte para colunas não-float para Blaze-backed Pipeline datasets (1201). Adicionado zipline. pipeline. slice. Slice. Um novo termo pipeline projetado para extrair uma única coluna de outro termo. As fatias podem ser criadas pela indexação em um termo, chaveado pelo recurso. (1267) Correções de Bugs Corrigido um bug em que os carregadores de Pipeline não foram inicializados corretamente pelo zipline. runalgorithm (). Isso também afetou as invocações de tirolesa correr a partir da CLI. Corrigido um bug que causou a falha da magia de célula IPython de zipline (533233fae43c7ff74abfb0044f046978817cb4e4). Corrigido um erro no modelo de comissão PerTrade, onde as comissões foram incorretamente aplicadas a cada preenchimento parcial de uma ordem, em vez da ordem em si, resultando em algoritmos sendo cobrados demais em comissões ao colocar grandes pedidos. O PerTrade agora aplica corretamente as comissões por ordem (1213). Os acessos de atributo em CustomFactors que definem múltiplas saídas agora retornarão corretamente uma fatia de saída quando a saída for também o nome de um método Factor (1214). Substituiu o uso deprecated de pandas. io. data com pandasdatareader (1218). Corrigido um problema em que arquivos. pyi stub para zipline. api foram excluídos acidentalmente da distribuição de origem PyPI. Os usuários Conda não devem ser afetados (1230). Documentação Adicionado um novo exemplo, zipline. examples. momentumpipeline. Que exerce a Pipeline API (1230). Destaques Zipline 1.0 Rewrite (1105) Temos reescrito um monte de Zipline e seus conceitos básicos, a fim de melhorar o desempenho runtime. Ao mesmo tempo, we8217ve introduziu várias novas APIs. Em um nível alto, versões anteriores de simulações Zipline puxado de um fluxo multiplexado de fontes de dados, que foram mescladas via heapq. Este fluxo foi alimentado para o loop de simulação principal, dirigindo o relógio para a frente. Essa forte dependência na leitura de todos os dados tornou difícil otimizar o desempenho da simulação, porque não havia nenhuma conexão entre a quantidade de dados que buscamos ea quantidade de dados realmente usados ​​pelo algoritmo. Agora, só buscamos dados quando o algoritmo precisa dele. Uma nova classe, DataPortal. Envia as solicitações de dados para várias fontes de dados e retorna os valores solicitados. Isso torna o tempo de execução de uma escala de simulação muito mais próximo da complexidade do algoritmo, em vez do número de recursos fornecidos pelas fontes de dados. Em vez de o fluxo de dados dirigir o relógio, agora as simulações iterar através de um conjunto pré-calculado de dia ou minutos timestamps. Os carimbos de data / hora são emitidos por MinuteSimulationClock e DailySimulationClock. E consumido pelo loop principal em transform (). We8217ve retired the datasid(N) and history APIs, replacing them with several methods on the BarData object: current(). history(). cantrade(). and isstale(). Old APIs will continue to work for now, but will issue deprecation warnings. You can now pass in an adjustments source to the DataPortal. and we will apply adjustments to the pricing data when looking backwards at data. Prices and volumes for execution and presented to the algorithm in data. current are the as-traded value of the asset. New Entry Points (1173 and 1178 ) In order to make it easier to use zipline we have updated the entry points for a backtest. The three supported ways to run a backtest are now: zipline. runalgo() zipline run zipline (IPython magic) Data Bundles (1173 and 1178 ) 1.0.0 introduces data bundles. Data bundles are groups of data that should be preloaded and used to run backtests later. This allows users to not need to to specify which tickers they are interested in each time they run an algorithm. This also allows us to cache the data between runs. By default, the quantopian-quandl bundle will be used which pulls data from Quantopian8217s mirror of the quandl WIKI dataset. New bundles may be registered with zipline. data. bundles. register() like: This function should retrieve the data it needs and then use the writers that have been passed to write that data to disc in a location that zipline can find later. This data can be used in backtests by passing the name as the - b --bundle argument to zipline run or as the bundle argument to zipline. runalgorithm() . For more information see Data Bundles for more information. String Support in Pipeline (1174 ) Added support for string data in Pipeline. zipline. pipeline. data. Column now accepts object as a dtype, which signifies that loaders for that column should emit windowed iterators over the experimental new LabelArray class. Several new Classifier methods have also been added for constructing Filter instances based on string operations. The new methods are: elementof is defined for all classifiers. The remaining methods are only defined for string-dtype classifiers. Enhancements Made the data loading classes have more consistent interfaces. This includes the equity bar writers, adjustment writer, and asset db writer. The new interface is that the resource to be written to is passed at construction time and the data to write is provided later to the write method as dataframes or some iterator of dataframes. This model allows us to pass these writer objects around as a resource for other classes and functions to consume (1109 and 1149 ). Added masking to zipline. pipeline. CustomFactor. Custom factors can now be passed a Filter upon instantiation. This tells the factor to only compute over stocks for which the filter returns True, rather than always computing over the entire universe of stocks. (1095 ) Added zipline. utils. cache. ExpiringCache. A cache which wraps entries in a zipline. utils. cache. CachedObject. which manages expiration of entries based on the dt supplied to the get method. (1130 ) Implemented zipline. pipeline. factors. RecarrayField. a new pipeline term designed to be the output type of a CustomFactor with multiple outputs. (1119 ) Added optional outputs parameter to zipline. pipeline. CustomFactor. Custom factors are now capable of computing and returning multiple outputs, each of which are themselves a Factor. (1119 ) Added support for string-dtype pipeline columns. Loaders for thse columns should produce instances of zipline. lib. labelarray. LabelArray when traversed. latest() on string columns produces a string-dtype zipline. pipeline. Classifier. (1174 ) Added several methods for converting Classifiers into Filters. The new methods are: - elementof() - startswith() - endswith() - hassubstring() - matches() elementof is defined for all classifiers. The remaining methods are only defined for strings. (1174 ) Fetcher has been moved from Quantopian internal code into Zipline (1105 ). Experimental Features Experimental features are subject to change. Added a new zipline. lib. labelarray. LabelArray class for efficiently representing and computing on string data with numpy. This class is conceptually similar to pandas. Categorical. in that it represents string arrays as arrays of indices into a (smaller) array of unique string values. (1174 ) Bug Fixes Highlights Added a new EarningsCalendar dataset for use in the Pipeline API. (905 ). AssetFinder speedups (830 and 817 ). Improved support for non-float dtypes in Pipeline. Most notably, we now support datetime64 and int64 dtypes for Factor. and BoundColumn. latest now returns a proper Filter object when the column is of dtype bool . Zipline now supports numpy 1.10, pandas 0.17, and scipy 0.16 (969 ). Batch transforms have been deprecated and will be removed in a future release. Using history is recommended as an alternative. Enhancements Adds a way for users to provide a context manager to use when executing the scheduled functions (including handledata ). This context manager will be passed the BarData object for the bar and will be used for the duration of all of the functions scheduled to run. This can be passed to TradingAlgorithm by the keyword argument createeventcontext (828 ). Added support for zipline. pipeline. factors. Factor instances with datetime64ns dtypes. (905 ) Added a new EarningsCalendar dataset for use in the Pipeline API. This dataset provides an abstract interface for adding earnings announcement data to a new algorithm. A pandas-based reference implementation for this dataset can be found in zipline. pipeline. loaders. earnings. and an experimental blaze-based implementation can be found in zipline. pipeline. loaders. blaze. earnings. (905 ). Added new built-in factors, zipline. pipeline. factors. BusinessDaysUntilNextEarnings and zipline. pipeline. factors. BusinessDaysSincePreviousEarnings. These factors use the new EarningsCalendar dataset. (905 ). Added isnan(). notnan() and isfinite() methods to zipline. pipeline. factors. Factor (861 ). Added zipline. pipeline. factors. Returns. a built-in factor which calculates the percent change in close price over the given windowlength. (884 ). Added a new built-in factor: AverageDollarVolume. (927 ). Added ExponentialWeightedMovingAverage and ExponentialWeightedMovingStdDev factors. (910 ). Allow DataSet classes to be subclassed where subclasses inherit all of the columns from the parent. These columns will be new sentinels so you can register them a custom loader (924 ). Added coerce() to coerce inputs from one type into another before passing them to the function (948 ). Added optionally() to wrap other preprocessor functions to explicitly allow None (947 ). Added ensuretimezone() to allow string arguments to get converted into datetime. tzinfo objects. This also allows tzinfo objects to be passed directly (947 ). Added two optional arguments, dataquerytime and dataquerytz to BlazeLoader and BlazeEarningsCalendarLoader. These arguments allow the user to specify some cutoff time for data when loading from the resource. For example, if I want to simulate executing my beforetradingstart function at 8:45 USEastern then I could pass datetime. time(8, 45) and USEastern to the loader. This means that data that is timestamped on or after 8:45 will not seen on that day in the simulation. The data will be made available on the next day (947 ). BoundColumn. latest now returns a Filter for columns of dtype bool (962 ). Added support for Factor instances with int64 dtype. Column now requires a missingvalue when dtype is integral. (962 ) It is also now possible to specify custom missingvalue values for float. datetime. and bool Pipeline terms. (962 ) Added auto-close support for equities. Any positions held in an equity that reaches its autoclosedate will be liquidated for cash according to the equity8217s last sale price. Furthermore, any open orders for that equity will be canceled. Both futures and equities are now auto-closed on the morning of their autoclosedate. immediately prior to beforetradingstart. (982 ) Experimental Features Experimental features are subject to change. Added support for parameterized Factor subclasses. Factors may specify params as a class-level attribute containing a tuple of parameter names. These values are then accepted by the constructor and forwarded by name to the factor8217s compute function. This API is experimental, and may change in future releases. Bug Fixes Fixes an issue that would cause the dailyminutely method caching to change the len of a SIDData object. This would cause us to think that the object was not empty even when it was (826 ). Fixes an error raised in calculating beta when benchmark data were sparse. Instead numpy. nan is returned (859 ). Fixed an issue pickling sentinel() objects (872 ). Fixed spurious warnings on first download of treasury data (:issue 922 ). Corrected the error messages for setcommission() and setslippage() when used outside of the initialize function. These errors called the functions override instead of set. This also renamed the exception types raised from OverrideSlippagePostInit and OverrideCommissionPostInit to SetSlippagePostInit and SetCommissionPostInit (923 ). Fixed an issue in the CLI that would cause assets to be added twice. This would map the same symbol to two different sids (942 ). Fixed an issue where the PerformancePeriod incorrectly reported the totalpositionsvalue when creating a Account (950 ). Fixed issues around KeyErrors coming from history and BarData on 32-bit python, where Assets did not compare properly with int64s (959 ). Fixed a bug where boolean operators were not properly implemented on Filter (991 ). Installation of zipline no longer downgrades numpy to 1.9.2 silently and unconditionally (969 ). Performance Speeds up lookupsymbol() by adding an extension, AssetFinderCachedEquities. that loads equities into dictionaries and then directs lookupsymbol() to these dictionaries to find matching equities (830 ). Improved performance of lookupsymbol() by performing batched queries. (817 ). Maintenance and Refactorings Asset databases now contain version information to ensure compatibility with current Zipline version (815 ). Upgrade requests version to 2.9.1 (2ee40db ) Upgrade logbook version to 0.12.5 (11465d9 ). Upgrade Cython version to 0.23.4 (5f49fa2 ). Makes zipline install requirements more flexible (825 ). Use versioneer to manage the project version and setup. py version (829 ). Fixed coveralls integration on travis build (840 ). Fixed conda build, which now uses git source as its source and reads requirements using setup. py, instead of copying them and letting them get out of sync (937 ). Require setuptools gt 18.0 (951 ). Documentation Document the release process for developers (835 ). Added reference docs for the Pipeline API. (864 ). Added reference docs for Asset Metadata APIs. (864 ). Generated documentation now includes links to source code for many classes and functions. (864 ). Added platform-specific documentation describing how to find binary dependencies. (883 ). Miscellaneous Added a showgraph() method to render a Pipeline as an image (836 ). Adds subtest() decorator for creating subtests without noseparameterized. expand() which bloats the test output (833 ). Limits timer report in test output to 15 longest tests (838 ). Treasury and benchmark downloads will now wait up to an hour to download again if data returned from a remote source does not extend to the date expected. (841 ). Added a tool to downgrade the assets db to previous versions (941 ). Release 0.8.3 Highlights New documentation system with a new website at zipline. io Major performance enhancements. Dynamic history. New user defined method: beforetradingstart . New api function: schedulefunction() . New api function: getenvironment() . New api function: setmaxleverage() . New api function: setdonotorderlist() . Pipeline API. Support for trading futures. Enhancements Account object: Adds an account object to context to track information about the trading account. Example: Returns the settled cash value that is stored on the account object. This value is updated accordingly as the algorithm is run (396 ). HistoryContainer can now grow dynamically. Calls to history() will now be able to increase the size or change the shape of the history container to be able to service the call. addhistory() now acts as a preformance hint to pre-allocate sufficient space in the container. This change is backwards compatible with history. all existing algorithms should continue to work as intended (412 ). Simple transforms ported from quantopian and use history. SIDData now has methods for: These methods, except for returns. accept a number of days. If you are running with minute data, then this will calculate the number of minutes in those days, accounting for early closes and the current time and apply the transform over the set of minutes. returns takes no parameters and will return the daily returns of the given asset. Example: New fields in Performance Period. Performance Period has new fields accessible in return value of todict. - gross leverage - net leverage - short exposure - long exposure - shorts count - longs count (464 ). Allow orderpercent() to work with various market values (by Jeremiah Lowin). Currently, orderpercent() and ordertargetpercent() both operate as a percentage of self. portfolio. portfoliovalue. This PR lets them operate as percentages of other important MVs. Also adds context. getmarketvalue(). which enables this functionality. For example: Command line option to for printing algo to stdout (by Andrea D8217Amore) (545 ). New user defined function beforetradingstart. This function can be overridden by the user to be called once before the market opens every day (389 ). New api function schedulefunction(). This function allows the user to schedule a function to be called based on more complicated rules about the date and time. For example, call the function 15 minutes before market close respecting early closes (411 ). New api function setdonotorderlist(). This function accepts a list of assets and adds a trading guard that prevents the algorithm from trading them. Adds a list point in time list of leveraged ETFs that people may want to mark as 8216do not trade8217 (478 ). Adds a class for representing securities. order() and other order functions now require an instance of Security instead of an int or string (520 ). Generalize the Security class to Asset. This is in preperation of adding support for other asset types (535 ). New api function getenvironment(). This function by default returns the string zipline. This is used so that algorithms can have different behavior on Quantopian and local zipline (384 ). Extends getenvironment() to expose more of the environment to the algorithm. The function now accepts an argument that is the field to return. By default, this is platform which returns the old value of zipline but the following new fields can be requested: arena. Is this live trading or backtesting datafrequency. Is this minute mode or daily mode start. Simulation start date. end. Simulation end date. capitalbase. The starting capital for the simulation. platform. The platform that the algorithm is running on. . A dictionary containing all of these fields. New api function setmaxleveraged(). This method adds a trading guard that prevents your algorithm from over leveraging itself (552 ). Experimental Features Experimental features are subject to change. Adds new Pipeline API. The pipeline API is a high-level declarative API for representing trailing window computations on large datasets (630 ). Adds support for futures trading (637 ). Adds Pipeline loader for blaze expressions. This allows users to pull data from any format blaze understands and use it in the Pipeline API. (775 ). Bug Fixes Fix a bug where the reported returns could sharply dip for random periods of time (378 ). Fix a bug that prevented debuggers from resolving the algorithm file (431 ). Properly forward arguments to user defined initialize function (687 ). Fix a bug that would cause treasury data to be redownloaded every backtest between midnight EST and the time when the treasury data was available (793 ). Fix a bug that would cause the user defined analyze function to not be called if it was passed as a keyword argument to TradingAlgorithm (819 ). Performance Major performance enhancements to history (by Dale Jung) (488 ). Maintenance and Refactorings Remove simple transform code. These are available as methods of SIDData (550 ). Highlights Command line interface to run algorithms directly. IPython Magic zipline that runs algorithm defined in an IPython notebook cell. API methods for building safeguards against runaway ordering and undesired short positions. New history() function to get a moving DataFrame of past market data (replaces BatchTransform). A new beginner tutorial . Enhancements CLI: Adds a CLI and IPython magic for zipline. Example: Grabs the data from yahoo finance, runs the file dualmovingavg. py (and looks for dualmovingavganalyze. py which, if found, will be executed after the algorithm has been run), and outputs the perf DataFrame to dma. pickle (325 ). IPython magic command (at the top of an IPython notebook cell). Example: Does the same as above except instead of executing the file looks for the algorithm in the cell and instead of outputting the perf df to a file, creates a variable in the namespace called perf (325 ). Adds Trading Controls to the algorithm API. The following functions are now available on TradingAlgorithm and for algo scripts: setmaxordersize(self, sidNone, maxsharesNone, maxnotionalNone) Set a limit on the absolute magnitude, in shares andor total dollar value, of any single order placed by this algorithm for a given sid. If sid is None, then the rule is applied to any order placed by the algorithm. Example: setmaxpositionsize(self, sidNone, maxsharesNone, maxnotionalNone) - Set a limit on the absolute magnitude, in either shares or dollar value, of any position held by the algorithm for a given sid. If sid is None, then the rule is applied to any position held by the algorithm. Example: setlongonly(self) Set a rule specifying that the algorithm may not hold short positions. Example: Adds an allapimethods classmethod on TradingAlgorithm that returns a list of all TradingAlgorithm API methods (333 ). Expanded record() functionality for dynamic naming. The record() function can now take positional args before the kwargs. All original usage and functionality is the same, but now these extra usages will work: The requirements are simply that the poritional args occur only before the kwargs (355 ). history() has been ported from Quantopian to Zipline and provides moving window of market data. history() replaces BatchTransform. It is faster, works for minute level data and has a superior interface. To use it, call addhistory() inside of initialize() and then receive a pandas DataFrame by calling history() from inside handledata(). Check out the tutorial and an example. (345 and 357 ). history() now supports 1m window lengths (345 ). Bug Fixes Fix alignment of trading days and open and closes in trading environment (331 ). RollingPanel fix when addingdropping new fields (349 ). Performance Maintenance and Refactorings Removed undocumented and untested HDF5 and CSV data sources (267 ). Refactor simparams (352 ). Refactoring of history (340 ). The following dependencies have been updated (zipline might work with other versions too): Highlights Major fixes to risk calculations, see Bug Fixes section. Port of history() function, see Enhancements section Start of support for Quantopian algorithm script-syntax, see ENH section. conda package manager support, see Build section. Enhancements Always process new orders i. e. on bars where handledata isn8217t called, but there is 8216clock8217 data e. g. a consistent benchmark, process orders. Empty positions are now filtered from the portfolio container. To help prevent algorithms from operating on positions that are not in the existing universe of stocks. Formerly, iterating over positions would return positions for stocks which had zero shares held. (Where an explicit check in algorithm code for pos. amount 0 could prevent from using a non-existent position.) Add trading calendar for BMFampBovespa. Add beginning of algo script support. Starts on the path of parity with the script syntax in Quantopian8217s IDE on quantopian Example: Add HDF5 and CSV sources. Limit handledata to times with market data. To prevent cases where custom data types had unaligned timestamps, only call handledata when market data passes through. Custom data that comes before market data will still update the data bar. But the handling of that data will only be done when there is actionable market data. Extended commission PerShare method to allow a minimum cost per trade. Add symbol api function A symbol() lookup feature was added to Quantopian. By adding the same API function to zipline we can make copyamppasting of a Zipline algo to Quantopian easier. Add simulated random trade source. Added a new data source that emits events with certain user-specified frequency (minute or daily). This allows users to backtest and debug an algorithm in minute mode to provide a cleaner path towards Quantopian. Remove dependency on benchmark for trading day calendar. Instead of the benchmarks8217 index, the trading calendar is now used to populate the environment8217s trading days. Remove extradate field, since unlike the benchmarks list, the trading calendar can generate future dates, so dates for current day trading do not need to be appended. Motivations: The source for the open and closeearly close calendar and the trading day calendar is now the same, which should help prevent potential issues due to misalignment. Allows configurations where the benchmark is provided as a generator based data source to need to supply a second benchmark list just to populate dates. Port history() API method from Quantopian. Opens the core of the history() function that was previously only available on the Quantopian platform. The history method is analoguous to the batchtransform functiondecorator, but with a hopefully more precise specification of the frequency and period of the previous bar data that is captured. Example usage: N. B. this version of history lacks the backfilling capability that allows the return a full DataFrame on the first bar. Bug Fixes Adjust benchmark events to match market hours (241 ). Previously benchmark events were emitted at 0:00 on the day the benchmark related to: in 8216minute8217 emission mode this meant that the benchmarks were emitted before any intra-day trades were processed. Ensure perf stats are generated for all days When running with minutely emissions the simulator would report to the user that it simulated 8216n - 18217 days (where n is the number of days specified in the simulation params). Now the correct number of trading days are reported as being simulated. Fix repr for cumulative risk metrics. The repr for RiskMetricsCumulative was referring to an older structure of the class, causing an exception when printed. Also, now prints the last values in the metrics DataFrame. Prevent minute emission from crashing at end of available data. The next day calculation was causing an error when a minute emission algorithm reached the end of available data. Instead of a generic exception when available data is reached, raise and catch a named exception so that the tradesimulation loop can skip over, since the next market close is not needed at the end. Fix pandas indexing in trading calendar. This could alternatively be filed under Performance. Index using loc instead of the inefficient index-ing of day, then time. Prevent crash in vwap transform due to non-existent member. The WrongDataForTransform was referencing a self. fields member, which did not exist. Add a self. fields member set to price and volume and use it to iterate over during the check. Fix max drawdown calculation. The input into max drawdown was incorrect, causing the bad results. i. e. the compoundedlogreturns were not values representative of the algorithms total return at a given time, though calculatemaxdrawdown was treating the values as if they were. Instead, the algorithmperiodreturns series is now used, which does provide the total return. Fix cost basis calculation. Cost basis calculation now takes direction of txn into account. Closing a long position or covering a short shouldn8217t affect the cost basis. Fix floating point error in order(). Where order amounts that were near an integer could accidentally be floored or ceilinged (depending on being postive or negative) to the wrong integer. por exemplo. an amount stored internally as -27.99999 was converted to -27 instead of -28. Update perf period state when positions are changed by splits. Otherwise, self. positionamounts will be out of sync with position. amount, etc. Fix misalignment of downside series calc when using exact dates. An oddity that was exposed while working on making the return series passed to the risk module more exact, the series comparison between the returns and mean returns was unbalanced, because the mean returns were not masked down to the downside data points however, in most, if not all cases this was papered over by the call to. valid() which was removed in this change set. Check that self. logger exists before using it. self. logger is initialized as None and there is no guarantee that users have set it, so check that it exists before trying to pass messages to it. Prevent out of sync market closes in performance tracker. In situations where the performance tracker has been reset or patched to handle state juggling with warming up live data, the marketclose member of the performance tracker could end up out of sync with the current algo time as determined by the performance tracker. The symptom was dividends never triggering, because the end of day checks would not match the current time. Fix by having the tradesimulation loop be responsible, in minuteminute mode, for advancing the market close and passing that value to the performance tracker, instead of having the market close advanced by the performance tracker as well. Fix numerous cumulative and period risk calculations. The calculations that are expected to change are: cumulative. beta cumulative. alpha cumulative. information cumulative. sharpe period. sortino How Risk Calculations Are Changing Risk Fixes for Both Period and Cumulative Use sample instead of population for standard deviation. Add a rounding factor, so that if the two values are close for a given dt, that they do not count as a downside value, which would throw off the denominator of the standard deviation of the downside diffs. Standard Deviation Type Across the board the standard deviation has been standardized to using a 8216sample8217 calculation, whereas before cumulative risk was mostly using 8216population8217. Using ddof1 with np. std calculates as if the values are a sample. Cumulative Risk Fixes Use the daily algorithm returns and benchmarks instead of annualized mean returns. Use sample instead of population with standard deviation. The volatility is an input to other calculations so this change affects Sharpe and Information ratio calculations. The benchmark returns input is changed from annualized benchmark returns to the annualized mean returns. The benchmark returns input is changed from annualized benchmark returns to the annualized mean returns. Period Risk Fixes Now uses the downside risk of the daily return vs. the mean algorithm returns for the minimum acceptable return instead of the treasury return. The above required adding the calculation of the mean algorithm returns for period risk. Also, uses algorithmperiodreturns and tresauryperiodreturn as the cumulative Sortino does, instead of using algorithm returns for both inputs into the Sortino calculation. Performance Removed aliasdt transform in favor of property on SIDData. Adding a copy of the Event8217s dt field as datetime via the aliasdt generator, so that the API was forgiving and allowed both datetime and dt on a SIDData object, was creating noticeable overhead, even on an noop algorithms. Instead of incurring the cost of copying the datetime value and assigning it to the Event object on every event that is passed through the system, add a property to SIDData which acts as an alias datetime to dt. Eventually support for datafoo. datetime may be removed, and could be considered deprecated. Remove the drop of 8216null return8217 from cumulative returns. The check of existence of the null return key, and the drop of said return on every single bar was adding unneeded CPU time when an algorithm was run with minute emissions. Instead, add the 0.0 return with an index of the trading day before the start date. The removal of the null return was mainly in place so that the period calculation was not crashing on a non-date index value with the index as a date, the period return can also approximate volatility (even though the that volatility has high noise-to-signal strength because it uses only two values as an input.) Maintenance and Refactorings Allow simparams to provide data frequency for the algorithm. In the case that datafrequency of the algorithm is None, allow the simparams to provide the datafrequency . Also, defer to the algorithms data frequency, if provided. Added support for building and releasing via conda For those who prefer building with conda. pydata. org to compiling locally with pip. The following should install Zipline on many systems. RTLSDR Scanner Thank you for your work. Your aplication runs perfectly on my windows 7 32bit. Only one thing, in the installation instructions link at the windows instructions after: In the same way download pyrtlsdr and extract it, then run the command setup. py from the extracted folder. I think there should be a link pointing RTLSDR-Scanner package, because the next instruction is run rtlsdrscan. py Submitted by Al on Tue, 04022013 - 20:14 Thanks for the feedback, everything helps Ive updated the installation instructions to make things clearer. Submitted by Bill on Sun, 06302013 - 17:31 Any chance to get an already compiled. exe for Windows No chance for me to do such monster install process. Obrigado. Hi Bill, DVB-T has a high spectral density so Im not sure that youd see that much difference with increased dwell times. Its more useful on FM where a higher dwell will allow you to see the wider response of a signal. If you click on Continuous Update the graph will be updated with each sub-scan but this can really slow down your machine on large scans due to the amount of points plotted, I hope to fix this problem soon Submitted by Gisle Vanem on Thu, 08292013 - 20:38 That 32-bit. exe file required a Python package () named mulitarray. Never heard of it and neither did pip. exe. So I simply ran python rtlsdrscan. py and it worked well but slow. Submitted by Pascal on Tue, 07232013 - 11:09 Dear Alan, Another quick note to throw some ideas for improvement on this already great before I forget. but these remarks are called for a constructive purpose and not anything imperative. To see if it would be possible to add a vertical line marker in the stop mode to better locate the frequency or maybe a cross on the blue line of the spectrum. The frequency and the cursor would be visible at the top of the window. would be better if the text just above the spectrum peak examines the place. Very good for the scan range at the bottom with the start frequency and stop frequency. However, you may also provide input to the center frequency and span of bandwidth for research: this method may be faster for the user. It would be really nice to have the adjustment of the gain in the low spectrum under the direct access without going through the menu. Another idea would be to put four windows side by side to see for example the occupation of four frequency ranges at the same time with a single key. course of the scanning would be a window to another in a cyclic manner without stop with a tidal of the screen at each scanning. Window 1 Window 2 Window 3 Window 4 Window 1, etc. That is all for now. Excellent work and soon to test a new Windows version, 73s of F1MIJ Submitted by Al on Thu, 07252013 - 18:16 Hello again, Unfortunately adding lines to the plot causes a complete re-draw of the graph which slows things down massively. Ill try and code an overlay sometime so I can implement features like this. Ill add centre frequencybandwidth and gain controls to the toolbar soon. I like the idea of separate windows for different ranges. For the moment if you have more than one dongle you could start the scanner multiple times, once for each dongle. Submitted by Pascal on Tue, 07232013 - 15:27 HELLO ALAN I HAVE MANY SPEAK YOUR SOFTWARE WITH FRIENDS AND OTHER APPLICATIONS OF SPOILER WAS REFERRED TO: THAT OF AN OPTION TO OFFSET FREQUENCY FOR BAR X BOTTOM TO ALLOW THE USE OF A CONVERTER HF OR BY MY SHF FRIENDS HANDY. GOOD TO YOU, PASCAL Submitted by Tony Abbey on Thu, 10242013 - 18:50 Thanks for the reply. However, I was also being a bit stupid - I hadnt yet downloaded your full scanner software. I have now done that with git clone git:githubEarToEarOakRTLSDR-Scanner. git In the src files I found rtlsdrscandiag. py which reports no library problems. Then from the same src directory (RTLSDR-Scannersrc) I ran python rtlsdrscan. py but get warnings and error messages: usrlibpymodulespython2.7matplotlibinit. py:923: UserWarning: This call to matplotlib. use() has no effect because the the backend has already been chosen usrlibpymodulespython2.7matplotlibinit. py:923: UserWarning: This call to matplotlib. use() has no effect because the the backend has already been chosen matplotlib. use() must be called before pylab, matplotlib. pyplot, or matplotlib. backends is imported for the first time. if warn: warnings. warn(useerrormsg) RTLSDR Scanner Detached kernel driver Found Elonics E4000 tuner Traceback (most recent call last): File rtlsdrscan. py, line 84, in FrameMain(RTLSDR Scanner, pool) File homepiRTLSDR-Scannersrcmainwindow. py, line 128, in init self. devices getdevices(self. settings. devices) File homepiRTLSDR-Scannersrcdevices. py, line 69, in getdevices device. gains sdr. validgainsdb AttributeError: RtlSdr object has no attribute validgainsdb Reattaching kernel driver failed AttributeError: RtlSdr object has no attribute validgainsdb Reattaching kernel driver failed Now, I dont know whether I should be doing some sort of install, but I realise this code was probably a multi-platform installer, and not fully relevant to linux. Seems python is finding things correctly, and as I posted previously, the waterfall code in the pyrtlsdr directory works. Im sorry if I am not fully understanding what to do - I realise you have been making it all as easy as possible for a variety of users. It would be nice to be able to turn the Raspberry Pi into a cheap spectrum analyser, so I hope its got enough power. best regards Tony Hi Al Thank you for the update - I did the pull (note - also I need to use sudo python setup. py install - so I guess my python isnt set up fully) I ran RTLSDR-Scannersrc. rtlsdrscan. py from a terminal window on the LXDE desktop screen - got the window up and started a scan, but got an error at first which looks like it was related to Pi resources (threading - cant show it you now). So I tried shutting down LXDE and running from SSH - fantastic - got lovely display on my Macbook. Then tried desktop again and it worked. Well done - the display is beautiful Have achieved what I wanted - a low cost spectrum analyser with the Pi. Just need to speed it all up a bit - I guess that needs experiments with FFT width and dwell times. Thanks again Tony Submitted by Al on Wed, 10302013 - 16:34 Glad to hear you got it working. Not sure what the threading error was but when I get time Ill try it on the Pi. The scan will speed up if you reduce the dwell and FFTvalues, but its a shame to reduce them much below the defaults. The scanner spends most of its time performing Fast Fourier Transforms. on desktop systems each FFT is performed on a sperate core but as the Pi has only one processor only one process is run at a time. The other option with a Pi is to use it as a remote server with the dongle, you can then stream data to another machine. Start the server on the Pi using: rtltcl - a ltip address of the Pigt Submitted by Takis on Thu, 10242013 - 23:47 Hey excellent software. So i run the installer, and then I have to connect my tuner to receive So simply It would be great if you can create a GNU radio windows installer. I tried 2 times to install, but i had difficulties. Submitted by Al on Fri, 10252013 - 23:51 You can download a Live DVD of GNU Radio using a BitTorrent client (Torrent worked for me). Either create a DVD from the image and boot your computer from this, or try it in a virtual machine (VirtualBox for example), although this is more complex.

No comments:

Post a Comment