Tuesday 4 July 2017

Moving Average Pylab


Spyder - die Python IDE Mo 16 September 2013 Hans Fangohr. University of Southampton, UK, 2013 Spyder hat sich zu einem ziemlich ausgereiften und sehr produktiven Tool hier habe ich versuchen, ein Tutorial bieten. Diese Dokumentation wird durch Schulungen in Python und Computational Modeling für Studenten an der University of Southampton motiviert (siehe historische Anmerkung für mehr Details). Dieser Blog-Eintrag wurde in Spyder als Tutorial integriert. Sobald Spyder begonnen hat, kann die aktuellste Version dieses Tutorials unter Help - gt Spyder Tutorial gefunden werden. Holen Sie sich die Hallo-Welt-Datei in das Spyder-Editor-Fenster von entweder Download hello. py und speichern als hello. py. (Sie laden die Datei herunter, indem Sie mit der rechten Maustaste auf den Link in Ihrem Browser klicken und dann Ziel speichern unter oder als Download speichern unter) und dann die Datei hello. py über das Menü Datei öffnen und dann Öffnen wählen. Wir drücken dies als File - gt Open kurz aus. Klicken Sie auf hallo. py, um den Quellcode im Webbrowser zu sehen, dann kopieren Sie den ganzen Code navigieren Sie zum Editor-Fenster in Spyder und fügen Sie den Code ein. Dann speichern Sie die Datei als hallo. py. Um das Programm auszuführen, wählen Sie Run - gt Run (oder drücken Sie F5) und bestätigen Sie die Run-Einstellungen, falls erforderlich. Sie sollten die Ausgabe wie folgt aussehen: oder (der jeweilige Pfad hängt davon ab, wo Sie die Datei gespeichert haben, aber das wird von Spyder automatisch eingefügt): Wenn ja, dann hast du gerade dein erstes Python-Programm ausgeführt - gut gemacht. Bevor wir fortfahren, bitte die IPython-Konsole kann ein bisschen mehr als die Standard-Python-Konsole, und wir empfehlen, es als Standard-Konsole hier zu verwenden. In der IPython-Interpreter-Session, die wir gerade erst begonnen haben, kannst du Run-gtRun (wie vorher) verwenden, um hallo. py auszuführen, und du solltest sehen: Python liest die Datei Zeile für Zeile und ignoriert Kommentare, wenn es um das Def-Keyword geht Weiß, dass eine Funktion in dieser und der nächsten (ein oder mehreren) Zeilen definiert ist. In der Datei hello. py erstellt also Python ein Funktionsobjekt mit dem Namen hallo. Alle eingekerbten Zeilen nach def hallo () gehören zum Funktionskörper. Beachten Sie, dass das Funktionsobjekt gerade an dieser Stelle in der Datei erstellt wird, aber die Funktion noch nicht aufgerufen wird (d. h. nicht ausgeführt). Wenn Python über Befehle (anders als def. Und ein paar andere Schlüsselwörter) kommt, die in der linken Spalte geschrieben werden, wird es diese sofort ausführen. In der hallo. py-Datei ist das nur die Zeile Hallo (), die eigentlich die Funktion mit dem Namen hallo aufrufen (d. h. ausführen). Wenn du die Zeile hello () aus dem Programm löschst und die ganze Datei nochmal renierst (durch Drücken von F5 oder Auswahl von run - gt run), wird nichts gedruckt (da die Funktion hallo definiert, aber nicht aufgerufen, dh nicht ausgeführt wird) . Jetzt solltest du wissen, wie man ein Python-Programm ausführt, das du im Editor-Fenster in Spyder mit der Python-Konsole und der anspruchsvolleren IPython-Konsole hast. Wenn Sie gerade erst anfangen, Python zu lernen, ist dies wahrscheinlich ein guter Punkt, um zu Ihrem Textbuchkurs zurückzukehren und schauen Sie sich einfachere Beispiele an. Im nächsten Abschnitt finden Sie detailliertere Informationen, wie Sie Teile des Codes im Editor in der Python-Konsole ausführen und so Teile Ihrer Definitionen im Editor aktualisieren können. Dies ist eine fortgeschrittenere Technik, kann aber sehr nützlich sein. (Sie können auch an der Option interessiert sein, Chunks (sog. Quotcellsquot) von Code auszuführen, die durch Trennzeichen getrennt sind - siehe Verknüpfungen für nützliche Funktionen.) Sobald Sie das Programm hello. py ausgeführt haben, wird das Funktionsobjekt hello definiert Und bekannt an der Python-Aufforderung. Wir können also die Funktion von der Python-Eingabeaufforderung aufrufen: Rufen Sie die Hallo () - Funktion aus der Python-Eingabeaufforderung auf, dh geben Sie hallo () in das Python-Shell-Fenster ein (die Python-Eingabeaufforderung wird als gtgtgt oder als In angezeigt, wenn wir die IPython-Sitzung verwenden Das Fragezeichen kann jede positive ganze Zahl sein.), Und drücken Sie die Return-Taste. Sie sollten feststellen, dass die Hallo () - Funktion wieder ausgeführt wird, d. h. Hello World wird erneut gedruckt. Ihr Funktionsaufruf an der Python-Aufforderung zusammen mit der Ausgabe sollte so aussehen: Können Sie sehen, wie sich das von der Ausführung des gesamten Programms unterscheidet Wenn wir das ganze Programm ausführen (durch Drücken von F5), geht Python durch die Datei, erstellt die Hallo-Funktion Objekt (überschreibt das vorherige Objekt), erreicht das Hauptprogramm und ruft die Funktion auf. Wenn wir hallo () von der Python-Eingabeaufforderung anrufen, rufen wir nur die Funktionsobjekte Hallo an, die in der (I) Python-Konsole definiert wurden, als wir die ganze hallo. py-Datei früher ausgeführt haben (durch Drücken von F5). Dies wird im Laufe der Zeit klarer und auch wenn wir mit etwas größeren Beispielen arbeiten. Vielleicht möchten Sie zu diesem Tutorial zu einem etwas späteren Stadium zurückkehren. Python bietet eine Funktion, die alle bekannten Objekte (im aktuellen Namensraum) anzeigt. Es heißt dir (). Wenn Sie dir () an der Eingabeaufforderung eingeben, erhalten Sie eine Liste bekannter Objekte. Ignoriere alles mit einem Unterstrich für jetzt. Kannst du Hallo in der Liste sehen (Wenn du eine lange Liste von definierten Objekten bekommst, dann kann Spyder vielleicht schon einige Bequemlichkeitsimporte für dich getan haben. Um dies zu erreichen, kannst du vielleicht: Dann Dir laufen () wie oben angedeutet.) Einmal ein Objekt ist im aktuellen Namensraum sichtbar (wie es in diesem Beispiel hallo ist), können wir die Hilfefunktion wie folgt nutzen, um darüber zu erfahren: Geben Sie help (hallo) an der Python-Eingabeaufforderung ein, Sie sollten die Ausgabe wie folgt sehen: Wo ist Python Nehmen Sie die Informationen von einigen davon (wie die Anzahl der Eingabe-Argumente und Namen dieser Variablen hier haben wir keine Eingabe-Argumente) Python kann durch die Inspektion seiner Objekte zu finden, zusätzliche Informationen kommt aus der Dokumentation Zeichenfolge für die Funktion Objekt hallo gegeben. Der Dokumentationsstring ist der erste String unmittelbar unterhalb der Linie def hello ():. Die Spyder-Umgebung bietet auch ein Panel in der oberen rechten Ecke (standardmäßig), die der Objekt-Inspektor ist. Wenn du im Objekt-Inspektor-Fenster hallo in die leere Zeile eingibst, gibt es auch die Hilfe-Zeichenfolge. Im Editor-Fenster, ändern Sie die Funktion hallo, so dass es Good Bye World statt hallo Welt druckt. Drücken Sie F5 (um das ganze Programm auszuführen) und überprüfen Sie, ob die Ausgabe des Programms nun ist: Was ist passiert, wenn Sie F5 gedrückt haben, ist das: Python hat die Datei hello. py durchlaufen und ein neues Funktionsobjekt erstellt hallo (Überschreiben der Funktion Objekt hallo hatten wir vorher definiert) und dann die Funktion ausgeführt. Wir müssen mit einem klar definierten Zustand beginnen. Um dies zu tun, ändere bitte die Funktion hallo () zurück, damit es Hallo Welt druckt (d. h. die Originaldatei hello. py verwenden), dann drücke F5, um das ganze Programm auszuführen und zu überprüfen, ob es Hallo Welt druckt. Rufen Sie die Funktion hallo () an der Eingabeaufforderung auf (wie unter Aufruf bestehender Funktionsobjekte aus der Befehlszeile beschrieben). Du solltest Hallo Welt sehen. Ändern Sie nun die Funktionsdefinition so, dass es Laters World ausdrucken würde. Und speichern Sie die Datei (aber führen Sie das Programm NICHT aus, d. H. Drücken Sie F5 noch nicht). Rufen Sie die Funktion hello () wieder aus der Eingabeaufforderung auf. Sie sollten feststellen, dass der Text gedruckt liest Hallo Welt. Wie hier Warum ist das so Weil das Hallo-Funktionsobjekt im Python-Interpreter das alte ist, das Hallo Welt druckt. Bisher haben wir die Datei hello. py (und ersetzt Hallo World dort mit Laters World) im Editor geändert, aber das hat die Objekte nicht beeinflusst, die zuvor im Python-Interpreter erstellt wurden. Hier sind zwei Möglichkeiten, unsere modifizierte Version der Hallo-Funktion zu nutzen: Option 1: die ganze Datei hello. py erneut durch Drücken von F5 ausführen: das erzeugt ein neues Funktionsobjekt hallo (und überschreibt das alte). Sie sollten feststellen, dass, wenn Sie F5 drücken und dann hallo () an der Eingabeaufforderung anrufen, der neue Text Laters World gedruckt wird. Option 2: Wähle die Region, die du gewechselt hast (in diesem Fall die ganze Funktion Hallo, beginnend von der Zeile def hallo (): nach unten, um keine zurückzukehren, und dann die Option Run - gt Run auswählen, um das Hallo-Objekt im Interpreter zu aktualisieren Ohne die ganze hallo. py-Datei ausführen zu müssen: Wenn wir nun hallo () eingeben, sehen wir die Update-Antwort: Die Fähigkeit, Teile des Codes auszuführen, um einige Objekte im Interpreter zu aktualisieren (im obigen Beispiel haben wir die Funktion aktualisiert Objekt hallo), ist bei der Entwicklung und dem Debugging komplexerer Codes von großem Nutzen und beim Erstellen von Objektdaten in der Interpreter-Session nehmen Sie sich Zeit, zB indem Sie nur die Funktionen (oder Klassenobjekte usw.) ändern, die wir tatsächlich entwickeln oder debuggen Um die Python-Programmierung und die rechnerische Modellierung zu vermitteln, empfehlen wir, (i) IPython anstelle des normalen Python-Interpreters zu verwenden und (ii) keine Bequemlichkeitsimporte zu verwenden Akzeptiert IPython als De-facto-Standard und hilft, Namespaces besser zu verstehen. Spyder versucht, weiter fortgeschrittenen Benutzern zu helfen, indem er eine Anzahl von Modulen in den Hauptnamenraum importiert. Geben Sie wissenschaftlich in die Eingabeaufforderung ein, um die Details zu sehen. Dieses Verhalten kann sich in zukünftigen Spyder-Releases ändern. Während diese Bequemlichkeit Importe sind sehr nützlich für erfahrenere Programmierer, können sie verwirrend (wenn nicht irreführend) für Anfänger. Wir empfehlen daher, diese Importe rückgängig zu machen, um unsere Anforderungen zu skizzieren und zu (i) auf eine IPython-Konsole zu wechseln. Und (ii) den Rücksetzbefehl ausgeben, um den Namensraum zurückzusetzen. Beide Schritte werden im nächsten Abschnitt näher erläutert. Im Konsolenfenster (rechte untere Ecke standardmäßig) sehen Sie standardmäßig eine Eingabeaufforderung mit drei größer als Zeichen, d. h. gtgtgt. Dies zeigt, dass wir die Konsole benutzen - im Grunde genommen eine normale Python-Interpreter-Session (mit einigen zusätzlichen Funktionen von Spyder). Stattdessen möchten wir eine interaktive Python-Shell verwenden, kurzes IPython aus dem ipython-Projekt. Wählen Sie dazu Interpreter - gt Öffnen Sie eine IPython-Konsole. Sie sollten im Konsolenfenster eine neue Shell sehen, und die IPython-Eingabeaufforderung In 1: sollte angezeigt werden. Der Namensraum kann in IPython mit dem Befehl reset gelöscht werden. Geben Sie zurück und drücken Sie die Eingabetaste, dann bestätigen Sie mit y: Wir besprechen dies ein wenig weiter, aber Sie können folgendes überspringen, wenn Sie nicht interessiert sind: Nach dem Ausgeben des Rücksetzbefehls sollten wir nur wenige Objekte im Namensraum dieser Sitzung definieren . Wir können alle mit dem Befehl dir () auflisten: Wenn du also den Bestätigungsschritt des reset-Befehls überspringen möchtest, kannst du reset - f anstelle von reset verwenden. Zusätzlich zu der Syntax, die von Python erzwungen wird, gibt es zusätzliche Konventionen bezüglich des Layouts des Quellcodes, insbesondere der Style Guide für Python Quellcode, der als pap88ot kennt. Eine Menge von Spyders Verhalten kann durch seine Voreinstellungen konfiguriert werden. Wo dies im Menü liegt, hängt von deinem Betriebssystem ab: Unter Windows und Linux geh zu Tools - gt Voreinstellungen Auf Mac OS geh zu Python - gt Voreinstellungen Gehe zu Vorgaben - gt IPython-Konsole - gt Start und wähle das Tickbox neben Öffnen Sie beim Start eine IPython-Konsole. Dann klicken Sie auf die Schaltfläche OK. Das nächste Mal, wenn Spyder startet, zeigt es die IPython-Konsole automatisch an. Gehen Sie zu Vorgaben - gt Editor - gt Code IntrospectionAnalyse und wählen Sie das Tickbox neben Style-Analyse (PEP8) Um jede Magie zu vermeiden, wenn die Konsole gestartet wird, gehen Sie zu Preferences - gt Console - gt Advanced Settings - gt PYTHONSTARTUP Ersatz und wählen Sie Standard PYTHONSTARTUP Skript (Und Spyder neu starten). (Diese Magie, unter anderem, läuft aus dem zukünftigen Import-Division-Befehl.) Die Standardeinstellungen können dies in der nächsten Hauptversion ändern. Um das Importieren aller Objekte aus pylab und numpy in den aktuellen Namensraum in der IPython-Konsole zu vermeiden, gehe zu Preferences - gt IPython console - gt Graphics und wähle das Tickbox neben dem automatischen Laden von Pylab - und NumPy-Modulen ab und deaktiviere auch die Option Support aktivieren. Die Standardeinstellungen können sich in der nächsten Hauptversion ändern. Durch Präferenzen - gt IPython-Konsole - gt Erweiterte Einstellungen - gt Verwenden Sie symbolische Mathematik Wir können IPythons symbolischen Python-Modus aktivieren. Dies ermöglicht eine gut gerenderte Sympy-Ausgabe (Latex-Stil) und importiert auch einige Sympy-Objekte automatisch, wenn die IPython-Konsole startet und berichtet, was es getan hat. Wir können dann die Variablen x verwenden. Y Zum Beispiel wie folgt: F5 führt den aktuellen Puffer aus F9 führt den aktuell markierten Code aus: Das ist sehr nützlich, um Definitionen von Funktionen (zB) in der Interpretersitzung zu aktualisieren, ohne die ganze Datei erneut ausführen zu müssen. CTRL ltRETURNgt führt die aktuelle Zelle aus ( Menu enty Run - gt Run Zelle). Eine Zelle ist definiert als der Code zwischen zwei Zeilen, die mit dem vereinbarten Tag beginnen. SHIFT ltRETURNgt führt die aktuelle Zelle aus und schaltet den Cursor zur nächsten Zelle (Menüeintrag Run - gt Run Zelle und Fortschritt). Zellen sind nützlich, um ein großes filecode Segment in kleineren Einheiten auszuführen. (Es ist ein bisschen wie eine Zelle in einem IPython-Notebook, in dem Stücke von Code unabhängig laufen können.) ALT ltCURSOR UPgt verschiebt das aktuelle Line up. Wenn mehrere Zeilen hervorgehoben sind, werden sie zusammen verschoben. ALTltCURSOR DOWNgt arbeitet entsprechend bewegte Linie (n) unten. Mit der rechten Maustaste auf eine Funktionsmethode in der Quelle, öffnet sich ein neues Editorfenster mit der Definition dieser Funktion. SHIFTCTRLALTM maximiert das aktuelle Fenster (oder verändert die Größe wieder normal, wenn in einem maximierten Fenster gedrückt wird) SHIFTCTRLF aktiviert die Suche über alle Dateien. Unter Mac OS X: CMD erhöht die Schriftgröße im Editor, CMD - abnehmen. Auch funktioniert in der IPython-Konsole. Die Schriftgröße für den Objekt-Explorer, die Python-Konsole usw. können einzeln über Preferences - gt Object Explorer etc. eingestellt werden. Ich konnte nicht eine Möglichkeit finden, die Schriftgröße im Variablen-Explorer zu ändern. CTRLSPACE autokompletiert Befehle, Funktionsnamen, Variablennamen, Methoden sehr nützlich. CMDs (unter Mac OS X) und CTRLs (ansonsten) im Editor-Fenster speichert die aktuell bearbeitete Datei. Dies führt auch dazu, dass verschiedene Warndreiecke in der linken Spalte des Editors aktualisiert werden (andernfalls aktualisieren sie alle 2 bis 3 Sekunden standardmäßig). CMDs (auf Mac OS X) und CTRLs (anders) im IPython-Konsolenfenster speichert die aktuelle IPython-Sitzung als HTML-Datei, einschließlich aller Zahlen, die inline angezeigt werden können. Dies ist nützlich als eine schnelle Art der Aufnahme, was in einer Sitzung gemacht wurde. (Es ist nicht möglich, diesen gespeicherten Datensatz wieder in die Session zu laden - wenn man so eine Funktionalität benötigt, suche das IPython Notebook.) CMDi (auf Mac OS X) und CTRLi (andernfalls), wenn es gedrückt wird, während sich der Cursor auf einem Objekt befindet , Öffnet die Dokumentation für dieses Objekt im Objektinspektor. Dies sind die Einstellungen, die festlegen, wie der Code im Editor ausgeführt wird, wenn wir Run - gt Run auswählen oder F5 drücken. Standardmäßig wird das Einstellungsfeld das erste Mal angezeigt, wenn wir versuchen, eine Datei auszuführen. Wenn wir die Einstellungen zu einem anderen Zeitpunkt ändern möchten, können sie unter Run - gt Configure oder durch Drücken von F6 gefunden werden. Es gibt drei Möglichkeiten für den Dolmetscher zu verwenden, von denen Ill diskutieren die ersten beiden. Nehmen wir an, wir haben ein Programm hello. py in den Editor, der liest Dies ist die Standardvorschlag, und auch allgemein eine gute Wahl. Auswählen Ausführen in der aktuellen Python - oder IPython-Interpreter-Einstellung unter Run - gt Configure bedeutet, dass Wenn die Ausführung von hello. py abgeschlossen ist, können wir mit dem Interpreter interagieren, in dem das Programm ausgeführt wurde, und wir können hierfür den praktischen IPython-Interpreter verwenden Als der Standard-Python-Interpreter). Wir können mit Objekten inspizieren und interagieren, die die Ausführung unseres Programms erstellt hat, wie ich und hallo (). Dies ist in der Regel sehr nützlich für inkrementelle Codierung, Testen und Debugging: Wir können Hallo () direkt aus der Interpreter-Aufforderung aufrufen und brauchen nicht die ganze hallo. py für diese (obwohl, wenn wir die Funktion Hallo () ändern wir Um den Puffer oder zumindest die Funktionsdefinition auszuführen, um die neue Version von hallo () beim Interpreter sichtbar zu machen, entweder durch Ausführen des ganzen Puffers oder über Run - gt Run Selection.) Allerdings führt der Code im Editor im Aktueller Interpreter bedeutet auch, dass der Code, der ausgeführt wird, andere (globale) Objekte sehen kann, die in der Interpretersitzung definiert wurden. Diese Beharrlichkeit von Objekten ist leicht forgotton und ist in der Regel nicht erforderlich, wenn man an kleinen Programmen arbeitet (obwohl es gelegentlich von großem Wert sein kann). Diese Objekte könnten aus der vorherigen Ausführung von Code, aus interaktiver Arbeit im Dolmetscher oder aus Bequemlichkeitsimporten wie aus dem Pylab-Import kommen (Spyder kann einige dieser Bequemlichkeitsimporte automatisch durchführen). Diese Sichtbarkeit von Objekten im globalen Namensraum des Interpreters auf den Code, den wir ausführen, kann auch zu Codierungsfehlern führen, wenn der Code versehentlich auf diese Objekte angewiesen ist. Hier ist ein Beispiel: Stellen Sie sich vor, dass wir den Code hallo. py laufen lassen. Anschließend ist die Variable i im Interpreter als globale Variable bekannt. Wir bearbeiten die Hallo. py-Quelle und versehentlich löschen die Zeile i 42 Wir führen den Puffer mit hallo. py wieder aus. An diesem Punkt wird der Aufruf von hallo (i) nicht fehlschlagen, weil der Dolmetscher ein Objekt des Namens hat, das ich definiert habe, obwohl dies nicht in der Quelle von hello. py definiert ist. An dieser Stelle konnten wir hallo. py retten und (fälschlicherweise) denken, dass es richtig ausführen würde. Allerdings würde es in einem neuen Python-Interpreter-Session laufen (oder über python hallo. py. Sagen) würde zu einem Fehler führen, weil ich nicht definiert ist. Das Problem entsteht, weil der Code von einem Objekt (hier i) Gebrauch macht, ohne es zu erstellen. Dies wirkt sich auch auf den Import von Modulen aus: Wenn wir an der IPython-Eingabeaufforderung ein Pylab importiert hätten, dann wird unser Programm das sehen, wenn es in dieser IPython-Interpretersitzung ausgeführt wird. Um zu erlernen, wie wir überprüfen können, dass unser Code nicht von solchen vorhandenen Objekten abhängt, sehen Sie, wie man den Scheck überprüft, den Ihr Code korrekt ausführt, seinen eigenen Quot. Die Auswahl von Execute im neuen dedizierten Python-Interpreter unter Run - gt Configure startet einen neuen Python-Interpreter, sobald das Programm hello. py ausgeführt wird. Der Hauptvorteil dieses Modus über Execute im aktuellen Python - oder IPython-Interpreter ist, dass wir sicher sein können, dass es in diesem Interpreter keine globalen Objekte gibt, die aus dem Debugging und der wiederholten Ausführung unseres Codes entstehen: Jedes Mal, wenn wir den Code im Editor ausführen , Der Python-Interpreter, in dem der Code läuft, wird neu gestartet. Dies ist eine sichere Option, bietet aber weniger Flexibilität und kann den IPyton-Interpreter nicht nutzen. Angenommen, Sie haben sich für Ihren Code zum Ausführen im aktuellen Python - oder IPython-Interpreter entschieden. Dann seid ihr zwei Optionen, um zu überprüfen, ob unser Code auf eigene Faust arbeitet (dh es hängt nicht von undefinierten Variablen, unimported Modulen und Befehlen etc. ab.) Alternativ, wenn du mit dem aktuellen IPython-Interpreter bleiben möchtest, kannst du IPythons Magic Reset verwenden Befehl, der alle Objekte (wie zB im obigen Beispiel) aus dem aktuellen Namensraum entfernt und dann den Code im Editor ausführt. Sobald Sie ein Stück Code abgeschlossen haben, überprüfen Sie, ob es selbstständig ausgeführt wird, indem Sie eine der Optionen verwenden, die in der Verdopplung überprüft werden, ob Ihr Code den korrekten Zitat seines eigenen Quotes ausführt. Wenn mehrere Dateien im Editor geöffnet sind, werden die entsprechenden Registerkarten am oberen Rand des Fensterbereichs in alphabetischer Reihenfolge des Dateinamens von links nach rechts angeordnet. Auf der linken Seite der Registerkarten gibt es als Symbol, das die Registerkarten durchsucht, wenn die Maus darüber schwebt. Es ist sinnvoll, direkt zu einer bestimmten Datei zu springen, wenn viele Dateien geöffnet sind. Umgebungsvariablen können aus dem Konsolenfenster (rechts unten im Standardlayout) angezeigt werden. Klicken Sie auf das Symbol Optionen (die Tooltip ist Optionen) und wählen Sie dann Umgebungsvariablen aus. Alle auf der Festplatte gespeicherten Anpassungen können durch Aufruf von Spyder aus der Befehlszeile mit dem Schalter - zurückgesetzt werden. D. h. ein Befehl wie Spyder - Rücksetzen. Wenn Sie mit der rechten Maustaste auf Arrays im Variablen-Explorer klicken, können Sie diese weitergeben und analysieren. Ein Doppelklick auf ein Wörterbuchobjekt öffnet ein neues Fenster, das das Wörterbuch schön anzeigt. Vermutlich gibt es andere versteckte Fähigkeiten für einige andere Datentypen. Es gibt einige Konventionen, die in Bezug auf Dokumentationsstrings in umstrukturiertem Text geschrieben wurden. Wenn wir diesen Richtlinien folgen, können wir in Spyder wunderschön formatierte Dokumentationsstrings erhalten. Zum Beispiel, um unsere durchschnittliche () Funktion wie folgt auszusehen im Spyder Object Explorer: Wir müssen den Dokumentationsstring wie folgt formatieren. Was hier wichtig ist, ist, dass das Wort Parameter verwendet und unterstrichen wird. Die Linie a. Zahl zeigt uns, dass der Typ des Parameters a die Nummer ist. In der nächsten Zeile, die eingerückt ist, können wir eine ausführlichere Erklärung schreiben, was diese Variable repräsentiert, welche Bedingungen die erlaubten Typen erfüllen müssen. Das gleiche gilt für alle Parameter und auch für den zurückgegebenen Wert. Oft ist es eine gute Idee, ein Beispiel wie gezeigt einzuschließen. Durch Aktivieren des Debug-Modus (Debug - gt Debug) wird der IPython-Debugger (ipdb) in der IPython-Konsole gestartet. Dies wird als normal betrieben, aber das Editor-Anzeigefenster markiert die Zeile, die gerade ausgeführt werden soll, und der Variable Explorer zeigt Variablen im aktuellen Kontext der Programmausführung an. (Es werden nur numerische Variablen angezeigt, d. h. keine Funktionsobjekte usw.) Die Tastenbefehle innerhalb des IPython-Debuggers sind einzelne Tastenanschläge: s, um in die aktuelle Anweisung zu treten. Wenn dies ein Funktionsaufruf ist, treten Sie in diese Funktion ein. N in die nächste Anweisung übergehen. Wenn die aktuelle Anweisung eine Funktion ist, treten Sie nicht in diese Funktion ein, sondern führen Sie sie vollständig aus, bevor Sie die Kontrolle an die interaktive Debugger-Eingabeaufforderung zurückgeben. R alle Anweisungen in der aktuellen Funktion abschließen und von dieser Funktion zurückkehren, bevor du die Steuerung zurückgibst. P Print erlaubt es, Werte von Variablen anzuzeigen, zB p x druckt den Wert der Variablen x. Beachten Sie, dass Sie bei der ipdb auch Werte der Variablen ändern können. Zum Beispiel, um eine wertvolle x zu ändern. Sie können sagen, ipdb gt x 42 und der Debugger wird weiter mit x an 42 gebunden. Sie können auch Funktionen anrufen und viele andere Dinge machen. Um den Debugging-Modus zu verlassen, kannst du im Menü Debug - gt Debugging Control - gt Exit eingeben. Exit In der IPython-Konsole können wir das Debuggen direkt nach dem Auslösen einer Exception aufrufen: Damit wird der IPython-Debug-Modus gestartet und erlaubt Inspektion der lokalen Variablen an der Stelle, an der die Ausnahme wie oben beschrieben aufgetreten ist. Dies ist viel effizienter als das Hinzufügen von print-Anweisungen zum Code und läuft es wieder. Wenn Sie dies verwenden, können Sie auch die Befehle nach oben und unten verwenden, die den Prüfpunkt nach oben und unten den Stapel navigieren. (Auf den Stack bedeutet, dass die Funktionen, die die aktuelle Funktion aufgerufen haben, die entgegengesetzte Richtung ist.) Angenommen, wir verwenden eine IPython-Konsole mit Version gt 1.0.0, können wir entscheiden, ob die mit matplotlibpylab erstellten Zahlen inline zeigen. D. h. innerhalb der IPython-Konsole, oder ob sie in einem neuen Fenster erscheinen sollen. Option 1 ist bequem, um eine Aufzeichnung der interaktiven Sitzung zu speichern (Abschnitt Verknüpfungen für nützliche Funktionen listet eine Verknüpfung, um die IPython-Konsole in einer HTML-Datei zu speichern). Option 2 ermöglicht interaktive Zoom in die Figur, manipulieren sie ein wenig, und speichern Sie die Figur in verschiedene Dateiformate über das Menü. Der Befehl, die Zahlen in der IPython-Konsole inline zu sehen, ist matplotlib inline. Der Befehl, um Figuren zu sehen, erscheinen in ihrem eigenen Fenster (das ist technisch ein QT Windown) ist matplotlib qt. Die Spyder-Voreinstellungen können verwendet werden, um das Standardverhalten anzupassen (insbesondere Präferenzen - gt IPython Console - gt Graphics - gt Aktivieren Unterstützung, um in Inline-Plotten umzuschalten). Aktuelle Beiträge KategorienRelease Notes 8. September 2016 Erweiterungen Fügt für den Blaze-Core-Loader Vorwärts-Füll-Checkpoint-Tabellen hinzu. Dies ermöglicht es dem Lader, die Daten effizienter zu füllen, indem er das niedrigere Datum kapselt, das es bei der Abfrage von Daten suchen muss. Die Checkpoints sollten neuartige Deltas angewendet haben (1276). VagrantFile aktualisiert, um alle dev-Anforderungen einzubeziehen und ein neues Bild zu verwenden (1310). Erlaube Korrelationen und Regressionen zwischen zwei 2D-Faktoren zu berechnen, indem sie Berechnungen asset-weise (1307) durchführen. Filter wurden standardmäßig Windowsafe hergestellt. Jetzt können sie als Argumente an andere Filter, Faktoren und Klassifikatoren (1338) weitergegeben werden. Es wurde ein optionaler groupby-Parameter hinzugefügt. oben(). Und unten (). (1349). Neue Pipeline-Filter hinzugefügt, alle und alle. Die einen anderen Filter aufnimmt und True zurückgibt, wenn ein Asset für alle Tage in den vorherigen Fensterlängestagen (1358) einen True erzeugt hat. Neue Pipeline Filter hinzugefügt AtLeastN. Die einen anderen Filter und einen int N nimmt und True zurückgibt, wenn ein Asset ein True on N oder mehr Tage in den vorherigen windowlennth Tagen (1367) produziert hat. Verwenden Sie externe Bibliothek empyrisch für Risikoberechnungen. Empyrisch vereinheitlicht die Risiko-Metrik-Berechnungen zwischen pyfolio und zipline. Empyrisch fügt benutzerdefinierte Jahresoptionsoptionen für die Rückgabe von benutzerdefinierten Frequenzen hinzu. (855) Aroonfaktor hinzufügen (1258) Schnellstochastischer Oszillatorfaktor hinzufügen. (1255) Dockerfile hinzufügen. (1254) Neuer Handelskalender, der Sitzungen unterstützt, die sich über Mitternacht erstrecken, z. B. 24 Stunden 6:01 PM-6:00PM Sitzungen für Futures-Handel. Zipline. utils. tradingcalendar ist jetzt veraltet. (1138) (1312) Erlaube das Slicing einer einzelnen Spalte aus einem FactorFilterClassifier. (1267) Denimoku-Cloud-Faktor bereitstellen (1263) Standardparameter auf Pipeline-Terme zulassen. (1263) Geben Sie die Änderungsrate an. (1324) Geben Sie einen linear gewichteten gleitenden Mittelfaktor an. (1325) NotNullFilter hinzufügen. (1345) Erlaube Kapitaländerungen durch einen Zielwert zu definieren. (1337) TrueRange Faktor hinzufügen. (1348) Fügen Sie Punkt in der Zeit-Lookups zu assets. db hinzu. (1361) Machen Sie Cantrade bewusst der Asset8217s Austausch. (1346) Add-Sample-Methode auf alle berechenbaren Begriffe. (1394) QuantopianUSFuturesCalendar hinzufügen. (1414) Freigeben der Veröffentlichung von alten assets. db Versionen. (1430) Zeitplan für Futures-Handelskalender aktivieren. (1442) Demonstration von Regressionen der Länge 1. (1466) Experimentell Fügen Sie Unterstützung für kommende Future - und Equity-History-Fenster hinzu und aktivieren Sie den zukünftigen Datenzugriff über das Datenportal. (1435) (1432) Bug Fixes Änderungen AverageDollarVolume Eingebauter Faktor, um fehlende Nah - oder Volumenwerte als 0 zu behandeln. Bisher wurden NaNs einfach vor der Mittelung weggeworfen, wobei die restlichen Werte zu viel Gewicht (1309) gegeben wurden. Entfernen Sie die risikofreie Rate aus der Berechnung des Sharpe-Verhältnisses. Das Verhältnis ist nun der Durchschnitt der risikoadjustierten Renditen über die Vorträglichkeit der bereinigten Renditen. (853) Sortino-Verhältnis wird die Berechnung anstelle von np. nan zurückgeben, wenn die Rückgabe gleich Null ist. Das Verhältnis gibt nun den Durchschnitt der risikoadjustierten Renditen über das Abwärtsrisiko zurück. Fixed falsch markierte API durch Umwandlung von Mar zu Downsiderisk. (747) Das Downside-Risiko gibt nun die Quadratwurzel des Mittelwerts der Downside-Differenzquadrate zurück. (747) Informationsquote aktualisiert auf Rendite Mittel der risikoadjustierten Renditen über die Standardabweichung der risikoadjustierten Renditen. (1322) Alpha und Sharpe Ratio sind nun annualisiert. (1322) Fix-Einheiten beim Lesen und Schreiben der täglichen Bar firsttradingday Attribut. (1245) Optionale Versandmodule, wenn sie fehlen, verursachen nicht mehr einen NameError. (1246) Behandlungsplan-Argument als Zeitregel, wenn eine Zeitregel, aber keine Datumsregel geliefert wird. (1221) Schützen Sie sich vor den Grenze Bedingungen am Anfang und Ende Handelstag in Zeitplan Funktion. (1226) Anwenden von Anpassungen auf den vorherigen Tag bei der Verwendung von Verlauf mit einer Frequenz von 1d. (1256) Fail schnell auf ungültige Pipeline-Spalten, anstatt zu versuchen, die nicht vorhandene Spalte zugreifen. (1280) Fix AverageDollarVolume NaN Handhabung. (1309) Leistungsverbesserungen zum Bohren von Kernlader. (1227) Gleichzeitige Blaze-Abfragen zulassen (1323) Vermeiden Sie fehlende führende bcolz-Minuten-Daten aus wiederholten unnötigen Lookups. (1451) Cache zukünftige Ketten-Lookups. (1455) Instandhaltung und Refactorings Entfernt verbleibende Erwähnungen der Zusatzgeschichte. (1287) Dokumentation Fügen Sie Testbefestigung hinzu, welche Quellen täglich Preisdatumsdaten von den kleinsten Preisfaktoren belegen. (1243) Datenformatänderungen BcolzDailyBarReader und BcolzDailyBarWriter verwenden Handelskalenderinstanz anstelle von Handelstagen, die an JSON serialisiert sind. (1330) Ändern Sie das Format von assets. db, um Point-of-Time-Lookups zu unterstützen. (1361) Ändern Sie BcolzMinuteBarReaderand BcolzMinuteBarWriter, um verschiedene Tick-Größen zu unterstützen. (1428) Release 1.0.1 Dies ist eine kleine Bug-Fix-Version von 1.0.0 und enthält eine kleine Anzahl von Bug-Fixes und Dokumentations-Verbesserungen. Erweiterungen Unterstützung für benutzerdefinierte Provisionsmodelle hinzugefügt. Weitere Informationen zur Implementierung eines Provisionsmodells finden Sie in der zipline. financemissionmissionModel-Klasse. (1213) Unterstützung für Nicht-Float-Spalten zu Blaze-backed Pipeline-Datensätzen (1201) hinzugefügt. Zipline. pipeline. slice. Slice hinzugefügt. Ein neuer Pipeline-Begriff, der entworfen ist, um eine einzelne Spalte aus einem anderen Begriff zu extrahieren. Scheiben können durch Indizierung in einen Begriff erstellt werden. (1267) Fehlerkorrekturen Ein Fehler wurde behoben, bei dem Pipeline-Lader nicht ordnungsgemäß von zipline. runalgorithm () initialisiert wurden. Dies trifft auch auf die Aufruf von Zipline aus der CLI zu. Es wurde ein Fehler behoben, der dazu führte, dass die Zipline-IPython-Zelle Magie versagte (533233fae43c7ff74abfb0044f046978817cb4e4). Ein Fehler im ProTrade-Provisionsmodell wurde behoben, bei dem Provisionen bei jeder Teilfüllung eines Auftrags falsch angewendet wurden, anstatt auf den Auftrag selbst, was dazu führte, dass Algorithmen bei der Bestellung großer Aufträge zu viel in Provisionen aufgeladen wurden. PerTrade beantragt nun Provisionen auf Auftragsebene (1213). Attributzugriffe auf CustomFactors, die mehrere Ausgänge definieren, geben nun korrekt ein Ausgabe-Slice zurück, wenn die Ausgabe auch der Name einer Factor-Methode (1214) ist. Ersetzte veraltete Verwendung von pandas. io. data mit pandasdatareader (1218). Es wurde ein Problem behoben, bei dem pyi stub-Dateien für zipline. api versehentlich von der PyPI-Quellverteilung ausgeschlossen wurden. Conda-Nutzer sollten nicht betroffen sein (1230). Dokumentation Ein neues Beispiel hinzugefügt, zipline. examples. momentpipeline. Die die Pipeline API (1230) ausübt. Highlights Zipline 1.0 Rewrite (1105) Wir haben viel Zipline und seine Grundkonzepte umgeschrieben, um die Laufzeitperformance zu verbessern. Gleichzeitig haben wir mehrere neue APIs eingeführt. Auf einem hohen Niveau zogen frühere Versionen von Zipline-Simulationen aus einem gemultiplexten Strom von Datenquellen, die über Heapq zusammengeführt wurden. Dieser Stream wurde der Haupt-Simulationsschleife zugeführt und fuhr die Uhr vorwärts. Diese starke Abhängigkeit vom Lesen aller Daten machte es schwierig, die Simulationsleistung zu optimieren, da es keine Verbindung zwischen der Menge der Daten, die wir abgerufen haben, und der Menge der Daten, die tatsächlich von dem Algorithmus verwendet wurden, gab. Jetzt holen wir nur Daten, wenn der Algorithmus es braucht. Eine neue Klasse, DataPortal. Sendet Datenanforderungen an verschiedene Datenquellen und gibt die angeforderten Werte zurück. Dies macht die Laufzeit einer Simulationsskala viel stärker mit der Komplexität des Algorithmus und nicht mit der Anzahl der von den Datenquellen bereitgestellten Assets. Statt des Datenstroms, der die Uhr treibt, werden nun Simulationen durch einen vorberechneten Satz von Tag - oder Minuten-Zeitstempeln durchgelesen. Die Zeitstempel werden von MinuteSimulationClock und DailySimulationClock ausgegeben. Und verbraucht von der Hauptschleife in 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. z. B. 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. Vielen Dank. 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