Wednesday, 27 December 2017

Moving genomsnittet pylab


Spyder - Python IDE mån 16 september 2013 Hans Fangohr. University of Southampton, Storbritannien, 2013 Spyder har utvecklats till ett relativt moget och mycket produktivt verktyg här försöker jag ge en handledning. Denna dokumentation motiveras av kurser i Python och beräkningsmodellering för studenter vid University of Southampton (se historisk notering för mer detaljer). Denna blogginmatning har integrerats i Spyder som handledning. När Spyder har startat kan den senaste versionen av denna handledning hittas under Help - gt Spyder-handledningen. Hämta världsfilen i Spyder-redigeringsfönstret genom att antingen Hämta hello. py och spara som hello. py. (Du laddar ner filen genom att högerklicka på länken i din webbläsare, välj sedan Spara mål som eller Spara nedladdning som) och öppna filen hello. py via menyn Arkiv och välj sedan Öppna. Vi uttrycker detta som File - gt Open kortfattat. klicka på hello. py för att se källkoden i webbläsaren och kopiera hela koden till redigeringsfönstret i spyder och klistra in koden. Spara sedan filen som hej. py. För att utföra programmet, välj Kör - gt Kör (eller tryck på F5) och bekräfta Kör inställningar om det behövs. Du ska se produktionen som: eller (den specifika sökvägen beror på var du har sparat filen, men den läggs automatiskt in av Spyder): Om så har du bara kört ditt första Python-program - bra gjort. Innan vi fortsätter, vänligen IPython-konsolen kan göra lite mer än standard Python-konsolen, och vi föreslår att du använder den som standardkonsol här. I den IPython tolk sessions som vi just har börjat kan du använda Run-gtRun (som tidigare) för att utföra hej. py och du bör se: Python läser fillinjen för rad, ignorerar kommentarer när det kommer över def nyckelordet, det vet att en funktion är DEFined i denna och nästa (en eller flera) linjer. I hello. py-filen skapar Python ett funktionsobjekt med namn hej. Alla indragna rader efter def hej (): tillhör funktionskroppen. Observera att funktionsobjektet just skapats vid denna punkt i filen, men funktionen är ännu inte kallad (dvs inte exekverad). När Python kommer över kommandon (annat än def. och några andra nyckelord) som är skrivna i den vänstra kolumnen, kommer det att genomföras direkt. I hej. py-filen är det bara linjeläsningshälsningen () som faktiskt kommer att ringa (dvs exekvera) funktionen med namn hej. Om du tar bort linjen hej () från programmet och kör hela filen igen (genom att trycka på F5 eller välja kör-kör), skrivs inget ut (eftersom funktionen hej är definierad men inte kallad, dvs inte exekverad) . Nu borde du veta hur man utför ett Python-program som du har i redigeringsfönstret i Spyder med Python Console och den mer sofistikerade IPython Console. Om du just börjat lära dig Python är det förmodligen en bra poäng att återvända till din textbokskurs och titta på mer grundläggande exempel. Nästa avsnitt ger mer detaljerad information om hur du kan utföra delar av koden i redigeraren i Python-konsolen och därmed uppdatera delar av dina definitioner i redigeraren. Detta är en mer avancerad teknik men kan vara mycket användbar. (Du kan också vara intresserad av alternativet att utföra bitar (så kallad quotcellsquot) av kod som är separerade av avgränsare - se genvägar för användbara funktioner.) När du har kört hello. py-programmet är funktionsobjektet hej definierat och känd vid Python-prompten. Vi kan sålunda ringa funktionen från Python-prompten: Ring funktionen hello () från Python-prompten, dvs typ hej () i Python Shell-fönstret (Python-prompten visar som gtgtgt. Eller som In om vi använder IPython-sessionen där Frågetecknet kan vara ett positivt heltal.) och tryck på returknappen. Du bör upptäcka att hello () - funktionen exekveras igen, dvs Hello World skrivs ut igen. Ditt funktionssamtal vid Python-prompten tillsammans med utmatningen ska se ut så här: Kan du se hur detta skiljer sig från att genomföra hela programmet igen När vi utför hela programmet (genom att trycka på F5), går Python igenom filen, skapar hejfunktionen objekt (tvingande föregående objekt), når huvudprogrammet och kallar funktionen. När vi kallar hej () från Python-prompten, ringer vi bara de funktionella objekten hej som har definierats i (I) Python-konsolen när vi körde hela hej. py-filen tidigare (genom att trycka på F5). Detta blir tydligare över tiden och även när vi arbetar med lite större exempel. Du kanske vill återvända till denna handledning på ett lite senare stadium. Python tillhandahåller en funktion som visar alla kända objekt (i nuvarande namnrymd). Det kallas dir (). När du skriver dir () vid prompten får du en lista med kända objekt. Ignorera allt som börjar med en understrykning för nu. Kan du se hej på listan (Om du får en lång lista med definierade objekt kan Spyder kanske ha gjort lite praktisk import för dig redan. För att adressera det här kanske du vill: Så kör dir () som föreslagits ovan.) En gång en objektet är synligt i det aktuella namnet utrymme (som det är hej i det här exemplet) kan vi använda hjälpfunktionen enligt följande för att få veta om det: Skriv hjälp (hej) vid Python-prompten, så ska du se produktionen så här: Var går Python ta informationen från något av det (som antalet inmatningsargument och namn på dessa variabler här har vi inga inmatningsargument) Python kan hitta genom att inspektera dess objekt, ytterligare information kommer från dokumentationssträngen som tillhandahålls för funktionsobjektet hej. Dokumentationssträngen är den första strängen strax under linjen def hej ():. Spyder-miljön ger också en panel i det övre högra hörnet (som standard) som är objektinspektören. Om du skriver hej till den tomma raden i objektinspektionsfönstret, kommer den också att ge hjälpsträngen. I redigeringsfönstret, ändra funktionen hej så att den skriver ut Good Bye World snarare än Hello World. Tryck på F5 (för att utföra hela programmet) och kontrollera att programmets utdata nu är: Vad som hänt när du tryckte på F5 är detta: Python har gått igenom hello. py-filen och skapat ett nytt funktionsobjekt hej (tvingande funktionen objekt hej vi hade definierat tidigare) och utförde sedan funktionen. Vi måste börja med en klart definierad stat. För att göra det, vänligen ändra funktionen hallo () tillbaka så att den skriver Hello World (dvs använd den ursprungliga hello. py-filen) och tryck sedan på F5 för att köra hela programmet och kontrollera att det skrivs ut Hello World. Ring funktionen hej () från kommandotolken (som beskrivs i Ring befintliga funktionsobjekt från kommandoraden). Du ska se Hello World tryckt. Ändra nu funktionsdefinitionen så att den skulle skriva ut Laters World. och spara filen (men kör INTE programmet, dvs tryck inte på F5 ännu). Ring funktionen hej () från kommandotolken igen. Du bör upptäcka att texten som skrivs ut läser Hello World. som här Varför är det så Eftersom hejfunktionsobjektet i Python-tolken är den gamla som skriver ut Hello World. Hittills har vi ändrat filen hej. py (och ersatt Hello World där med Laters World) i redigeraren men det har inte påverkat objekten som tidigare skapats i Python tolken. Här är två möjligheter att använda vår modifierade version av hejfunktionen: Alternativ 1: Kör hela filen hello. py igen genom att trycka på F5: detta skapar ett nytt funktionsobjekt hej (och överstyrer den gamla). Du bör hitta det om du trycker på F5 och sedan ringa hej () vid prompten, skrivs den nya texten Laters World ut. Alternativ 2: Välj den region du har ändrats (i så fall hela funktionen hej. Börja från raden def hej (): ner för att återvända Ingen. Och välj sedan Run - gt Run-val. Detta uppdaterar hejobjektet i tolken utan att behöva utföra hela hello. py-filen: Om vi ​​nu skriver hej () ser vi uppdateringssvaret: Möjligheten att utföra delar av koden för att uppdatera vissa objekt i tolken (i exemplet ovan uppdaterade vi funktionen objekt hej), är till stor nytta när du utvecklar och felsöker mer komplexa koder, och när du skapar objektsdata i tolkens session tar du tid. Till exempel genom att endast ändra de funktioner (eller klassobjekt, etc) som vi faktiskt utvecklar eller felsöker, vi kan fortsätta att använda data strukturerna etc som definieras i tolk sessionen. För att undervisa Python programmering och beräkningsmodellering rekommenderar vi att (i) använda IPython istället för den vanliga Python tolken och (ii) inte använda någon bekväm import. Han accepterar IPython som de facto-standarden och hjälper till att bättre förstå namnområden. Spyder försöker hjälpa fler avancerade användare genom att importera ett antal moduler till huvudnamnutrymmet. Skriv vetenskapliga i kommandotolken för att se detaljerna. Detta beteende kan ändras i framtida Spyder-utgåvor. Medan denna bekvämliga import är mycket användbar för mer erfarna programmerare kan de vara förvirrande (om inte vilseledande) för nybörjare. Vi rekommenderar därför att ångra denna import för att uppfylla våra krav ovan och att (i) byta till en IPython-konsol. och (ii) utfärda återställningskommandot för att återställa namnutrymmet. Båda stegen förklaras närmare i nästa avsnitt. I konsolfönstret (nederst högra hörnet som standard) ser du som standard en prompten med tre större än tecken, dvs gtgtgt. Detta visar att vi använder konsolen - i princip en vanlig Python tolk session (med lite extra funktionalitet från Spyder). I stället vill vi använda ett interaktivt Python-skal, kort IPython från ipython-projektet. För att göra detta, välj tolk - gt Öppna en IPython-konsol. Du bör se i det konsolska fönstret ett nytt skal visas och IPython prompt In 1: ska visas. Namnutrymmet kan rensas i IPython med hjälp av återställningskommandot. Skriv reset och tryck på Retur, bekräfta med y: Vi diskuterar det här lite längre, men du kan hoppa över följande om du inte är intresserad: Efter att ha utfärdat återställningskommandot borde vi bara ha några objekt definierade i namnet på den sessionen . Vi kan lista dem alla med kommandot dir (): Slutligen, om du gillar att hoppa över bekräftelsesteget för återställningskommandot, kan användningen använda återställningen - f istället för återställningen. Förutom syntaxen som verkställs av Python finns det ytterligare konventioner om källkods layout, särskilt Style Guide för Python-källkod vet som quotPEP8quot. Många Spyders-beteenden kan konfigureras genom sina inställningar. Om det här ligger i menyn beror på operativsystemet: På Windows och Linux, gå till Verktyg - för Inställningar på Mac OS, gå till Python - gt Inställningar Gå till Inställningar - hämta IPython-konsolen - gt Starta upp och välj kryssrutan bredvid Öppna en IPython-konsol vid uppstart. Klicka sedan på OK-knappen. Nästa gång Spyder startar, kommer den att visa IPython-konsolen automatiskt. Gå till Preferences - gt Editor - gt Code IntrospectionAnalysis och välj kryssrutan bredvid Style analysis (PEP8) För att undvika någon magi när konsolen startas, gå till Inställningar - gt Console - gt Avancerade inställningar - för PYTHONSTARTUP-ersättning och välj Standard PYTHONSTARTUP-skript (och starta om Spyder). (Den här magiken driver bland annat kommandot för kommande importdelning.) Standardinställningarna kan ändras för detta i nästa stora utgåva. För att undvika import av alla objekt från pylab och numpy till det aktuella namnutrymmet i IPython Console, gå till Preferences - gt IPython Console - gt Graphics och avmarkera kryssrutan bredvid Pylab och NumPy-moduler och välj även Aktivera support. Standardinställningarna kan ändras för detta i nästa stora utgåva. Genom Preferences - gt IPythons console - gt Avancerade inställningar - Använd Använd symbolisk matte kan vi aktivera IPythons symboliska python-läge. Detta kommer att möjliggöra snyggt återgiven sympyoutgång (latexstil) och importera också några sympyobjekt automatiskt när IPython-konsolen startar och rapporterar vad den har gjort. Vi kan då använda variablerna x. y. F5 exekverar den aktuella bufferten F9 exekverar den aktuella markerade bitkoden: Det här är mycket användbart för att uppdatera definitioner av funktioner (säg) i tolk sessionen utan att behöva springa hela filen igen CTRL ltRETURNgt exekverar den aktuella cellen ( menyn innehåller Run - gt Run-cell). En cell definieras som koden mellan två linjer som börjar med den överenskomna taggen. SHIFT ltRETURNgt exekverar den aktuella cellen och förflyttar markören till nästa cell (meny posten Run - gt Run cell och advance). Celler är användbara för att utföra ett stort filecodesegment i mindre enheter. (Det är lite som en cell i en IPython-anteckningsbok, eftersom bitar av kod kan köras oberoende.) ALT ltCURSOR UPgt flyttar den aktuella raden upp. Om flera rader markeras flyttas de upp tillsammans. ALTltCURSOR DOWNgt fungerar motsvarande flyttlinje (r) ner. Högerklickning på en funktionsmetod i källan öppnar ett nytt redigeringsfönster som visar definitionen av den funktionen. SHIFTCTRLALTM maximerar nuvarande fönster (eller ändrar storleken tillbaka till normal om den trycks in i ett maximerat fönster) SHIFTCTRLF aktiverar sökningen över alla filer. På Mac OS X: CMD ökar teckenstorleken i redigeraren, CMD - minska. Fungerar också i IPython Console. Stilsortsstorleken för objektutforskaren, Python-konsolen etc kan ställas in individuellt via Preferences - gt Objekt Explorer etc. Jag kunde inte hitta ett sätt att ändra teckensnittstorlek i variabel explorer. CTRLSPACE autocompletes kommandon, funktionsnamn, variabla namn, metoder som är mycket användbara. CMD-filer (på Mac OS X) och CTRL (annars) i redigeringsfönstret sparar filen som för närvarande redigeras. Detta tvingar också olika varningstrianglar i den vänstra kolumnen av redigeraren att uppdateras (annars uppdaterar de varannan sekund till 3 sekunder som standard). CMD-filer (på Mac OS X) och CTRL (annars) i IPython-konsolfönstret sparar den aktuella IPython-sessionen som en HTML-fil, inklusive eventuella siffror som kan visas inline. Detta är användbart som ett snabbt sätt att spela in vad som har gjorts i en session. (Det går inte att ladda den sparade posten igen i sessionen - om du behöver funktionalitet så här, leta efter IPython Notebook.) CMDi (på Mac OS X) och CTRLi (annars) när du trycker på medan markören är på ett objekt , öppnar dokumentation för objektet i objektinspektören. Det här är de inställningar som definierar hur koden i redigeraren körs om vi väljer Run - gt Run eller tryck F5. Som standard visas inställningsrutan första gången vi försöker utföra en fil. Om vi ​​vill ändra inställningarna när som helst kan de hittas under Run - gt Configure eller genom att trycka på F6. Det finns tre val för tolken att använda, varav jag diskuterar de två första. Låt oss anta att vi har ett program hello. py i redigeraren som läser Detta är standardförslaget, och det är också ett bra val. Välja Execute i nuvarande Python eller IPython tolk inställning under Run - gt Configure innebär att när exekveringen av hej. py är klar kan vi interagera med tolken som programmet körde och vi kan använda den praktiska IPython tolken för detta (snarare än standard Python tolk). Vi kan inspektera och interagera med objekt som utförandet av vårt program skapat, till exempel jag och hej (). Detta är generellt mycket användbart för inkrementell kodning, testning och felsökning: vi kan ringa hej () direkt från tolkprompten och behöver inte utföra hela hej. p.py för detta (även om vi ändrar funktionen hej () behöver vi för att utföra bufferten, eller åtminstone funktionsdefinitionen, för att göra den nya versionen av hej () synlig hos tolken antingen genom att utföra hela bufferten eller via Run - gt Run Selection.) Genomför dock koden i redigeraren i nuvarande tolk betyder också att koden som körs kan se andra (globala) objekt som definierades i tolkens session. Denna persistens av objekt glöms lätt och behövs vanligtvis inte när man arbetar med små program (även om det kan vara av stor värde ibland). Dessa objekt kan härröra från tidigare exekvering av kod, från interaktivt arbete i tolken eller från bekväm import till exempel från import av pylab (Spyder kan göra en del av den bekvämlighetsimporteringen automatiskt). Denna synlighet av objekt i tolkens globala namnrymd till koden vi kör kan också resultera i kodningsfel om koden oavsiktligt bygger på dessa objekt. Här är ett exempel: tänk på att vi kör koden hello. py. Därefter är variabeln i känd i tolken som en global variabel. vi ändrar hello. py källan och oavsiktligt raderar linjen jag 42 utför vi bufferten som innehåller hej. py igen. Vid denna punkt kommer inte hej (i) att misslyckas eftersom tolken har ett objekt med namn som jag definierat, även om det inte är definierat i källan till hej. py. Vid denna tidpunkt kunde vi spara hello. py och (falskt) tro att det skulle utföras korrekt. Om du kör det i en ny python tolk session (eller via python hello. py. Say) skulle det resultera i ett fel eftersom jag inte är definierad. Problemet uppstår eftersom koden använder ett objekt (här jag) utan att skapa det. Detta påverkar också import av moduler: om vi hade importerat pylab vid IPython-prompten så kommer vårt program att se det när den körs i denna IPython tolk sessionen. Om du vill veta hur vi kan dubbelklicka på att vår kod inte är beroende av sådana befintliga objekt, se Hur du dubbelklickar att koden exekveras korrekt anger sin egen kvot. Att välja Execute i en ny dedikerad Python tolk under Run - gt Configure startar en ny Python tolk varje gång programmet hello. py exekveras. Den stora fördelen med detta läge över Execute i nuvarande Python eller IPython tolk är att vi kan vara säkra på att det inte finns några globala objekt definierade i denna tolk som härrör från felsökning och upprepad exekvering av vår kod: varje gång vi kör koden i redigeraren , python tolken i vilken koden körs startas om. Detta är ett säkert alternativ, men ger mindre flexibilitet och kan inte använda IPyton-tolken. Förutsatt att du har valt för din kod att exekvera i nuvarande Python eller IPython tolk. då har du två alternativ för att kontrollera att vår kod fungerar själv (det vill säga det beror inte på odefinierade variabler, oimporterade moduler och kommandon etc.) Alternativt kan du använda IPythons magic reset om du vill stanna hos den nuvarande IPython tolken. kommando som kommer att ta bort alla objekt (som jag i exemplet ovan) från det aktuella namnsutrymmet och sedan köra koden i redigeraren. När du väl har fyllt i ett kodstycke, dubbelkolla att det körs självständigt med hjälp av ett av alternativen som förklaras i Hur du dubbelklickar din kod exekverar korrekt kvitton på egenkoden. När flera filer öppnas i redigeraren ordnas motsvarande flikar överst i fönstergruppen i alfabetisk ordning av filnamnet från vänster till höger. Till vänster om flikarna finns det som ikon som visar Browse flikar om musen svänger över den. Det är användbart att hoppa direkt till en viss fil om många filer är öppna. Miljövariabler kan visas i fönstret Console (nedre högra fönstret i standardlayout). Klicka på ikonen Alternativ (verktygstipset är Alternativ) och välj sedan Miljövariabler. All anpassning som sparas på disken kan återställas genom att ringa spyder från kommandoraden med switch-reset. dvs ett kommando som spyder-reset. Högerklicka på arrayer i variabel explorer ger alternativ att plotta och analysera dessa vidare. Dubbelklicka på ett ordlistorobjekt öppnar ett nytt fönster som visar ordlistan snyggt. Förmodligen finns det annan dold förmåga för vissa andra datatyper. Det finns några konventioner som antagits beträffande dokumentationssträngar skrivna i omstrukturerad text. Om vi ​​följer dessa riktlinjer kan vi få snyggt formaterade dokumentationssträngar i Spyder. Till exempel, för att få vår genomsnittliga () - funktion att se ut så här i Spyder Object Explorer: Vi behöver formatera dokumentationssträngen enligt följande. Vad betyder här är att ordet Parametrar används och understrykas. Linjen a. siffran visar att typen av parametern a är nummer. I nästa rad, som är indragad, kan vi skriva en mer utökad förklaring vad denna variabel representerar, vilka villkor de tillåtna typerna måste uppfylla, etc. Samma för alla parametrar, och även för det returnerade värdet. Det är ofta en bra idé att inkludera ett exempel som visas. Aktivering av debug-läget (Debug - gt Debug) startar IPython debugger (ipdb) i IPython-konsolen. Detta drivs som vanligt, men redigeringsdisplayfönstret lyfter fram linjen som ska utföras, och variabel explorer visar variabler i det aktuella sammanhanget för punkten för programkörning. (Den visar bara numeriska variabler, dvs inte funktionsobjekt etc.) Nyckelkommandon inom IPython debugger är indivduella tangenttryckningar: s till Steg i det aktuella uttalandet. Om det här är ett funktionssamtal, gå in i den funktionen. n gå till nästa uttalande. Om det aktuella uttalandet är en funktion, gå inte in i den funktionen, utan kör den helt innan du återvänder kontrollen till den interaktiva debuggerprompten. r slutföra alla uttalanden i den aktuella funktionen och Returnera från den funktionen innan du återgår kontrollen. p Print tillåter att visa värden för variabler, till exempel p x kommer att skriva ut värdet på variabeln x. Observera att i ipdb kan du också ändra värden på variabeln. Till exempel, för att ändra en valbar x. du kan säga ipdb gt x 42 och debuggeren fortsätter med att x är bunden till 42. Du kan också ringa funktioner och göra många andra saker. För att lämna debugging-läget kan du skriva ut eller välja från menyn Debug - gt Debugging Control - gt Exit I IPython-konsolen kan vi ringa debug rakt efter ett undantag har höjts: det här startar IPython debug mode och tillåter inspektion av lokala variabler vid den punkt där undantaget inträffade som beskrivits ovan. Det här är mycket effektivare än att lägga till utskriftsdeklarationer i koden och köra den igen. Om du använder det kan du också använda kommandona upp och ner som navigerar över inspektionspunkten upp och ner i stapeln. (Upp stapeln betyder att funktionerna som har ringt den aktuella funktionen nedåt är motsatt riktning.) Anta att vi använder en IPython-konsol med version gt 1.0.0, vi kan bestämma om siffror skapade med matplotlibpylab kommer att visa inline. dvs inuti IPython-konsolen, eller om de ska visas i ett nytt fönster. Alternativ 1 är bekvämt att spara en rekord av den interaktiva sessionen (avsnitt Genvägar för användbara funktioner visar en genväg för att spara IPython-konsolen till en html-fil). Alternativ 2 tillåter interaktivt att zooma in i figuren, manipulera det lite och spara siffran till olika filformat via menyn. Kommandot att få siffrorna att visas inline i IPython-konsolen är matplotlib inline. Kommandot att få siffror visas i sitt eget fönster (vilket tekniskt är en QT windown) är matplotlib qt. Spyder-inställningarna kan användas för att anpassa standardbeteendet (i synnerhet Preferences - gt IPython Console - gt Graphics - gt Aktivera support för att växla till inline-plottning). Senaste inlägg KategorierRelease Anteckningar 8 september 2016 Förbättringar Lägger till förutfyllningscheckbordstabeller för blaze core loader. Detta gör det möjligt för lastaren att mer effektivt vidarebefordra fylla data genom att capping det lägre datumet som det måste söka efter när du frågar data. Kontrollpunkterna ska ha nya deltagare (1276). Uppdaterad VagrantFile för att inkludera alla dev-krav och använda en nyare bild (1310). Låt korrelationer och regressioner beräknas mellan två 2D-faktorer genom att göra beräkningar asset-wise (1307). Filter har som standard gjorts windowsafe. Nu kan de vidarebefordras som argument till andra filter, faktorer och klassificerare (1338). Lades till en valfri groupby parameter till rang (). topp(). och botten (). (1349). Lades till nya pipelinefilter, allt och alla. som tar ett annat filter och returnerar True om en tillgång producerade en True för några dagar under de föregående fönsterlängdsdagarna (1358). Tillagde nytt pipelinefilter AtLeastN. som tar ett annat filter och en int N och returnerar True om en tillgång producerade True på N eller flera dagar under de föregående fönsterlängdsdagarna (1367). Använd externt bibliotek empiriskt för riskberäkningar. Empyrical förenar riskmetriska beräkningar mellan pyfolio och ziplin. Empyrical lägger till anpassade årliga alternativ för avkastning av anpassade frekvenser. (855) Lägg till Aroon faktor. (1258) Lägg till snabb stokastisk oscillatorfaktor. (1255) Lägg till en Dockerfil. (1254) Ny handelskalender som stöder sessioner som sträcker sig över midnatt, t. ex. 24 timmar 6:01 - 6:00 PM sessioner för terminshandel. zipline. utils. tradingcalendar är nu avskriven. (1138) (1312) Tillåt skivning av en enda kolumn ur en FactorFilterClassifier. (1267) Ge Ichimoku Cloud-faktor (1263) Tillåt standardparametrar på pipeline villkor. (1263) Ange förändringsfrekvensfaktor. (1324) Ge en linjärt vägd rörlig medelfaktor. (1325) Lägg till NotNullFilter. (1345) Tillåt att kapitaländringar definieras av ett målvärde. (1337) Lägg till TrueRange-faktor. (1348) Lägg till punkt i tidsuppslag till tillgångar. db. (1361) Gör cantrade medveten om tillgång8217s utbyte. (1346) Lägg till downsample-metoden för alla beräknade villkor. (1394) Lägg till QuantopianUSFuturesCalendar. (1414) Aktivera publicering av gamla assets. db versioner. (1430) Aktivera schemaläggningsfunktion för Futures trading kalender. (1442) Tillåta regressioner av längd 1. (1466) Experimentellt Lägg till stöd för kommande Future och Equity historia fönster, och aktivera andra Framtida dataåtkomst via dataportalen. (1435) (1432) Buggfixar ändringar AverageDollarVolume inbyggd faktor för att behandla saknade slut - eller volymvärden som 0. Tidigare avlägsnades NaNs enkelt före medelvärdet, vilket gav de återstående värdena för mycket vikt (1309). Ta bort riskfri ränta från beräkning av skarpt förhållande. Kvoten är nu genomsnittet av riskjusterad avkastning över kränkbarhet av justerad avkastning. (853) Sortino-förhållandet kommer att returnera beräkningen istället för np. nan när den erfordrade avkastningen är lika med noll. Kvoten returnerar nu genomsnittet av riskjusterad avkastning mot nedåtrisk. Fasta misslabeled API genom att konvertera mar till downsiderisk. (747) Risken för nackdelen returnerar nu kvadratroten av medelvärdet av skillnaderna i nackdelen. (747) Informationskvot uppdaterad för att returnera medelvärdet av riskjusterad avkastning över standardavvikelsen för riskjusterad avkastning. (1322) Alfa och sharpe-förhållandet är nu årlig. (1322) Fix enheter under läsning och skrivning av den dagliga baren firsttradingday attributet. (1245) Valfria leveransmoduler, när de saknas, orsakar inte längre en NameError. (1246) Behandla schematfunktionsargument som en tidsregel när en tidsregel, men ingen datumregel levereras. (1221) Skydda mot gränsvillkor vid början och slutdagen i schemalagd funktion. (1226) Använd justeringar till föregående dag när du använder historia med en frekvens på 1d. (1256) Fel snabbt på ogiltiga pipeline kolumner, istället för att försöka komma åt den obefintliga kolumnen. (1280) Fix AverageDollarVolume NaN hantering. (1309) Prestandaförbättringar till flaskkärnlastare. (1227) Tillåt samtidiga blåsfrågor. (1323) Förhindra att du saknar ledande bcolz-minutdata från att göra upprepade onödiga uppslag. (1451) Cache framtida kedjans uppslag. (1455) Underhåll och refactorings Ta bort återstående anmärkningar av addhistory. (1287) Dokumentation Lägg till testfixtur som källar dagligen prissättning data från minut prissättning data fixtures. (1243) Ändringar av dataformat BcolzDailyBarReader och BcolzDailyBarWriter använder handelskalenderinstans istället för handelsdagar serialiserade till JSON. (1330) Ändra format för assets. db för att stödja tidpunktsuppslag. (1361) Byt BcolzMinuteBarReaderand BcolzMinuteBarWriter för att stödja olika tikstorlekar. (1428) Release 1.0.1 Detta är en mindre buggfix-release från 1.0.0 och innehåller ett litet antal buggfixar och dokumentationsförbättringar. Förbättringar Tillagt stöd för användardefinierade kommissionsmodeller. Se zipline. financemissionmissionModel-klassen för mer information om genomförande av en kommissionsmodell. (1213) Tillagt stöd för icke-flytande kolumner till Blaze-backed Pipeline dataset (1201). Lades till zipline. pipeline. slice. Slice. en ny pipeline term som är utformad för att extrahera en enda kolumn från en annan term. Skivor kan skapas genom att indexera till en term, som anges av tillgången. (1267) Buggfixar Fixade ett fel där pipelastare inte initialiserades korrekt av zipline. runalgorithm (). Detta påverkar också invokationer av zipline-körning från CLI. Fixat en bugg som orsakade zipline IPython cell magi att misslyckas (533233fae43c7ff74abfb0044f046978817cb4e4). Fixat ett fel i PerTrade-kommissionens modell där provisionerna felaktigt tillämpades på varje delfyllning av en order i stället för själva ordern, vilket resulterade i att algoritmer belastades för mycket i provisioner vid beställning av stora order. PerTrade tillämpar nu korrekt provisioner per order (1213). Attributstillgångar på CustomFactors som definierar flera utgångar kommer nu att returnera en utmatningsskiva korrekt när utdata också är namnet på en faktormetod (1214). Replaced deprecated användning av pandas. io. data med pandasdatareader (1218). Fixade ett problem där. pyi-stubfiler för zipline. api uteslutes av misstag från PyPI-källfördelningen. Conda-användare ska vara opåverkade (1230). Dokumentation Lades till ett nytt exempel, zipline. examples. momentumpipeline. som utövar pipeline API (1230). Höjdpunkter Zipline 1.0 Rewrite (1105) Vi har omskrivit mycket Zipline och dess grundläggande begrepp för att förbättra runtime prestanda. Samtidigt introducerade we8217ve flera nya API. På en hög nivå drog tidigare versioner av Zipline-simuleringar från en multiplexerad datakälla, som slogs samman via heapq. Denna ström matades till huvudsimuleringsslingan och kör klockan framåt. Detta starka beroende av att läsa all data gjorde det svårt att optimera simuleringsprestanda eftersom det inte fanns någon koppling mellan mängden data som vi hämtade och mängden data som faktiskt användes av algoritmen. Nu hämtar vi bara data när algoritmen behöver det. En ny klass, DataPortal. skickar dataförfrågningar till olika datakällor och returnerar de begärda värdena. Detta gör runtime för en simuleringsskala mycket närmare med algoritmens komplexitet, snarare än med antalet tillgångar som tillhandahålls av datakällorna. I stället för dataströmmen som kör klockan, simuleras nu simuleringar genom en förberäknad uppsättning dag - eller minuttidstämplar. Tidstämplarna avges av MinuteSimulationClock och DailySimulationClock. och förbrukas av huvudslingan i transformen (). 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. t. ex. 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. Tack. 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