Thursday 24 August 2017

Pindah rata rata pylab


Spyder - IDE Python Mon 16 September 2013 Hans Fangohr. University of Southampton, Inggris, 2013 Spyder telah berkembang menjadi alat yang cukup matang dan sangat produktif disini saya mencoba memberikan tutorial. Dokumentasi ini dimotivasi oleh kursus pelatihan dengan metode Python dan pemodelan komputasi untuk siswa di University of Southampton (lihat catatan sejarah untuk detail lebih lanjut). Entri blog ini telah diintegrasikan ke dalam Spyder sebagai Tutorial. Setelah Spyder dimulai, versi tutorial yang paling mutakhir dapat ditemukan di tutorial Help - gt Spyder. Dapatkan file hello world ke dalam jendela editor Spyder dengan mendownload hello. py dan save as hello. py. (Anda mendownload file dengan mengklik kanan pada link di browser Anda, lalu pilih Save Target As atau Save Download as), lalu buka file hello. py melalui menu File, lalu pilih Open. Kami menyatakan ini sebagai File - gt Open secara singkat. Klik di hello. py untuk melihat kode sumber di webbrowser, lalu salin keseluruhan kode navigasi ke jendela editor di spyder dan paste kode. Kemudian simpan file tersebut sebagai hello. py. Untuk menjalankan program, pilih Run - gt Run (atau tekan F5), dan konfirmasikan pengaturan Run jika diperlukan. Anda harus melihat output seperti: atau (jalur tertentu akan bergantung pada tempat Anda menyimpan file, tapi ini disisipkan oleh Spyder secara otomatis): Jika demikian, Anda baru saja menjalankan program Python pertama - dilakukan dengan baik. Sebelum kita melanjutkan, silakan Konsol IPython bisa melakukan sedikit lebih banyak daripada konsol Python standar, dan kami menyarankan untuk menggunakannya sebagai konsol default di sini. Pada sesi penerjemah IPython yang baru saja kita mulai, Anda bisa menggunakan Run-gtRun (seperti sebelumnya) untuk mengeksekusi hello. py dan Anda harus melihat: Python membaca file baris demi baris, mengabaikan komentar saat menemukan kata kunci def, Tahu bahwa sebuah fungsi DEFined dalam baris ini dan berikutnya (satu atau lebih). Dalam file hello. py, Python menciptakan objek fungsi dengan nama halo. Semua garis indentasi berikut def halo (): milik badan fungsi. Perhatikan bahwa objek fungsi hanya dibuat pada titik ini di file, namun fungsinya belum disebut (yaitu tidak dieksekusi). Ketika Python menemukan perintah (selain def dan beberapa kata kunci lainnya) yang ditulis di kolom paling kiri, akan dilakukan dengan segera. Di file hello. py ini hanya garis baca hello () yang sebenarnya akan memanggil (yaitu mengeksekusi) fungsinya dengan nama halo. Jika Anda menghapus baris halo () dari program dan menjalankan keseluruhan file lagi (dengan menekan F5, atau memilih run - gt run), tidak ada yang akan dicetak (karena fungsi hello didefinisikan, namun tidak dipanggil, yaitu tidak dijalankan) . Sekarang Anda harus tahu cara menjalankan program Python yang ada di jendela editor di Spyder menggunakan Konsol Python, dan Konsol IPython yang lebih canggih. Jika Anda baru mulai belajar Python, ini mungkin bagus untuk kembali ke kursus buku teks Anda dan melihat contoh yang lebih mendasar. Bagian selanjutnya memberikan informasi lebih rinci bagaimana Anda dapat mengeksekusi bagian kode di editor di konsol Python, dan dengan demikian memperbaharui sebagian dari definisi Anda di editor. Ini adalah teknik yang lebih maju namun bisa sangat bermanfaat. (Anda juga mungkin tertarik pada pilihan untuk mengeksekusi potongan (disebut quotcellsquot) kode yang dipisahkan oleh pembatas - lihat Cara pintas untuk fungsi yang berguna.) Setelah Anda menjalankan program hello. py, objek fungsi hello didefinisikan Dan dikenal dengan perintah Python. Dengan demikian kita dapat memanggil fungsi dari prompt Python: Panggil fungsi halo () dari prompt Python, yaitu ketik halo () di jendela Python Shell (prompt Python menunjukkan sebagai gtgtgt. Atau sebagai In jika kita menggunakan sesi IPython dimana Tanda tanya bisa berupa bilangan bulat positif.), Dan tekan tombol kembali. Anda harus menemukan bahwa fungsi halo () dijalankan lagi, yaitu Hello World dicetak lagi. Fungsi panggilan Anda pada prompt Python bersamaan dengan keluarannya akan terlihat seperti ini: Dapatkah Anda melihat bagaimana ini berbeda dengan menjalankan keseluruhan program lagi Saat kita menjalankan keseluruhan program (dengan menekan F5), Python melewati file tersebut, menciptakan fungsi hello Objek (mengesampingkan objek sebelumnya), mencapai program utama dan memanggil fungsinya. Saat kita memanggil halo () dari prompt Python, kita hanya memanggil fungsi benda halo yang telah didefinisikan di konsol Python (saya) saat kita mengeksekusi seluruh file hello. py tadi (dengan menekan F5). Ini akan menjadi lebih jelas dari waktu ke waktu dan juga saat kita bekerja dengan contoh yang sedikit lebih besar. Anda mungkin ingin kembali ke tutorial ini pada tahap yang sedikit kemudian. Python menyediakan fungsi yang menampilkan semua objek yang diketahui (dalam ruang nama saat ini). Ini disebut dir (). Saat Anda mengetik dir () pada prompt, Anda mendapatkan daftar objek yang diketahui. Abaikan semuanya dimulai dengan garis bawah untuk saat ini. Dapatkah Anda melihat halo dalam daftar (Jika Anda mendapatkan daftar panjang objek yang telah ditentukan, maka Spyder mungkin telah melakukan beberapa kemudahan impor untuk Anda. Untuk mengatasi ini, Anda mungkin ingin: Kemudian jalankan dir () seperti yang disarankan di atas.) Sekali sebuah Objek terlihat di ruang nama saat ini (seperti halo dalam contoh ini), kita dapat menggunakan fungsi bantuan sebagai berikut untuk mempelajarinya: Ketik bantuan (halo) pada prompt Python, Anda harus melihat keluaran seperti ini: Di ​​mana Python Mengambil informasi dari Beberapa dari itu (seperti jumlah argumen masukan dan nama variabel di sini kita tidak memiliki argumen masukan) Python dapat menemukannya melalui pemeriksaan objeknya, informasi tambahan berasal dari string dokumentasi yang diberikan untuk objek fungsi halo. String dokumentasi adalah string pertama tepat di bawah garis def halo ():. Lingkungan Spyder juga menyediakan panel di pojok kanan atas (secara default) yang merupakan object inspector. Jika Anda mengetikkan hello ke baris kosong di jendela Object inspector, itu juga akan memberikan string bantuan. Di jendela Editor, ubah fungsi halo sehingga mencetak Good Bye World daripada Hello World. Tekan F5 (untuk menjalankan keseluruhan program) dan periksa apakah output programnya sekarang: Apa yang terjadi saat Anda menekan F5 adalah ini: Python telah melalui file hello. py dan membuat objek fungsi baru halo (mengesampingkan fungsi Objek halo yang telah kita definisikan sebelumnya) dan kemudian dieksekusi fungsinya. Kita harus memulai dengan keadaan yang jelas. Untuk melakukan ini, tolong ubah fungsi halo () kembali agar bisa mencetak Hello World (yaitu menggunakan file hello. py asli), lalu tekan F5 untuk menjalankan keseluruhan program dan periksa apakah itu mencetak Hello World. Panggil fungsi halo () dari command prompt (seperti yang dijelaskan pada Call fungsi objek yang ada dari command line). Anda harus melihat Hello World dicetak. Sekarang ubah definisi fungsi agar bisa mencetak Laters World. Dan simpan file (tapi jangan jalankan programnya, misal jangan tekan F5). Panggil fungsi halo () dari command prompt lagi. Anda harus menemukan bahwa teks yang dicetak berbunyi Hello World. Seperti di sini Mengapa begitu Karena fungsi halo objek dalam penerjemah Python adalah yang lama yang mencetak Hello World. Sejauh ini, kami telah mengubah file hello. py (dan menggantikan Hello World di sana bersama Laters World) di editor namun ini tidak mempengaruhi objek yang sebelumnya telah dibuat pada penerjemah Python. Berikut adalah dua kemungkinan untuk menggunakan versi modifikasi dari fungsi hello: Option 1: jalankan seluruh file hello. py lagi dengan menekan F5: ini akan menciptakan fungsi objek baru halo (dan menggantikan yang lama). Anda harus menemukan bahwa jika Anda menekan F5, lalu memanggil halo () pada prompt, teks baru Laters World dicetak. Opsi 2: pilih daerah yang telah Anda ubah (dalam hal ini seluruh fungsi hello mulai dari garis def hello (): turun untuk kembali None dan pilih Run - gt Run selection Ini akan mengupdate objek hello di interpreter Tanpa harus mengeksekusi seluruh file hello. py: Jika kita sekarang mengetikkan hello () kita melihat respon update: Kemampuan untuk mengeksekusi bagian kode untuk memperbarui beberapa objek dalam interpreter (pada contoh di atas, kita memperbarui fungsi Objek halo), sangat berguna saat mengembangkan dan debug kode yang lebih kompleks, dan saat membuat objectdata dalam sesi interpreter membutuhkan waktu. Misalnya, dengan memodifikasi hanya fungsi (atau classesobjects, dll) yang sebenarnya kita kembangkan atau debugging, kita Dapat terus menggunakan kembali struktur data dll yang didefinisikan dalam sesi interpreter. Untuk mengajarkan pemrograman Python dan pemodelan komputasi, kami merekomendasikan untuk (i) menggunakan IPython alih-alih juru bahasa Python yang normal dan (ii) tidak menggunakan kemudahan impor apapun. Dia menerima IPython sebagai standar de facto dan membantu untuk lebih memahami ruang nama. Spyder mencoba untuk membantu pengguna yang lebih mahir dengan mengimpor sejumlah modul ke dalam ruang nama utama. Ketik ilmiah di command prompt untuk melihat detilnya. Perilaku ini bisa berubah dalam rilis Spyder di masa depan. Sementara kemudahan impor ini sangat berguna bagi pemrogram yang lebih berpengalaman, mereka bisa membingungkan (jika tidak menyesatkan) untuk pemula. Dengan demikian kami merekomendasikan untuk membatalkan impor ini untuk memenuhi persyaratan kami di atas dan untuk (i) beralih ke konsol IPython. Dan (ii) mengeluarkan perintah reset untuk mereset ruang nama. Kedua langkah tersebut dijelaskan secara lebih rinci pada bagian selanjutnya. Di jendela konsol (sudut kanan bawah secara default), Anda melihat secara default sebuah prompt dengan tiga tanda lebih besar, yaitu gtgtgt. Ini menunjukkan bahwa kita menggunakan konsol - pada dasarnya sesi juru bahasa Python normal (dengan beberapa fungsi tambahan dari Spyder). Sebagai gantinya, kami ingin menggunakan shell Python Interaktif, IPython pendek dari proyek ipython. Untuk melakukan ini, pilih Interpreters - gt Buka Konsol IPython. Anda harus melihat di jendela konsol shell baru muncul, dan IPython prompt Dalam 1: harus ditampilkan. Ruang nama dapat dihapus di IPython dengan menggunakan perintah reset. Ketik reset dan tekan kembali, lalu konfirmasikan dengan y: Kami membahasnya sedikit lebih jauh, tapi Anda bisa melewatkan yang berikut jika Anda tidak tertarik: Setelah mengeluarkan perintah reset, kita hanya boleh memiliki beberapa objek yang didefinisikan di ruang nama sesi itu. . Kita bisa daftar semuanya menggunakan perintah dir (): Akhirnya, jika Anda ingin melewatkan langkah konfirmasi dari perintah reset, gunakan dapat menggunakan reset - f alih-alih reset. Selain Sintaks yang ditegakkan oleh Python, ada konvensi tambahan mengenai tata letak kode sumber, khususnya Panduan Gaya untuk kode sumber Python yang dikenal sebagai quotPEP8quot. Banyak perilaku Spyders dapat dikonfigurasi melalui Preferensinya. Dimana letaknya di menu tergantung pada sistem operasi Anda: Pada Windows dan Linux, masuk ke Tools - gt Preferences Pada Mac OS, masuk ke Preferensi Python - gt Masuk ke Preferences - gt IPython console - gt Startup dan pilih tickbox di sebelahnya. Buka konsol IPython saat startup. Kemudian klik tombol OK. Waktu berikutnya Spyder dimulai, ia akan menunjukkan konsol IPython secara otomatis. Buka Preferences - gt Editor - gt Code IntrospectionAnalysis dan pilih kotak centang di samping Analisis gaya (PEP8) Untuk menghindari sihir saat konsol dimulai, masuk ke Preferences - gt Console - gt Advanced Settings - gt PYTHONSTARTUP replacement dan pilih Default PYTHONSTARTUP script (Dan restart Spyder). (Ini sihir, antara lain, menjalankan perintah pembagian impor di masa depan.) Pengaturan default mungkin berubah untuk ini dalam rilis besar berikutnya. Untuk menghindari impor semua benda dari pylab dan numpy ke dalam ruang nama saat ini di Konsol IPython, masuk ke Preferences - gt IPython console - gt Graphics dan hapus centang pada kotak centang di samping Secara otomatis memuat modul Pylab dan NumPy dan hapus juga Aktifkan dukungan. Pengaturan default mungkin berubah untuk ini dalam rilis utama berikutnya. Melalui Preferensi - gt konsol IPython - gt Pengaturan Lanjutan - g Gunakanlah simbolis matematika kita bisa mengaktifkan mode python simbolis IPythons. Ini akan memungkinkan output simpy yang bagus (gaya lateks) dan juga mengimpor beberapa benda simetris secara otomatis saat konsol IPython dimulai, dan melaporkan apa yang telah dilakukan. Kita kemudian bisa menggunakan variabel x. Y. Sebagai contoh seperti ini: F5 mengeksekusi buffer F9 saat ini menjalankan potongan kode yang saat ini disorot: ini sangat berguna untuk memperbarui definisi fungsi (katakanlah) di sesi interpreter tanpa harus menjalankan keseluruhan file lagi CTRL ltRETURNgt mengeksekusi sel saat ini ( Menu enty Run - gt Run cell). Sel didefinisikan sebagai kode antara dua baris yang dimulai dengan tag yang disepakati. SHIFT ltRETURNgt menjalankan sel saat ini dan memajukan kursor ke sel berikutnya (entri menu Run - gt Run cell and advance). Sel berguna untuk mengeksekusi segmen filecode besar di unit yang lebih kecil. (Ini seperti sebuah sel di notebook IPython, dalam potongan kode itu bisa dijalankan secara independen.) ALT ltCURSOR UPgt menggerakkan garis saat ini. Jika banyak baris disorot, mereka akan dipindahkan bersama. ALTltCURSOR DOWNgt bekerja dengan cara memindahkan garis ke bawah. Dengan mengklik kanan pada metode fungsi di sumbernya, buka jendela editor baru yang menunjukkan definisi fungsi itu. SHIFTCTRLALTM memaksimalkan jendela saat ini (atau mengubah ukurannya kembali normal jika ditekan di jendela yang dimaksimalkan) SHIFTCTRLF mengaktifkan pencarian di semua file. Pada Mac OS X: CMD akan meningkatkan ukuran font editor, CMD - menurun. Juga bekerja di Konsol IPython. Ukuran font untuk explorer objek, konsol Python dll dapat diatur secara individual melalui Preferences - gt Object explorer dll. Saya tidak dapat menemukan cara untuk mengubah ukuran font pada variabel explorer. Perintah autocompletes CTRLSPACE, nama fungsi, nama variabel, metode yang sangat berguna. CMD (pada Mac OS X) dan CTRLs (jika tidak) di jendela editor menyimpan file yang saat ini sedang diedit. Ini juga memaksa berbagai segitiga peringatan di kolom kiri editor untuk diperbarui (jika tidak mereka memperbarui setiap 2 sampai 3 detik secara default). CMDs (di Mac OS X) dan CTRLs (jika tidak) di jendela konsol IPython akan menghemat sesi IPython saat ini sebagai file HTML, termasuk gambar yang mungkin ditampilkan sebaris. Ini berguna sebagai cara cepat merekam apa yang telah dilakukan dalam sebuah sesi. (Tidak mungkin memuat catatan tersimpan ini kembali ke sesi - jika Anda memerlukan fungsionalitas seperti ini, cari Notebook IPython.) CMDi (di Mac OS X) dan CTRLi (jika tidak) saat ditekan saat kursor berada pada objek. , Membuka dokumentasi untuk objek itu di inspektur objek. Ini adalah pengaturan yang menentukan bagaimana kode di editor dijalankan jika kita memilih Run - gt Run atau tekan F5. Secara default, kotak setting akan muncul pertama kali kita mencoba mengeksekusi sebuah file. Jika kita ingin mengubah pengaturan pada waktu lain, mereka dapat ditemukan di bawah Run - gt Configure atau dengan menekan F6. Ada tiga pilihan bagi juru bahasa untuk digunakan, yang mendiskusikan pertama dari dua topik tersebut. Mari kita asumsikan kita memiliki program hello. py di editor yang berbunyi ini adalah saran default, dan umumnya juga pilihan yang bagus. Memilih Execute dalam pengaturan juru bahasa Python atau IPython saat ini di bawah Run - gt Configure berarti bahwa Ketika eksekusi hello. py selesai, kita dapat berinteraksi dengan penerjemah di mana program berjalan, dan kita dapat menggunakan penerjemah IPython yang mudah digunakan untuk hal ini (bukan Daripada juru bahasa Python default). Kita bisa memeriksa dan berinteraksi dengan objek yang pelaksanaan program kita buat, seperti i dan halo (). Hal ini umumnya sangat berguna untuk pengkodean, pengujian dan debugging inkremental: kita bisa memanggil halo () langsung dari juru bahasa, dan tidak perlu melakukan keseluruhan hello. py untuk ini (walaupun jika kita mengubah fungsi halo (). Untuk mengeksekusi buffer, atau paling tidak definisi fungsi, untuk membuat versi baru dari halo () terlihat di interpreter baik dengan mengeksekusi seluruh buffer atau melalui Run - gt Run Selection.) Namun, jalankan kode editor di Penerjemah saat ini juga berarti bahwa kode yang dijalankan dapat melihat objek (global) lainnya yang didefinisikan dalam sesi interpreter. Ketekunan benda ini mudah dilupakan dan biasanya tidak diperlukan saat mengerjakan program kecil (meski terkadang bisa sangat bernilai). Benda-benda ini bisa berasal dari eksekusi kode sebelumnya, dari kerja interaktif di juru bahasa, atau dari kemudahan impor seperti dari impor pylab (Spyder dapat melakukan beberapa kemudahan impor secara otomatis). Visibilitas objek dalam ruang nama penafsir global terhadap kode yang kita eksekusi juga dapat mengakibatkan kesalahan pengkodean jika kode tersebut secara tidak sengaja bergantung pada objek ini. Inilah contohnya: bayangkan kita menjalankan kode hello. py. Selanjutnya, variabel i diketahui dalam interpreter sebagai variabel global. Kita edit sumber hello. py dan tanpa sengaja menghapus baris i 42 kita jalankan buffer yang mengandung hello. py lagi. Pada titik ini, panggilan halo (i) tidak akan gagal karena penafsir memiliki objek nama yang saya definisikan, walaupun hal ini tidak didefinisikan dalam sumber hello. py. Pada titik ini, kita bisa menyelamatkan hello. py dan (salah) mengira itu akan berjalan dengan benar. Namun, menjalankannya di sesi juru bahasa python baru (atau melalui python hello. py) akan menghasilkan kesalahan, karena saya tidak didefinisikan. Masalahnya muncul karena kode tersebut menggunakan objek (disini i) tanpa membuatnya. Ini juga mempengaruhi pengimporan modul: jika kita mengimpor pylab pada prompt IPython, maka program kita akan melihat bahwa ketika dijalankan dalam sesi juru bahasa IPython ini. Untuk mempelajari bagaimana kita dapat memeriksa ulang bahwa kode kita tidak bergantung pada objek yang ada, lihat Bagaimana cara mengecek kode Anda dengan benar dengan mengklik kuota sendiri. Memilih Execute di penerjemah Python khusus baru di bawah Run - gt Configure akan memulai penerjemah Python baru setiap kali program hello. py dijalankan. Keuntungan utama dari mode ini melebihi Execute pada penerjemah Python atau IPython saat ini adalah bahwa kita dapat yakin bahwa tidak ada objek global yang didefinisikan dalam penerjemah ini yang berasal dari debugging dan eksekusi kode berulang-ulang: setiap kali kita menjalankan kode di editor , Penerjemah python di mana kode berjalan di-restart. Ini adalah pilihan yang aman, namun kurang memberi fleksibilitas dan tidak bisa menggunakan penerjemah IPyton. Dengan asumsi Anda telah memilih kode Anda untuk Execute pada juru bahasa Python atau IPython saat ini. Maka Anda dua pilihan untuk memeriksa bahwa kode kita bekerja dengan sendirinya (yaitu tidak tergantung pada variabel yang tidak terdefinisi, modul dan perintah yang tidak ada duanya) Atau, jika Anda ingin tinggal dengan penerjemah IPython saat ini, Anda dapat menggunakan IPythons magic reset Perintah yang akan menghapus semua objek (seperti i pada contoh di atas) dari ruang nama saat ini, dan kemudian jalankan kode di editor. Setelah Anda menyelesaikan sebuah kode, periksa kembali apakah ia dijalankan secara independen dengan menggunakan salah satu opsi yang dijelaskan di Bagaimana cara memeriksa ulang kode Anda dengan benar dengan kuota kuota sendiri. Saat beberapa file dibuka di editor, tab yang sesuai di bagian atas area jendela disusun menurut abjad dari nama file dari kiri ke kanan. Di sebelah kiri tab, ada ikon yang menunjukkan tab Browse jika mouse melayang di atasnya. Hal ini berguna untuk melompat ke file tertentu secara langsung, jika banyak file terbuka. Variabel lingkungan dapat ditampilkan dari jendela Console (jendela kanan bawah dalam layout default). Klik ikon Opsi (tooltip adalah Opsi), lalu pilih Variabel lingkungan. Semua kustomisasi yang tersimpan pada disk dapat diatur ulang dengan memanggil spyder dari baris perintah dengan tombol --reset. Yaitu sebuah perintah seperti spyder --reset. Mengklik kanan pada array pada variabel explorer memberi opsi untuk merencanakan dan menganalisa lebih lanjut. Mengklik dua kali pada objek kamus akan membuka jendela baru yang menampilkan kamus dengan baik. Agaknya ada kemampuan tersembunyi lainnya untuk beberapa tipe data lainnya. Ada beberapa konvensi yang diasumsikan mengenai dokumentasi string yang ditulis dalam teks yang direstrukturisasi. Jika kita mengikuti panduan tersebut, kita bisa mendapatkan string dokumentasi formatif yang indah di Spyder. Misalnya, untuk mendapatkan fungsi rata-rata () kita terlihat seperti ini di penjelajah Objek Spyder: Kita perlu memformat string dokumentasi sebagai berikut Apa yang penting di sini, apakah kata Parameter digunakan, dan digarisbawahi. Garis a. Nomor menunjukkan bahwa jenis parameter a adalah angka. Pada baris berikutnya, yang menjorok, kita dapat menulis penjelasan yang lebih panjang mengenai variabel apa yang ada, kondisi apa yang harus dipenuhi oleh tipe yang diijinkan dll. Sama untuk semua Parameter, dan juga untuk nilai yang dikembalikan. Seringkali merupakan ide bagus untuk memasukkan contoh seperti yang ditunjukkan. Mengaktifkan mode debug (Debug - gt Debug) memulai debugger IPython (ipdb) di konsol IPython. Ini dioperasikan seperti biasa, tapi jendela tampilan editor menyoroti garis yang akan dieksekusi, dan variabel explorer menampilkan variabel dalam konteks saat ini dari titik eksekusi program. (Ini hanya menampilkan variabel numerik, yaitu bukan fungsi objek dll.) Perintah utama dalam debugger IPython adalah penekanan tombol indivdual: s untuk melangkah ke pernyataan saat ini. Jika ini adalah fungsi panggilan, masuk ke fungsi itu. N pindah ke pernyataan Next. Jika pernyataan saat ini adalah sebuah fungsi, jangan masuk ke fungsi itu, tapi jalankan sepenuhnya sebelum mengembalikan kontrol ke prompt debugger interaktif. R melengkapi semua pernyataan dalam fungsi saat ini dan Kembali dari fungsi itu sebelum mengembalikan kontrol. P Print memungkinkan untuk menampilkan nilai variabel, misalnya p x akan mencetak nilai dari variabel x. Perhatikan bahwa di ipdb, Anda juga bisa mengubah nilai variabel. Misalnya, untuk memodifikasi x yang sesuai. Anda bisa mengatakan ipdb gt x 42 dan debugger akan menyala dengan x terikat ke 42. Anda juga bisa memanggil fungsi, dan melakukan banyak hal lainnya. Untuk meninggalkan mode debugging, Anda bisa mengetik exit atau memilih dari menu Debug - gt Debugging Control - gt Exit Di konsol IPython, kita bisa memanggil debug langsung setelah pengecualian telah diajukan: ini akan memulai mode debug IPython, dan memungkinkan Pemeriksaan variabel lokal pada titik di mana pengecualian terjadi seperti yang dijelaskan di atas. Ini jauh lebih efisien daripada menambahkan laporan cetak ke kode yang menjalankannya lagi. Jika Anda menggunakan ini, Anda mungkin juga ingin menggunakan perintah di atas dan ke bawah yang menavigasi titik inspeksi ke atas dan ke bawah tumpukan. (Up the stack berarti fungsi yang disebut fungsi saat ini turun adalah arah yang berlawanan.) Dengan asumsi kita menggunakan konsol IPython dengan versi gt 1.0.0, kita dapat memutuskan apakah gambar yang dibuat dengan matplotlibpylab akan tampil inline. Yaitu di dalam konsol IPython, atau apakah seharusnya muncul di jendela baru. Opsi 1 mudah untuk menyimpan rekaman sesi interaktif (bagian Shortcuts untuk fungsi yang berguna mencantumkan shortcut untuk menyimpan konsol IPython ke file html). Opsi 2 memungkinkan untuk secara interaktif memperbesar gambar, memanipulasinya sedikit, dan menyimpan gambar ke format file yang berbeda melalui menu. Perintah untuk mendapatkan figur yang muncul inline di konsol IPython adalah matplotlib inline. Perintah untuk mendapatkan gambar muncul di jendela mereka sendiri (yang secara teknis adalah windown QT) adalah matplotlib qt. Preferensi Spyder dapat digunakan untuk menyesuaikan perilaku default (khususnya Preferences - gt IPython Console - gt Graphics - gt Activate Support untuk beralih ke inline plotting). Recent Posts CategoriesRelease Notes 8 September 2016 Perangkat tambahan Menambahkan tabel pos pemeriksaan isi ulang untuk loader inti blaze. Hal ini memungkinkan loader untuk lebih efisien meneruskan mengisi data dengan membatasi tanggal yang lebih rendah yang harus dicari saat query data. Pos pemeriksaan harus memiliki delta baru yang diterapkan (1276). Diperbarui VagrantFile untuk menyertakan semua persyaratan dev dan menggunakan gambar yang lebih baru (1310). Izinkan korelasi dan regresi yang akan dihitung antara dua faktor 2D dengan melakukan penghitungan aset-bijaksana (1307). Filter telah dibuat windowsafe secara default. Sekarang mereka bisa dilewatkan sebagai argumen pada Filter, Faktor dan Klasifikasi lainnya (1338). Menambahkan parameter groupby opsional ke peringkat (). puncak(). Dan bawah (). (1349). Ditambahkan filter pipa baru, Semua dan Any. Yang mengambil filter dan pengembalian yang lain Benar jika aset menghasilkan True untuk setiap hari di windowlength days sebelumnya (1358). Ditambahkan filter pipa baru AtLeastN. Yang mengambil filter lain dan int N dan mengembalikan True jika sebuah aset menghasilkan True on N atau lebih hari di windowlength days sebelumnya (1367). Gunakan kalkulator perpustakaan eksternal untuk perhitungan risiko. Empiris menyatukan perhitungan metrik risiko antara pyfolio dan zipline. Empiris menambahkan pilihan anualisasi kustom untuk mengembalikan frekuensi khusus. (855) Tambahkan faktor Aroon. (1258) Tambahkan faktor osilator stochastic cepat. (1255) Tambahkan Dockerfile. (1254) Kalender perdagangan baru yang mendukung sesi yang berlangsung sepanjang malam, mis. 24 jam 6:01 PM-6:00PM sesi untuk perdagangan berjangka. Zipline. utils. tradingcalendar sekarang tidak berlaku lagi. (1138) (1312) Izinkan mengiris kolom tunggal dari FactorFilterClassifier. (1267) Sediakan faktor Ichimoku Cloud (1263) Izinkan parameter default pada istilah Pipeline. (1263) Memberikan tingkat perubahan persentase faktor. (1324) Memberikan faktor bobot bergerak tertimbang linear. (1325) Tambahkan NotNullFilter. (1345) Izinkan perubahan modal didefinisikan oleh nilai target. (1337) Tambahkan faktor TrueRange. (1348) Tambahkan pencarian waktu ke aset. db. (1361) Buat kantin tahu tentang pertukaran aset. (1346) Tambahkan metode undian ke semua persyaratan yang dapat dihitung. (1394) Tambahkan QuantopianUSFuturesCalendar. (1414) Aktifkan penerbitan versi asset. db lama. (1430) Aktifkan schedulefunction untuk kalender perdagangan Futures. (1442) Larang regresi dengan panjang 1. (1466) Percobaan Menambahkan dukungan untuk jendela sejarah Future and Equity yang akan datang, dan memungkinkan akses data Masa Depan lainnya melalui portal data. (1435) (1432) Perbaikan Bug Perubahan Faktor AverageDollarVolume built-in untuk mengobati nilai tutup atau volume yang hilang sebagai 0. Sebelumnya, NaNs hanya dibuang sebelum rata-rata, sehingga nilai sisanya terlalu banyak (1309). Hapus rasio bebas risiko dari perhitungan rasio sharpe. Rasio sekarang rata-rata pengembalian disesuaikan risiko atas pelanggaran pengembalian disesuaikan. (853) Sortino ratio akan mengembalikan perhitungan bukan np. nan bila tingkat pengembalian yang diminta sama dengan nol. Rasio ini sekarang mengembalikan rata-rata tingkat pengembalian yang disesuaikan risiko atas risiko penurunan. Fixed mislabeled API dengan mengubah mar menjadi downsiderisk. (747) Risiko kebelakang sekarang mengembalikan akar kuadrat rata-rata jatah perbedaan sisi bawah. (747) Rasio informasi diperbaharui dengan rata-rata pengembalian risiko yang disesuaikan dengan standar deviasi pengembalian disesuaikan risiko. (1322) Rasio alfa dan sharpe sekarang disetahunkan. (1322) Memperbaiki unit saat membaca dan menulis atribut firsttradingday bar pertama. (1245) Modul pengiriman opsional, bila hilang, tidak lagi menyebabkan NameError. (1246) Perlakukan argumen schedulefunction sebagai aturan waktu bila aturan waktu, namun tidak ada aturan tanggal yang diberikan. (1221) Melindungi terhadap kondisi batas pada awal dan akhir hari perdagangan dalam fungsi jadwal. (1226) Terapkan penyesuaian pada hari sebelumnya bila menggunakan riwayat dengan frekuensi 1d. (1256) Gagal cepat pada kolom pipa tidak benar, alih-alih mencoba mengakses kolom yang tidak ada. (1280) Perbaiki penanganan CaNN AverageDollarVolume. (1309) Peningkatan kinerja blaze core loader. (1227) Izinkan kuncian api bersamaan. (1323) Mencegah hilangnya data bcolz menit terdahulu dari melakukan pencarian berulang kali yang tidak perlu. (1451) Cache pencarian rantai masa depan. (1455) Pemeliharaan dan Refactorings Dihapus sisa menyebutkan addhistory. (1287) Dokumentasi Tambahkan perlengkapan uji yang menghasilkan data harga harian dari perlengkapan data harga menit. (1243) Format Data Perubahan BcolzDailyBarReader dan BcolzDailyBarWriter menggunakan contoh kalender perdagangan, bukan hari dagang yang disambung ke JSON. (1330) Mengubah format aset. db untuk mendukung pencarian dalam waktu tertentu. (1361) Ubah BcolzMinuteBarReader dan BcolzMinuteBarWriter untuk mendukung berbagai ukuran kutu. (1428) Versi 1.0.1 Ini adalah rilis bug fix minor dari 1.0.0 dan mencakup sejumlah kecil perbaikan bug dan perbaikan dokumentasi. Enhancements Menambahkan dukungan untuk model komisi yang ditentukan pengguna. Lihat kelas zipline. financemissionmissionModel untuk rincian lebih lanjut tentang penerapan model komisioning. (1213) Menambahkan dukungan untuk kolom non-float ke dataset Pipeline yang didukung Blaze (1201). Ditambahkan zipline. pipeline. slice. Slice. Istilah pipa baru yang dirancang untuk mengekstrak satu kolom dari istilah lain. Irisan dapat dibuat dengan cara mengindeks ke dalam sebuah istilah, dikodekan oleh aset. (1267) Perbaikan Bug Memperbaiki bug di mana pemuat pipa tidak diinisialisasi dengan benar oleh zipline. runalgorithm (). Hal ini juga mempengaruhi seruan zipline yang dijalankan dari CLI. Memperbaiki bug yang menyebabkan sel saraf zipline IPython gagal (533233fae43c7ff74abfb0044f046978817cb4e4). Memperbaiki bug dalam model komisi PerTrade dimana komisi salah diterapkan pada setiap pengisian parsial pesanan dan bukan pada pesanan itu sendiri, sehingga algoritma dibebankan terlalu banyak dalam komisi saat menempatkan pesanan besar. PerTrade sekarang menerapkan komisi secara per-order secara benar (1213). Akses atribut pada CustomFactor yang menentukan beberapa keluaran sekarang akan mengembalikan irisan output dengan benar saat output juga merupakan nama metode Factor (1214). Menggantikan penggunaan pandas. io. data yang tidak berlaku lagi dengan pandasdatareader (1218). Memperbaiki masalah di mana file berhala. pyi untuk zipline. api secara tidak sengaja dikecualikan dari distribusi sumber PyPI. Pengguna Conda seharusnya tidak terpengaruh (1230). Dokumentasi Menambahkan contoh baru, zipline. examples. momentumpipeline. Yang melatih Pipeline API (1230). Highlight Zipline 1.0 Rewrite (1105) Kami telah menulis ulang banyak Zipline dan konsep dasarnya untuk meningkatkan kinerja runtime. Pada saat bersamaan, kami memperkenalkan beberapa API baru. Pada tingkat tinggi, versi sebelumnya dari simulasi Zipline ditarik dari sumber data multiplexing, yang digabungkan melalui heapq. Aliran ini diumpankan ke loop simulasi utama, menggerakkan jam ke depan. Ketergantungan yang kuat pada membaca semua data membuat sulit untuk mengoptimalkan kinerja simulasi karena tidak ada hubungan antara jumlah data yang kita isi dan jumlah data yang sebenarnya digunakan oleh algoritma. Sekarang, kita hanya mengambil data saat algoritma membutuhkannya. Kelas baru, DataPortal. Mengirimkan permintaan data ke berbagai sumber data dan mengembalikan nilai yang diminta. Hal ini membuat runtime skala simulasi lebih dekat dengan kompleksitas algoritma, bukan dengan jumlah aset yang disediakan oleh sumber data. Alih-alih arus data yang menggerakkan jam, sekarang simak iterasi melalui rangkaian cap waktu hari atau menit yang telah dihitung sebelumnya. Cap waktu dipancarkan oleh MinuteSimulationClock dan DailySimulationClock. Dan dikonsumsi oleh lingkaran utama dalam transformasi (). 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. misalnya 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. Terima kasih. 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