Friday 27 October 2017

Moving Media Pylab


Spyder - l'IDE Python Mon 16 settembre 2013 Hans Fangohr. Università di Southampton, UK 2013 Spyder si è sviluppato in uno strumento abbastanza maturo e molto produttivo Qui provo a fornire un tutorial. Questa documentazione è motivata da corsi di formazione in Python e modellazione computazionale per gli studenti presso l'Università di Southampton (vedi nota storica per maggiori dettagli). Questo blog è stato integrato nel Spyder come il Tutorial. Una volta Spyder è iniziata, la versione più aggiornata di questo tutorial si trova sotto Aiuto - gt Spyder tutorial. Ottenere il file ciao mondo nella finestra dell'editor Spyder da entrambe Scarica hello. py e salvare come hello. py. (Si scarica il file facendo clic destro sul link nel browser, quindi selezionare Salva oggetto con nome o Salva Scarica come), e quindi aprire il hello. py file mediante il menu File, quindi selezionare Apri. Esprimiamo questo come File - gt Apri in breve. cliccare su hello. py per vedere il codice sorgente nel browser web, quindi copiare il codice intero Passare alla finestra dell'editor in spyder e incollare il codice. Quindi salvare il file come hello. py. Per eseguire il programma, selezionare Esegui - gt Run (o premere F5), e confermare le impostazioni di esecuzione, se necessario. Si dovrebbe vedere un output come: o (il percorso particolare dipenderà da dove avete salvato il file, ma questa è inserita da Spyder automaticamente): Se è così, allora avete appena eseguire il vostro primo programma Python - ben fatto. Prima di procedere, si prega di La console IPython può fare un po 'di più rispetto alla console standard di Python, e si consiglia di utilizzare come la console di default qui. Nella sessione interprete IPython che abbiamo appena iniziato, è possibile utilizzare Run-gtRun (come in precedenza) per eseguire hello. py e si dovrebbe vedere: Python legge il file riga per riga, ignorando i commenti quando si incontra la parola chiave def, è sa che una funzione è definita in questo e il prossimo (una o più) linee. Nel file hello. py, Python crea così un oggetto funzione con il nome ciao. Tutte le linee frastagliate seguenti def ciao (): appartengono al corpo della funzione. Notare che l'oggetto funzione viene appena creato a questo punto nel file, ma la funzione non è ancora chiamato (cioè non eseguito). quando Python si imbatte comandi (diversi def. e poche altre parole chiave) che sono scritti nella colonna più a sinistra, eseguirà questi immediatamente. Nel file hello. py questa è solo la linea di lettura ciao (), che sarà effettivamente chiamare (vale a dire l'esecuzione) la funzione con il nome ciao. Se si rimuove la linea di ciao () dal programma ed eseguire di nuovo l'intero file (premendo F5 o selezionando Run Run - gt), non verrà stampato (perché la funzione ciao è definita, ma non ha chiamato, cioè non eseguito) . Ora si dovrebbe sapere come eseguire un programma Python che si ha nella finestra dell'editor in Spyder utilizzando la console di Python, e il più sofisticato Console IPython. Se si sta appena iniziando a imparare Python, questo è probabilmente un buon punto per tornare al corso libro di testo e guardare gli esempi più fondamentale. La sezione successiva fornisce informazioni più dettagliate come è possibile eseguire parti del codice nell'editor nella console Python, e quindi aggiornare parti dei vostri definizioni nell'editor. Questa è una tecnica più avanzata, ma può essere molto utile. (Si può essere interessati anche la possibilità di eseguire pezzi (cd quotcellsquot) di codice che sono separati da delimitatori -. Vedere Collegamenti per le funzioni utili) Una volta eseguito il programma hello. py, l'oggetto ciao funzione è definita e conosciuto al prompt di Python. Possiamo quindi chiamare la funzione dal prompt di Python:. Chiamare la funzione ciao () dal Python pronta, cioè tipo ciao () nella finestra Python Shell (gli spettacoli prompt di Python come gtgtgt o come in se usiamo la sessione IPython dove il punto interrogativo può essere un qualsiasi numero intero positivo.), e premere il tasto Invio. Si dovrebbe trovare che la funzione ciao () viene eseguito di nuovo, vale a dire Ciao mondo viene stampato di nuovo. La vostra chiamata di funzione in Python richiedere insieme con l'output dovrebbe essere simile a questo: si può vedere come questo si differenzia da eseguire di nuovo l'intero programma Quando eseguiamo l'intero programma (premendo F5), Python passa attraverso il file, crea la funzione ciao oggetto (ignorando l'oggetto precedente), raggiunge il programma principale e chiama la funzione. Quando chiamiamo ciao () dal prompt di Python, si limita a chiamare gli oggetti la funzione ciao che è stata definita nella console (I) Python quando abbiamo eseguito l'intero file hello. py in precedenza (premendo F5). Questo diventerà più chiara nel corso del tempo e anche quando lavoriamo con esempi leggermente più grandi. Si consiglia di tornare a questa esercitazione in una fase un po 'più tardi. Python fornisce una funzione che consente di visualizzare tutti gli oggetti conosciuti (nello spazio dei nomi corrente). Si chiama dir (). quando si digita dir () al prompt, si ottiene un elenco di oggetti noti. Ignorare tutto inizia con una sottolineatura per ora. Riesci a vedere ciao nella lista (Se si ottiene una lunga lista di oggetti definiti, quindi Spyder può aver fatto alcune importazioni convenienza per voi già di affrontare questo si consiglia di:. Quindi eseguire dir () come suggerito sopra.) Una volta che un oggetto è visibile nello spazio nome attuale (come è ciao in questo esempio), possiamo utilizzare la funzione di aiuto come segue per imparare a questo proposito: Tipo di aiuto (ciao) al prompt di Python, si dovrebbe vedere un output come questo: dove viene Python prendere le informazioni da parte di essa (come il numero di argomenti di input e nomi di tali variabili qui non abbiamo argomenti di input) Python può trovare attraverso l'ispezione dei suoi oggetti, informazioni aggiuntive viene dalla stringa di documentazione prevista per l'oggetto funzione ciao. La stringa di documentazione è la prima stringa immediatamente al di sotto della linea def ciao ():. L'ambiente Spyder offre anche un pannello in alto a destra (di default), che è l'ispettore oggetto. Se si digita ciao nella linea vuota nella finestra oggetto di ispezione, fornirà anche la stringa di aiuto. Nella finestra Editor, modificare la funzione ciao in modo che stampi Good Bye, piuttosto che mondo Ciao mondo. Premere F5 (per eseguire l'intero programma) e verificare che l'output del programma è ora: Che cosa è successo quando si è premuto F5 è questo: Python è passato attraverso il file hello. py e ha creato un nuovo oggetto funzione ciao (ignorando la funzione oggetto ciao avevamo definito in precedenza) e quindi eseguita la funzione. Abbiamo bisogno di iniziare con uno stato ben definito. Per fare questo, si prega di cambiare la funzione ciao () di nuovo in modo che stampi Ciao Mondo (ossia utilizzare il file hello. py originale), quindi premere F5 per eseguire l'intero programma e verificare che la stampa Ciao Mondo. Chiamare la funzione ciao () dal prompt dei comandi (come descritto nella chiamata di funzione di oggetti esistenti dalla riga di comando). Si dovrebbe vedere Ciao mondo stampato. Ora cambiare la definizione della funzione in modo che sarebbe stampare Laters mondo. e salvare il file (ma non eseguire il programma, vale a dire NON premere F5 ancora). Chiamare la funzione ciao () dal prompt dei comandi di nuovo. Si dovrebbe trovare che il testo stampato si legge Ciao Mondo. come qui Perché è così perché l'oggetto funzione ciao nel l'interprete Python è quello vecchio che stampa Ciao Mondo. Finora, abbiamo cambiato il file hello. py (e sostituito Ciao Mondo in là con Laters mondiale) nell'editor, ma questo non ha influenzato gli oggetti che sono stati precedentemente creati in Python. Qui ci sono due possibilità per utilizzare la nostra versione modificata della funzione ciao: Opzione 1: eseguire di nuovo l'intero file hello. py premendo F5: questo crea un nuovo oggetto funzione ciao (e sostituisce il vecchio). Si dovrebbe trovare che se si preme F5, e quindi chiamare ciao () al prompt, il nuovo testo Laters mondiale viene stampato. Opzione 2: selezionare la regione è stato modificato (in questo caso l'intera funzione ciao a partire dalla linea def ciao ():... Verso il basso per tornare Nessuno e quindi selezionare Esegui - gt Run selezione Questo aggiornerà l'oggetto ciao nell'interprete senza dover eseguire l'intero file hello. py:. Se ora digitiamo ciao () vediamo la risposta di aggiornamento: la possibilità di eseguire parti del codice per aggiornare alcuni oggetti in l'interprete (nell'esempio di cui sopra, abbiamo aggiornato la funzione oggetto ciao), è di grande utilità nello sviluppo e il debug di codici più complessi, e durante la creazione objectsdata nel tempo interprete sessione di ripresa. Per esempio, modificando solo le funzioni (o classesobjects, ecc) che stiamo effettivamente sviluppando, noi può continuare a ri-utilizzando le strutture di dati, ecc che sono definiti nella sessione interprete. per insegnare la programmazione Python e la modellazione computazionale, si consiglia di (i) utilizzare IPython al posto del normale interprete Python e (ii) non utilizzare le importazioni di convenienza. Questo accetta IPython come lo standard de-facto e aiuta a capire meglio gli spazi dei nomi. Spyder cerca di aiutare gli utenti più avanzati per l'importazione di un numero di moduli nello spazio nome principale. Scientific nel prompt dei comandi per vedere i dettagli. Questo comportamento potrebbe cambiare nelle future versioni Spyder. Mentre queste importazioni di alimentari sono molto utili per i programmatori più esperti, possono essere fonte di confusione (se non fuorvianti) per i principianti. Si consiglia quindi di annullare tali importazioni per soddisfare le nostre esigenze schema di cui sopra e per (i) passare a una console IPython. e (ii) il comando di reset per ripristinare lo spazio dei nomi. Entrambi i passaggi sono spiegati in maggior dettaglio nella sezione successiva. Nella finestra della console (in basso a destra per impostazione predefinita), si vede un messaggio predefinito con tre maggiore di segni, cioè gtgtgt. Questo dimostra che stiamo utilizzando la console - fondamentalmente una normale sessione di Python interprete (con alcune funzionalità aggiunte dalla Spyder). Invece, vorremmo usare una shell interattiva di Python, breve IPython dal progetto ipython. Per fare questo, selezionare interpreti - gt Aprire una console IPython. Si dovrebbe vedere nella finestra consolse una nuova shell che appare, e la richiesta IPython In 1: deve essere visualizzato. Lo spazio dei nomi può essere cancellato in IPython utilizzando il comando di reset. Tipo di reset e premere Invio, quindi confermare con y: Ne parliamo un po 'oltre, ma si può saltare il seguente se non siete interessati: Dopo il rilascio del comando di reset, dovremmo avere solo pochi oggetti definiti nello spazio dei nomi di quella sessione . Possiamo elencare tutti loro con il comando dir (): Infine, se vi piace saltare la fase di conferma del comando di reset, l'uso può utilizzare ripristinare - f invece di reset. Oltre alla sintassi che viene applicata da Python, ci sono convenzioni supplementari per quanto riguarda il layout del codice sorgente, in particolare la Guida allo stile per il codice sorgente Python sa come quotPEP8quot. Un sacco di comportamento Spyder può essere configurato attraverso le sue preferenze. Dove questo si trova nel menu dipende dal vostro sistema operativo: In Windows e Linux, andare in Strumenti - gt Preferenze su Mac OS, vanno a Python - gt Preferenze andare in Preferenze - gt console IPython - gt di avvio e selezionare la casella di spunta accanto alla aprire una console IPython all'avvio. Quindi fare clic sul pulsante OK. La prossima volta che si avvia Spyder, mostrerà automaticamente la console IPython. Vai a Preferenze - gt Editor - gt Codice IntrospectionAnalysis e selezionare la casella di spunta accanto ad analisi Style (PEP8) Per evitare qualsiasi magia quando viene avviata la console, accedere a Preferenze - gt Console - gt Impostazioni avanzate - gt sostituzione PYTHONSTARTUP e selezionare lo script predefinito PYTHONSTARTUP (e riavviare Spyder). (Questa magia, tra le altre cose, viene eseguito il comando di divisione dal futuro di importazione.) Le impostazioni predefinite possono cambiare per questo nella prossima major release. Per evitare l'importazione di tutti gli oggetti da pylab e numpy nello spazio nome attuale nella console IPython, andare in Preferenze - gt console IPython - gt grafica e deselezionare la casella di spunta accanto alla caricare automaticamente i moduli Pylab e NumPy e anche deselezionare supporto Attiva. Le impostazioni predefinite possono cambiare per questo nella prossima major release. Attraverso Preferenze - gt console IPython - gt Impostazioni avanzate - gt Usa matematica simbolica possiamo attivare la modalità IPythons pitone simbolica. Questo permetterà di uscita sympy ben reso (stile lattice) e le importazioni anche alcuni oggetti sympy automaticamente quando la console IPython inizia, e riporta quello che ha fatto. Possiamo quindi utilizzare le variabili x. y. per esempio come questo: F5 esegue la corrente F9 tampone esegue il pezzo attualmente evidenziata di codice: questo è molto utile per aggiornare le definizioni di funzioni (ad esempio) nella sessione interprete senza dover eseguire l'intero file di nuovo CTRL ltRETURNgt esegue la cella corrente ( menù enty Run - gt cellulare Run). Una cella è definito come il codice tra due linee che iniziano con il tag concordato. SHIFT ltRETURNgt esegue la cella corrente e fa avanzare il cursore sulla cella successiva (voce di menu Esegui - gt cellulare Run e anticipo). Le cellule sono utili per eseguire un grande segmento filecode in unità più piccole. (E 'un po' come una cellula in un quaderno IPython, in quanto pezzi di codice può essere eseguito in modo indipendente.) ALT ltCURSOR UPgt sposta la linea di corrente fino. Se più linee sono evidenziate, vengono spostati insieme. ALTltCURSOR DOWNgt funziona linea corrispondentemente in movimento (s) verso il basso. clic destro su un functionmethod nella fonte, si apre una nuova finestra dell'editor che mostra la definizione di tale funzione. SHIFTCTRLALTM massimizza la finestra corrente (o modifica le dimensioni di nuovo al normale, se premuto in una finestra ingrandita) SHIFTCTRLF attiva la ricerca in tutti i file. Su Mac OS X: CMD aumenterà la dimensione del carattere nell'editor, CMD - diminuzione. Funziona anche nella console IPython. Il formato per l'esploratore oggetto tipo di carattere, la console Python, ecc può essere impostata singolarmente tramite Preferenze - gt Esplora oggetti ecc ho potuto trovare un modo di cambiare la dimensione del carattere in explorer variabile. CTRLSPACE autocompletes comandi, i nomi delle funzioni, i nomi delle variabili, metodi molto utili. CMD (su Mac OS X) e Ctrls (altrimenti) nella finestra di editor salva il file attualmente in fase di modifica. Questo costringe anche diversi triangoli nella colonna di sinistra dell'editor da aggiornare (altrimenti aggiornamento ogni 2 o 3 secondi per impostazione predefinita). CMD (su Mac OS X) e Ctrls (altrimenti) nella finestra della console IPython salva la sessione IPython corrente come un file HTML, comprese le figure che possono essere visualizzati in linea. Questo è utile come un modo rapido di registrare ciò che è stato fatto in una sessione. (Non è possibile caricare questo record salvato di nuovo alla sessione - se avete bisogno di funzionalità in questo modo, cercare il Notebook IPython.) CMDI (su Mac OS X) e CTRLi (altrimenti) quando premuto mentre il cursore si trova su un oggetto , apre la documentazione per l'oggetto nella finestra di ispezione oggetto. Queste sono le impostazioni che definiscono come viene eseguito il codice nell'editor se selezionare Esegui - gt Run o premere F5. Per impostazione predefinita, viene visualizzata la finestra delle impostazioni per la prima volta si cerca di eseguire un file. Se vogliamo cambiare le impostazioni in qualsiasi altro momento, possono essere trovati sotto Run - gt Configurare o premendo F6. Ci sono tre scelte per l'interprete di usare, di cui Ill discutere i primi due. Assumiamo che abbiamo un hello. py programma nell'editor che legge questo è il suggerimento di default, e anche in generale una buona scelta. Scegliere Esegui in Python corrente o IPython impostazione in Esegui - gt Configurare significa che quando l'esecuzione di hello. py è completato, siamo in grado di interagire con l'interprete in cui il programma ha funzionato, e siamo in grado di utilizzare la comoda IPython interprete per questo interprete (piuttosto che l'interprete Python di default). possiamo ispezionare e interagire con gli oggetti che l'esecuzione del nostro programma creata, come i e ciao (). Questo è generalmente molto utile per incrementale la codifica, testing e debugging: possiamo chiamare ciao () direttamente dal prompt interprete, e non avete bisogno di eseguire il tutto hello. py per questo (anche se si cambia la funzione ciao () abbiamo bisogno. eseguire il buffer, o almeno la definizione della funzione, per rendere la nuova versione di ciao () visibile l'interprete sia eseguendo l'intero buffer o tramite Run - gt Selezione RUN.) Tuttavia, eseguendo il codice nell'editor nel interprete corrente significa anche che il codice che esegue può vedere gli altri oggetti (globali) che sono stati definiti nella sessione interprete. Questa persistenza di oggetti è facilmente Forgotton e di solito non necessaria quando si lavora su piccoli programmi (anche se può essere di grande valore occasionalmente). Questi oggetti potrebbero provenire dal precedente esecuzione di codice, dal lavoro interattivo l'interprete, o dalle importazioni di convenienza, come da importazione pylab (Spyder può fare un po 'di tali importazioni di convenienza automaticamente). Questa visibilità degli oggetti nello spazio interprete nome globale per il codice eseguiamo può anche provocare la codifica degli errori se il codice si basa inavvertitamente su questi oggetti. Ecco un esempio: immaginiamo che corriamo il codice hello. py. Successivamente, la variabile i è noto nell'interprete come una variabile globale. abbiamo modificare l'origine hello. py e accidentalmente cancellare la linea i 42 eseguiamo il tampone contenente hello. py di nuovo. A questo punto, la chiamata di ciao (i) non mancherà, perché l'interprete ha un oggetto di nome che ho definito, anche se questo non è definito nella sorgente di hello. py. A questo punto, potremmo risparmiare hello. py e (falsamente) pensare che sarebbe eseguito correttamente. Tuttavia, l'esecuzione in una nuova sessione di interprete Python (o tramite Python hello. py. Dirlo) si tradurrebbe in un errore, perché non è definita. Il problema nasce dal fatto che il codice fa uso di un oggetto (qui i) senza creare esso. Questo riguarda anche l'importazione di moduli: se avessimo importato pylab al prompt IPython, allora il nostro programma vedrà che quando eseguito in questa sessione interprete IPython. Per sapere come possiamo controllare due volte che il nostro codice non dipende da tali oggetti esistenti, vedere Come raddoppiare controllare il codice viene eseguito correttamente quoton sua ownquot. Scegliere Esegui nel nuovo interprete Python dedicato sotto Run - gt Configurare inizierà un nuovo interprete Python ogni volta che il programma viene eseguito hello. py. Il principale vantaggio di questa modalità nel corso di esecuzione in Python corrente o IPython interprete è che possiamo essere certi che non ci siano oggetti globali definiti in questo interprete che provengono da debug e l'esecuzione ripetuta di nostro codice: ogni volta che esegue il codice nell'editor , l'interprete Python in cui il codice viene eseguito viene riavviato. Questa è una scelta sicura, ma offre meno flessibilità e non è possibile utilizzare l'interprete IPyton. Supponendo che avete scelto per il vostro codice da eseguire in Python corrente o IPython interprete. poi due opzioni per controllare che il nostro codice funziona da sola (cioè non dipende da variabili indefinite, moduli unimported e comandi, ecc) In alternativa, se si vuole rimanere con l'attuale interprete IPython, è possibile utilizzare IPythons ripristino magia comando che rimuove tutti gli oggetti (ad esempio i nell'esempio precedente) dallo spazio nome attuale, e quindi eseguire il codice nell'editor. Dopo aver completato un pezzo di codice, doppio controllo che esegue utilizzando in modo indipendente una delle opzioni di cui alla Come ricontrollare il codice viene eseguito correttamente quoton sua ownquot. Quando più file vengono aperti nell'editor, le corrispondenti schede nella parte superiore dell'area della finestra sono disposti in ordine alfabetico del nome del file da sinistra a destra. A sinistra delle schede, non vi è l'icona che mostra Sfoglia le schede se il mouse passa sopra di esso. E 'utile per passare a un particolare file direttamente, se molti file aperti. Le variabili di ambiente possono essere visualizzati dalla finestra della console (in basso a destra della finestra nel layout di default). Fare clic sull'icona Opzioni (il tooltip è Opzioni), quindi selezionare Variabili d'ambiente. Tutti personalizzazione salvati su disco può essere azzerato chiamando spyder dalla riga di comando con il --reset interruttore. cioè un comando come spyder --reset. Cliccando col tasto destro su array in Esplora variabile dà opzioni per tracciare e analizzare questi ulteriori. Facendo doppio click su un oggetto dizionario apre una nuova finestra che visualizza il dizionario bene. Presumibilmente non vi è altra possibilità nascosto per alcuni altri tipi di dati. Ci sono alcune convenzioni assunti per quanto riguarda le stringhe di documentazione scritta nel testo ristrutturato. Se seguiamo queste linee guida, si possono ottenere le stringhe di documentazione ben formattati in Spyder. Ad esempio, per ottenere la nostra funzione media () simile a questa in Esplora oggetti Spyder: Abbiamo bisogno di formattare la stringa di documentazione come segue Ciò che conta qui, è che la parola parametri vengono utilizzati, e sottolineati. La linea a. numero ci mostra che il tipo del parametro a è il numero. Nella riga successiva, che è rientrato, possiamo scrivere una spiegazione più estesa cosa questa variabile rappresenta, quali condizioni i tipi permessi devono soddisfare ecc Lo stesso per tutti i parametri, e anche per il valore restituito. Spesso è una buona idea per includere un esempio come mostrato. Attivazione della modalità di debug (Debug - gt Debug) inizia il debugger IPython (IPDB) nella console IPython. Questo è gestito come normale, ma la finestra di visualizzazione Editor evidenzia la riga che sta per essere eseguita, e l'esploratore variabile visualizza variabili nel contesto corrente del punto di esecuzione del programma. (Viene visualizzato solo variabili numeriche, cioè non oggetti funzione etc.) I comandi chiave all'interno del debugger IPython sono battute indivdual: S per Passo in istruzione corrente. Se si tratta di una chiamata di funzione, un passo in tale funzione. n passare alla dichiarazione successiva. Se l'istruzione corrente è una funzione, non un passo in quella funzione, ma eseguirlo completamente prima di restituire il controllo al prompt del debugger interattivo. R completare tutte le istruzioni nella funzione attuale e Ritorno da tale funzione, prima di restituire il controllo. p Stampa consente di visualizzare i valori delle variabili, per esempio p x stamperà il valore della variabile x. Si noti che al IPDB, è anche possibile modificare i valori di variabile. Ad esempio, per modificare un valiable x. si può dire IPDB gt x 42 e il debugger portare avanti con x essere vincolato a 42. È anche possibile chiamare funzioni, e fare molte altre cose. Per uscire dalla modalità di debug, è possibile digitare exit o selezionare dal menu di debug - gt Debug controllo - gt Exit Nella console IPython, si può chiamare il debug subito dopo l'eccezione è stata sollevata: questo si avvierà la modalità di debug IPython, e permette ispezione delle variabili locali nel punto in cui si è verificata l'eccezione come descritto sopra. Questo è molto più efficiente di aggiungere istruzioni di stampa per il codice di correre di nuovo. Se si utilizza questo, si consiglia inoltre di utilizzare i comandi su e giù che navigano il punto di controllo su e giù per lo stack. (Lo stack significa le funzioni che hanno chiamato la funzione di corrente verso il basso è la direzione opposta.) Supponendo che usiamo una console IPython con la versione GT 1.0.0, possiamo decidere se le figure create con matplotlibpylab mostreranno in linea. vale a dire all'interno della console IPython, o se devono apparire all'interno di una nuova finestra. Opzione 1 è conveniente per salvare un record della sessione interattiva (sezione Tasti di scelta rapida per le funzioni utili elenca una scorciatoia per salvare la console IPython in un file HTML). Opzione 2 permette di ingrandire in modo interattivo in figura, manipolarlo un po ', e salvare la cifra di diversi formati di file tramite il menu. Il comando per ottenere i dati di apparire in linea nella console IPython è in linea matplotlib. Il comando per ottenere figure appaiono in una propria finestra (che tecnicamente è una windown QT) è matplotlib qt. Le preferenze Spyder possono essere utilizzate per personalizzare il comportamento di default (in particolare Preferenze - gt IPython Console - gt grafica - gt Attiva supporto per passare alla linea stampa). Messaggi Recenti CategoriesRelease Notes 8 settembre 2016 Miglioramenti Aggiunge avanti compilare tabelle di checkpoint per il core loader fiammata. Questo permette il caricatore in modo più efficiente in avanti riempire i dati dalla tappatura la data in basso si deve cercare quando l'interrogazione dei dati. I posti di blocco devono avere nuovi delta applicati (1276). Aggiornato VagrantFile per includere tutti i requisiti dev e utilizzare una immagine più recente (1310). Consentire correlazioni e regressioni a essere calcolati tra i due fattori 2D facendo calcoli asset-saggio (1307). I filtri sono stati fatti windowsafe per impostazione predefinita. Ora possono essere passati come argomenti ad altri filtri, Fattori e Classificatori (1338). Aggiunto un parametro GroupBy opzionale di rango (). superiore(). e inferiore (). (1349). Aggiunti nuovi filtri gasdotti, ogni e qualsiasi. che prende un altro filtro e restituisce true se un bene prodotto un Vero per anyall giorni nei giorni precedenti windowlength (1358). Aggiunto nuovo filtro AtLeastN pipeline. che prende un altro filtro e un int N e restituisce true se un bene prodotto un vero su N o più giorni nei precedenti giorni windowlength (1367). Utilizzare empyrical libreria esterna per i calcoli di rischio. unifica Empyrical rischiano computi metrici tra pyfolio e zipline. Empyrical aggiunge opzioni annualizzazione personalizzate per i ritorni di frequenze personalizzati. (855) Aggiungi fattore Aroon. (1258) Aggiungere fattore oscillatore stocastico veloce. (1255) Aggiungi un Dockerfile. (1254) Nuovo calendario commerciale che supporta le sessioni che si estendono attraverso midnights, ad esempio 24 ore 06:01 sessioni PM-6:00PM per il trading dei futures. zipline. utils. tradingcalendar è ora sconsigliato. (1138) (1312) consentono affettare una singola colonna di un FactorFilterClassifier. (1267) Fornire fattore Ichimoku Cloud (1263) Consentire parametri di default a condizioni Pipeline. (1263) Fornire tasso del fattore di variazione percentuale. (1324) Fornire lineare ponderata movimento fattore medio. (1325) Aggiungi NotNullFilter. (1345) Consentire variazioni di capitale da definire con un valore obiettivo. (1337) Aggiungi fattore TrueRange. (1348) Aggiungere punto in ricerche di tempo per assets. db. (1361) Fai Cantrade a conoscenza dello scambio asset8217s. (1346) Aggiungi metodo downsample a tutti i termini calcolabili. (1394) Aggiungi QuantopianUSFuturesCalendar. (1414) abilitare la pubblicazione di versioni vecchie assets. db. (1430) Enable schedulefunction per il calendario Futures trading. (1442) Non consentire regressioni di lunghezza 1. (1466), Sperimentale aggiungere il supporto per comingled futuri e storia equità finestre, e consentire ad altri l'accesso ai dati futuro tramite il portale di dati. (1435) fattore di built-in (1432) Bug Fixes Modifiche AverageDollarVolume trattare mancante valori prossimi o di volume come 0. In precedenza, NaNs erano semplicemente scartato prima media, dando i restanti valori troppo peso (1309). Rimuovere tasso privo di rischio da calcolo Sharpe Ratio. Il rapporto è ora la media dei rendimenti risk adjusted oltre violatility dei rendimenti rettificati. (853) rapporto di Sortino restituirà calcolo anziché np. nan quando rendimenti richiesti sono uguali a zero. Il rapporto ora restituisce la media dei rendimenti risk adjusted sopra rischio di ribasso. Corretto API mislabeled convertendo Mar a downsiderisk. (747) il rischio di ribasso ora restituisce la radice quadrata della media dei quadrati di differenza al ribasso. (747) rapporto di Informazioni aggiornate al rendimento medio dei rendimenti risk adjusted oltre deviazione standard dei rendimenti risk adjusted. (1322) l'Alfa e l'Indice di Sharpe sono ora annualizzati. (1322) Fissare le unità durante la lettura e la scrittura di un attributo quotidiano bar firsttradingday. (1245) moduli invio facoltativo, quando mancano, non causano più un NameError. (1246) Trattare argomenti schedulefunction come regola momento in cui viene fornita una regola di tempo, ma nessuna regola data. (1221) Proteggere contro le condizioni al contorno all'inizio e alla fine giorno di negoziazione in funzione di programmazione. (1226) Applicare adattamenti giorno precedente quando si utilizza la storia con una frequenza di 1d. (1256) Fail veloce su colonne della pipeline non validi, invece di tentare di accedere colonna inesistente. (1280) Fissare la gestione AverageDollarVolume NaN. (1309) il miglioramento delle prestazioni a tracciare loader nucleo. (1227) Consentire le query Blaze simultanee. (1323) Prevenire mancante che porta i dati bcolz minute da fare ricerche inutili ripetuti. (1451) Cache future ricerche catena. (1455) Manutenzione e refactoring rimossi restante menzioni di addhistory. (1287) La documentazione Aggiungi dispositivo di prova che le fonti di dati dei prezzi giornalieri da infissi dati relativi ai prezzi al minuto. (1243) Formato dati Modifiche BcolzDailyBarReader e l'uso BcolzDailyBarWriter esempio il calendario di trading, invece di giorni di negoziazione serializzate a JSON. (1.330) Variazione formato assets. db per supportare punto in ricerche di tempo. (1.361) Variazione BcolzMinuteBarReaderand BcolzMinuteBarWriter per supportare varie dimensioni tick. Release (1428) 1.0.1 Si tratta di un minore bug-fix release da 1.0.0 e comprende un piccolo numero di correzioni di bug e miglioramenti della documentazione. Miglioramenti aggiunto il supporto per i modelli di commissione definiti dall'utente. Vedere la classe zipline. financemissionmissionModel per maggiori dettagli sull'implementazione di un modello di commissione. (1213) Aggiunto il supporto per le colonne non galleggiante a set di dati Pipeline Blaze-backed (1201). Aggiunto zipline. pipeline. slice. Slice. un nuovo termine gasdotto progettato per estrarre una singola colonna da un altro termine. Fette possono essere creati da indicizzare in un termine, digitato da bene. Correzioni (1267) errori È stato risolto un bug per cui caricatori Pipeline non erano adeguatamente inizializzati da zipline. runalgorithm (). Questo invocazioni anche colpite del zipline eseguiti dalla CLI. Corretto un bug che causava la magia delle cellule IPython zipline a fallire (533233fae43c7ff74abfb0044f046978817cb4e4). Corretto un bug nel modello commissione PerTrade cui commissioni sono state erroneamente applicate a ciascun parziale riempimento di un ordine piuttosto che l'ordine stesso, con conseguente algoritmi in fase di ricarica troppo nelle commissioni se grossi quantitativi. PerTrade ora si applica correttamente commissioni su una base per-ordine (1213). Attributo accede su CustomFactors definiscono uscite multiple sarà ora tornare correttamente una fetta d'uscita quando l'uscita è anche il nome di un metodo Factor (1214). utilizzo Sostituito deprecato di pandas. io. data con pandasdatareader (1218). Risolto un problema in cui i file stub. pyi per zipline. api sono stati accidentalmente esclusi dalla distribuzione sorgente PyPI. gli utenti Conda non dovrebbe essere modificata (1230). Documentazione Aggiunto un nuovo esempio, zipline. examples. momentumpipeline. che esercita l'API Pipeline (1230). In evidenza Zipline 1,0 Rewrite (1105) Abbiamo riscritto un sacco di Zipline e dei suoi concetti di base, al fine di migliorare le prestazioni di esecuzione. Allo stesso tempo, we8217ve introdotto diverse nuove API. Ad alto livello, le versioni precedenti di Zipline simulazioni tirato da un flusso multiplex di fonti di dati, che sono stati fusi via heapq. Questa corrente è stata alimentata al ciclo della simulazione, guidando l'orologio avanti. Questa forte dipendenza leggere tutti i dati ha reso difficile per ottimizzare le prestazioni di simulazione perché non vi era alcun legame tra la quantità di dati che abbiamo recuperato e la quantità di dati effettivamente utilizzati dall'algoritmo. Ora, noi recuperare i dati solo quando l'algoritmo ha bisogno. Una nuova classe, DataPortal. dispacci richieste di dati di varie fonti di dati e restituisce i valori richiesti. Questo rende il tempo di esecuzione di una simulazione scala molto più strettamente con la complessità dell'algoritmo, piuttosto che con il numero di risorse fornite dalle sorgenti di dati. Invece del flusso di dati di guida l'orologio, ora simulazioni scorrere un set pre-calcolata del giorno o timestamp minuto. I timestamp sono emessi da MinuteSimulationClock e DailySimulationClock. e consumata dal ciclo in main trasformata (). 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. per esempio. 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. Grazie. 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