NumPy
Beginner's
Guide
Second
Edition
An action
packed guide
using
real world
examples
of the
easy
to use,
high performance,
free
open
sourceNumPy
mathematical
library
Ivan Idris
[
PUBLISHING BIRMINGHAM-MUMBAI1 open
source
Table
of
Contents
Preface
1Chapter
1:NumPy
Quick Start 9Python
9Time for action
-installing Python
on differentoperating
systems 10Windows 10
Time foraction-
installing NumPy, Matplotlib, SciPy,
andIPython
on Windows 11
Linux 13
Time foraction-
installing
NumPy, Matplotlib, SciPy,
andIPython
on Linux 13Mac OS X 14
Timeforaction
-installing
NumPy,
Matplotlib,
andSciPy
onMac OS X 14Time for action-
installing
NumPy, SciPy,
Matplotlib,
andIPython
with MacPorts orFink 17
Building
fromsource 17Arrays
17Time for action-
adding
vectors 18IPython—an
interactive shell 21Online resources and
help
25Summary
26Chapter
2:Beginning
withNumPy
Fundamentals
27NumPy
arrayobject
28Time foraction
-creating
a multidimensional array 29Selecting
elements 30NumPy
numericaltypes
30Data
type
objects
32Character codes 32
dtype
constructors 33TableofContents
Time for action-
creating
a record data type 34One-dimensional
slicing
andindexing
35Time for action-
slicing
andindexing
multidimensional arrays 35Time for action
-manipulating
arrayshapes
38Stacking
39Time foraction
-stacking
arrays 40Splitting
43Time for action-
splitting
arrays 43
Array
attributes 45Time for action-
converting
arrays 48
Summary
49Chapter
3: Getin
Termswith
Commonly
Used Functions
51File
I/O
51Time for action-
reading
andwriting
files 52CSVfiles 52
Time for action-
loading
fromCSV files 53Volume-weighted
averageprice
53Time for action-
calculating volume-weighted
averageprice
54Themeanfunction 54
Time-weighted
averageprice
54Value range 55
Time for action
-finding highest
and lowest values 55Statistics 56
Time for action-
doing simple
statistics 57Stock returns 59
Time for action-
analyzing
stockreturns 59Dates 61
Time for action-
dealing
with dates 61Weekly
summary 65Time for action
-summarizing
data 65Average
truerange 69Time foraction-
calculating
the averagetruerange 69Simple
moving
average 72Time for action-
computing
thesimple moving
average 72Exponential moving
average 74Time for action-
calculating
theexponential moving
average 74Bollinger
bands 76Time for action-
enveloping
withBollinger
bands 76of
Time
for
action-predicting price
witha linear model 80Trend lines 82
Time for action-
drawing
trend lines 82Methods of
ndarray
86Time for action
-clipping
andcompressing
arrays 87Factorial 87
Time for action
-calculating
the factorial 88Summary
89Chapter
4: Convenience Functions for YourConvenience
91Correlation 92
Time
for
action-trading
correlatedpairs
92Polynomials
96Time for action-
fitting
topolynomials
96On-balance volume 99
Time for action-
balancing
volume 100Simulation 102
Time for action-
avoiding loops
with vectorize 102Smoothing
105Timeforaction-
smoothing
with thebanning
function 105Summary
109Chapter
5:Working
with Matrices
and ufuncs 111Matrices 111
Time for action-
creating
matrices 112Creating
amatrix from other matrices 113Time for action
-creating
a matrix from other matrices 113Universal functions 114
Time for action
-creating
universal function 115Universal function methods 116
Timeforaction-
applying
the ufunc methodsonadd 116Arithmetic functions 118
Timefor
action-dividing
arrays 119Timeforaction-
computing
the modulo 121Fibonaccinumbers 122
Timefor action-
computing
Fibonaccinumbers 122Lissajous
curves 123Time for action
-drawing
Lissajous
curves 124Square
waves 125Time for action
-drawing
asquarewave 125TableofContents
Time for action-
drawing
sawtooth andtriangle
waves 127
Bitwise and
comparison
functions 129Timefor
action-twiddling
bits 129Summary
131Chapter
6: Move Further withNumPy Modules
133Linear
algebra
133Timefor action-
inverting
matrices 133Solving
linear systems 135Time for action
-solving
a linearsystem
136Finding eigenvalues
andeigenvectors
137Time foraction
-determining eigenvalues
andeigenvectors
137Singular
valuedecomposition
139Time for action-
decomposing
amatrix 139Pseudoinverse 141
Timefor action-
computing
thepseudo
inverse ofamatrix 141Determinants 142
Time for action-
calculating
the determinant ofa matrix 142Fast Fourier transform 143
Time for action-
calculating
the Fouriertransform 143Shifting
145Time foraction-
shifting frequencies
145
Randomnumbers 147
Time for action-
gambling
with the binomial 147Hypergeometric
distribution 149Timefor action
-simulating
agame show 149Continuous distributions 151
Time for action
-drawing
anormal distribution 151Lognormal
distribution 153Time for action
-drawing
thelognormal
distribution 153Summary
154Chapter
7:Peeking
intoSpecial
Routines
155Sorting
155Time for
action-sorting lexically
156Complex
numbers 157Time for action-
sorting complex
numbers 157Searching
158Time for action-
using
searchsorted 159Time for action
-extracting
elements fromanarray 160Financial functions 161
Time for action
-determining
futurevalue 161Presentvalue 163
Time for action-
getting
thepresent value 163Netpresentvalue 163
Timeforaction-
calculating
thenetpresent value 163Internal rate ofreturn 164
Time for action-
determining
the internal rate ofreturn 164
Periodic payments 165
Time for action-
calculating
theperiodic
payments 165
Number of payments 165
Time for action-
determining
the number ofperiodic payments
165Interest rate 166
Time foraction-
figuring
outtherate 166Window functions 166
Time foraction-
plotting
the Bartlett window 167Blackmanwindow 167
Time for action-
smoothing
stockprices
with the Blackmanwindow168
Hamming
window 170Timefor action
-plotting
theHamming
window 170Kaiser window 171
Timefor action
-plotting
theKaiser window 171Special
mathematical functions 172Time for action
-plotting
the modified Bessel function 172sine 173
Time for action-
plotting
thesine function 173Summary
175Chapter
8:AssureQuality
with
Testing
177Assert functions 178
Time foraction-
asserting
almostequal
178Approximately equal
arrays 179Time foraction-
asserting approximately equal
180Almost
equal
arrays 180Time for action
-asserting
arraysalmostequal
181Equal
arrays 182Time for action-
comparing
arrays 182TableofContents
Time for action
-checking
thearray order 183Objects
comparison
184Time for action-
comparing
objects
184
String
comparison
184Time foraction-
comparing strings
185
Floating
point comparisons
185Timefor action-
comparing
withassert_array_almost_equal_nulp
186Comparison
of floats withmore ULPs 187Timefor action
-comparing using maxulp
of2 187Unittests 187
Time for action-
writing
a unittest 188Nosetests decorators 190
Time foraction-
decorating
tests 191Docstrings
193Timefor action
-executing
doctests 194Summary
195Chapter
9:Plotting
withMatplotlib
197Simple
plots
198Time for action-
plotting
apolynomial
function198
Plot format
string
200Timeforaction-
plotting
apolynomial
and itsderivative200
Subplots
201Timefor action-
plotting
a
polynomial
and its derivatives 201Finance 204
Time for action-
plotting
ayear's
worth of stockquotes
204Histograms
207Time for action-
charting
stockprice
distributions 207Logarithmic
plots
209Time foraction-
plotting
stock volume209
Scatter
plots
211Timefor action
-plotting price
and volume returnswith scatterplot
211Fill between 213
Time for action
-shading plot
regions
basedon acondition 213Legend
and annotations 215Time for action-
using legend
and annotations215
Three dimensional
plots
218Time foraction-
plotting
in three dimensions219
Contour
plots
220Time foraction-
drawing
afilled contourplot
220Animation 222
Time for action-
animating plots
222Summary
223Chapter
10:When
NumPy
is NotEnough
-SciPy
andBeyond
225MATLABand Octave 225
Timeforaction
-saving
andloading
a .mat file 226Statistics 227
Time for action-
analyzing
random values 227Samples' comparison
and SciKits 230Time for action-
comparing
stocklog
returns 230Signal processing
232Time for action-
detecting
atrend inQQQ
233Fourier
analysis
235Time for action
-filtering
adetrendedsignal
236Mathematical
optimization
238Time for action
-fitting
toa sine 239Numerical
integration
242Timeforaction-
calculating
the Gaussianintegral
242Interpolation
243Time for action-
interpolating
inone dimension 243Image
processing
245Timefor action-
manipulating
Lena 245Audio
processing
247Time for action-
replaying
audioclips
247Summary
249Chapter
11:Playing
withPygame
251Pygame
251Time foraction-
installing Pygame
252Hello World 252
Time foraction-
creating
asimple
game 252Animation 255
Time for action-
animating objects
withNumPy
andPygame
255Matplotlib
258Time for action
-using
Matplotlib
inPygame
258Surface
pixels
261Time for action
-accessing
surfacepixel
data withNumPy
262Artificial
intelligence
263Time for action
-clustering points
264TableofContents
Time foraction-
drawing
theSierpinski
gasket
267Simulation gamewith
PyGame
270Time foraction-
simulating
life270