NumPy 3rd Edition Build efficient high speed programs using the high performance NumPy mathematical library

by Ivan Idris

NumPy 3rd Edition Build efficient high speed programs using the high performance NumPy mathematical library Build efficient high speed programs using the high performance NumPy mathematical library

Publisher :

Author : Ivan Idris

ISBN : 9781785281969

Year : 2015

Language: en

File Size : 22.11 MB

Category : Computers Technology



NumPy Beginner's Guide
Third Edition

Build efficient, high-speed programs using the
high-performance NumPy mathematical library

Ivan Idris

BIRMINGHAM - MUMBAI



NumPy Beginner's Guide
Third Edition

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly
or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: November 2011
Second edition: April 2013
Third edition: June 2015

Production reference: 1160615

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-196-9
www.packtpub.com



Credits
Author

Project Coordinator

Ivan Idris

Shweta H. Birwatkar

Reviewers

Proofreader

Alexandre Devert

Safis Editing

Davide Fiacconi
Indexer

Ardo Illaste

Rekha Nair

Commissioning Editor

Graphics

Amarabha Banerjee

Sheetal Aute
Jason Monteiro

Acquisition Editors
Shaon Basu

Production Coordinator

Usha Iyer

Aparna Bhagat

Rebecca Youe
Content Development Editor
Neeshma Ramakrishnan

Cover Work
Aparna Bhagat

Technical Editor
Rupali R. Shrawane
Copy Editors
Charlotte Carneiro
Vikrant Phadke
Sameen Siddiqui



About the Author
Ivan Idris has an MSc in experimental physics. His graduation thesis had a strong emphasis

on applied computer science. After graduating, he worked for several companies as a Java
developer, data warehouse developer, and QA Analyst. His main professional interests are
business intelligence, big data, and cloud computing. Ivan enjoys writing clean, testable
code and interesting technical articles. He is the author of NumPy Beginner's Guide, NumPy
Cookbook, Learning NumPy Array, and Python Data Analysis. You can find more information
about him and a blog with a few examples of NumPy at http://ivanidris.net/
wordpress/.
I would like to take this opportunity to thank the reviewers and the team
at Packt Publishing for making this book possible. Also thanks go to my
teachers, professors, colleagues, Wikipedia contributors, Stack Overflow
contributors, and other authors who taught me science and programming.
Last but not least, I would like to acknowledge my parents, family, and
friends for their support.



About the Reviewers
Davide Fiacconi is completing his PhD in theoretical astrophysics from the Institute for

Computational Science at the University of Zurich. He did his undergraduate and graduate
studies at the University of Milan-Bicocca, studying the evolution of collisional ring galaxies
using hydrodynamic numerical simulations. Davide's research now focuses on the formation
and coevolution of supermassive black holes and galaxies, using both massively parallel
simulations and analytical techniques. In particular, his interests include the formation of the
first supermassive black hole seeds, the dynamics of binary black holes, and the evolution of
high-redshift galaxies.

Ardo Illaste is a data scientist. He wants to provide everyone with easy access to data for

making major life and career decisions. He completed his PhD in computational biophysics,
prior to fully delving into data mining and machine learning. Ardo has worked and studied in
Estonia, the USA, and Switzerland.



www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
‹‹

Fully searchable across every book published by Packt

‹‹

Copy and paste, print, and bookmark content

‹‹

On demand and accessible via a web browser

Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.







I dedicate this book to my aunt Lies who recently passed away. Rest in peace.





Table of Contents
Preface ix
Chapter 1: NumPy Quick Start
1
Python 1
Time for action – installing Python on different operating systems
2
The Python help system
3
Time for action – using the Python help system
3
Basic arithmetic and variable assignment
4
Time for action – using Python as a calculator
4
Time for action – assigning values to variables
5
The print() function
6
Time for action – printing with the print() function
6
Code comments
7
Time for action – commenting code
7
The if statement
8
Time for action – deciding with the if statement
8
The for loop
9
Time for action – repeating instructions with loops
9
Python functions
11
Time for action – defining functions
11
Python modules
12
Time for action – importing modules
12
NumPy on Windows
13
Time for action – installing NumPy, matplotlib, SciPy, and IPython on Windows
13
NumPy on Linux
15
Time for action – installing NumPy, matplotlib, SciPy, and IPython on Linux
15
NumPy on Mac OS X
16
Time for action – installing NumPy, SciPy, matplotlib, and IPython with
MacPorts or Fink
16
[i]



Table of Contents

Building from source
16
Arrays 17
Time for action – adding vectors
17
IPython – an interactive shell
21
Online resources and help
25
Summary
26

Chapter 2: Beginning with NumPy Fundamentals

27

Chapter 3: Getting Familiar with Commonly Used Functions

53

NumPy array object
Time for action – creating a multidimensional array
Selecting elements
NumPy numerical types
Data type objects
Character codes
The dtype constructors
The dtype attributes
Time for action – creating a record data type
One-dimensional slicing and indexing
Time for action – slicing and indexing multidimensional arrays
Time for action – manipulating array shapes
Time for action – stacking arrays
Time for action – splitting arrays
Time for action – converting arrays
Summary
File I/O
Time for action – reading and writing files
Comma-seperated value files
Time for action – loading from CSV files
Volume Weighted Average Price
Time for action – calculating Volume Weighted Average Price
The mean() function
Time-weighted average price
Value range
Time for action – finding highest and lowest values
Statistics
Time for action – performing simple statistics
Stock returns
Time for action – analyzing stock returns
Dates
[ ii ]



28
29
30
31
33
33
34
35
35
36
36
39
41
46
51
51

53
54
55
55
56
56
56
57
58
58
59
59
62
63
65

Table of Contents

Time for action – dealing with dates
65
Time for action – using the datetime64 data type
69
Weekly summary
70
Time for action – summarizing data
70
Average True Range
74
Time for action – calculating Average True Range
75
Simple Moving Average
77
Time for action – computing the Simple Moving Average
77
Exponential Moving Average
80
Time for action – calculating the Exponential Moving Average
80
Bollinger Bands
82
Time for action – enveloping with Bollinger Bands
83
Linear model
86
Time for action – predicting price with a linear model
86
Trend lines
89
Time for action – drawing trend lines
90
Methods of ndarray
94
Time for action – clipping and compressing arrays
94
Factorial
95
Time for action – calculating the factorial
95
Missing values and Jackknife resampling
96
Time for action – handling NaNs with the nanmean(), nanvar(),
and nanstd() functions
97
Summary 98

Chapter 4: Convenience Functions for Your Convenience

Correlation
Time for action – trading correlated pairs
Polynomials
Time for action – fitting to polynomials
On-balance volume
Time for action – balancing volume
Simulation
Time for action – avoiding loops with vectorize()
Smoothing
Time for action – smoothing with the hanning() function
Initialization
Time for action – creating value initialized arrays with the full() and
full_like() functions
Summary

[ iii ]



99

100
100
104
105
108
109
111
111
114
114
118
119
120

Table of Contents

Chapter 5: Working with Matrices and ufuncs

121

Chapter 6: Moving Further with NumPy Modules

145

Matrices
Time for action – creating matrices
Creating a matrix from other matrices
Time for action – creating a matrix from other matrices
Universal functions
Time for action – creating universal functions
Universal function methods
Time for action – applying the ufunc methods to the add function
Arithmetic functions
Time for action – dividing arrays
Modulo operation
Time for action – computing the modulo
Fibonacci numbers
Time for action – computing Fibonacci numbers
Lissajous curves
Time for action – drawing Lissajous curves
Square waves
Time for action – drawing a square wave
Sawtooth and triangle waves
Time for action – drawing sawtooth and triangle waves
Bitwise and comparison functions
Time for action – twiddling bits
Fancy indexing
Time for action – fancy indexing in-place for ufuncs with the at() method
Summary
Linear algebra
Time for action – inverting matrices
Solving linear systems
Time for action – solving a linear system
Finding eigenvalues and eigenvectors
Time for action – determining eigenvalues and eigenvectors
Singular value decomposition
Time for action – decomposing a matrix
Pseudo inverse
Time for action – computing the pseudo inverse of a matrix
Determinants
Time for action – calculating the determinant of a matrix
Fast Fourier transform
[ iv ]



122
122
123
123
125
125
126
127
129
129
131
131
132
133
134
135
136
137
138
139
140
141
143
144
144
145
146
148
148
149
150
151
152
154
154
155
155
156

© 2018-2019 uberlabel.com. All rights reserved