• No results found

NumPy Beginner's Guide

N/A
N/A
Protected

Academic year: 2021

Share "NumPy Beginner's Guide"

Copied!
9
0
0

Loading.... (view fulltext now)

Full text

(1)

NumPy

Beginner's

Guide

Second

Edition

An action

packed guide

using

real world

examples

of the

easy

to use,

high performance,

free

open

source

NumPy

mathematical

library

Ivan Idris

[

PUBLISHING BIRMINGHAM-MUMBAI

1 open

source

(2)

Table

of

Contents

Preface

1

Chapter

1:

NumPy

Quick Start 9

Python

9

Time for action

-installing Python

on different

operating

systems 10

Windows 10

Time foraction-

installing NumPy, Matplotlib, SciPy,

and

IPython

on Windows 11

Linux 13

Time foraction-

installing

NumPy, Matplotlib, SciPy,

and

IPython

on Linux 13

Mac OS X 14

Timeforaction

-installing

NumPy,

Matplotlib,

and

SciPy

onMac OS X 14

Time for action-

installing

NumPy, SciPy,

Matplotlib,

and

IPython

with MacPorts orFink 17

Building

fromsource 17

Arrays

17

Time for action-

adding

vectors 18

IPython—an

interactive shell 21

Online resources and

help

25

Summary

26

Chapter

2:

Beginning

with

NumPy

Fundamentals

27

NumPy

array

object

28

Time foraction

-creating

a multidimensional array 29

Selecting

elements 30

NumPy

numerical

types

30

Data

type

objects

32

Character codes 32

dtype

constructors 33

(3)

TableofContents

Time for action-

creating

a record data type 34

One-dimensional

slicing

and

indexing

35

Time for action-

slicing

and

indexing

multidimensional arrays 35

Time for action

-manipulating

array

shapes

38

Stacking

39

Time foraction

-stacking

arrays 40

Splitting

43

Time for action-

splitting

arrays 43

Array

attributes 45

Time for action-

converting

arrays 48

Summary

49

Chapter

3: Get

in

Terms

with

Commonly

Used Functions

51

File

I/O

51

Time for action-

reading

and

writing

files 52

CSVfiles 52

Time for action-

loading

fromCSV files 53

Volume-weighted

average

price

53

Time for action-

calculating volume-weighted

average

price

54

Themeanfunction 54

Time-weighted

average

price

54

Value range 55

Time for action

-finding highest

and lowest values 55

Statistics 56

Time for action-

doing simple

statistics 57

Stock returns 59

Time for action-

analyzing

stockreturns 59

Dates 61

Time for action-

dealing

with dates 61

Weekly

summary 65

Time for action

-summarizing

data 65

Average

truerange 69

Time foraction-

calculating

the averagetruerange 69

Simple

moving

average 72

Time for action-

computing

the

simple moving

average 72

Exponential moving

average 74

Time for action-

calculating

the

exponential moving

average 74

Bollinger

bands 76

Time for action-

enveloping

with

Bollinger

bands 76

(4)

of

Time

for

action-

predicting price

witha linear model 80

Trend lines 82

Time for action-

drawing

trend lines 82

Methods of

ndarray

86

Time for action

-clipping

and

compressing

arrays 87

Factorial 87

Time for action

-calculating

the factorial 88

Summary

89

Chapter

4: Convenience Functions for Your

Convenience

91

Correlation 92

Time

for

action-

trading

correlated

pairs

92

Polynomials

96

Time for action-

fitting

to

polynomials

96

On-balance volume 99

Time for action-

balancing

volume 100

Simulation 102

Time for action-

avoiding loops

with vectorize 102

Smoothing

105

Timeforaction-

smoothing

with the

banning

function 105

Summary

109

Chapter

5:

Working

with Matrices

and ufuncs 111

Matrices 111

Time for action-

creating

matrices 112

Creating

amatrix from other matrices 113

Time for action

-creating

a matrix from other matrices 113

Universal functions 114

Time for action

-creating

universal function 115

Universal function methods 116

Timeforaction-

applying

the ufunc methodsonadd 116

Arithmetic functions 118

Timefor

action-dividing

arrays 119

Timeforaction-

computing

the modulo 121

Fibonaccinumbers 122

Timefor action-

computing

Fibonaccinumbers 122

Lissajous

curves 123

Time for action

-drawing

Lissajous

curves 124

Square

waves 125

Time for action

-drawing

asquarewave 125

(5)

TableofContents

Time for action-

drawing

sawtooth and

triangle

waves 127

Bitwise and

comparison

functions 129

Timefor

action-twiddling

bits 129

Summary

131

Chapter

6: Move Further with

NumPy Modules

133

Linear

algebra

133

Timefor action-

inverting

matrices 133

Solving

linear systems 135

Time for action

-solving

a linear

system

136

Finding eigenvalues

and

eigenvectors

137

Time foraction

-determining eigenvalues

and

eigenvectors

137

Singular

value

decomposition

139

Time for action-

decomposing

amatrix 139

Pseudoinverse 141

Timefor action-

computing

the

pseudo

inverse ofamatrix 141

Determinants 142

Time for action-

calculating

the determinant ofa matrix 142

Fast Fourier transform 143

Time for action-

calculating

the Fouriertransform 143

Shifting

145

Time foraction-

shifting frequencies

145

Randomnumbers 147

Time for action-

gambling

with the binomial 147

Hypergeometric

distribution 149

Timefor action

-simulating

agame show 149

Continuous distributions 151

Time for action

-drawing

anormal distribution 151

Lognormal

distribution 153

Time for action

-drawing

the

lognormal

distribution 153

Summary

154

Chapter

7:

Peeking

into

Special

Routines

155

Sorting

155

Time for

action-sorting lexically

156

Complex

numbers 157

Time for action-

sorting complex

numbers 157

Searching

158

Time for action-

using

searchsorted 159

(6)

Time for action

-extracting

elements fromanarray 160

Financial functions 161

Time for action

-determining

futurevalue 161

Presentvalue 163

Time for action-

getting

thepresent value 163

Netpresentvalue 163

Timeforaction-

calculating

thenetpresent value 163

Internal rate ofreturn 164

Time for action-

determining

the internal rate of

return 164

Periodic payments 165

Time for action-

calculating

the

periodic

payments 165

Number of payments 165

Time for action-

determining

the number of

periodic payments

165

Interest rate 166

Time foraction-

figuring

outtherate 166

Window functions 166

Time foraction-

plotting

the Bartlett window 167

Blackmanwindow 167

Time for action-

smoothing

stock

prices

with the Blackmanwindow

168

Hamming

window 170

Timefor action

-plotting

the

Hamming

window 170

Kaiser window 171

Timefor action

-plotting

theKaiser window 171

Special

mathematical functions 172

Time for action

-plotting

the modified Bessel function 172

sine 173

Time for action-

plotting

thesine function 173

Summary

175

Chapter

8:Assure

Quality

with

Testing

177

Assert functions 178

Time foraction-

asserting

almost

equal

178

Approximately equal

arrays 179

Time foraction-

asserting approximately equal

180

Almost

equal

arrays 180

Time for action

-asserting

arraysalmost

equal

181

Equal

arrays 182

Time for action-

comparing

arrays 182

(7)

TableofContents

Time for action

-checking

thearray order 183

Objects

comparison

184

Time for action-

comparing

objects

184

String

comparison

184

Time foraction-

comparing strings

185

Floating

point comparisons

185

Timefor action-

comparing

with

assert_array_almost_equal_nulp

186

Comparison

of floats withmore ULPs 187

Timefor action

-comparing using maxulp

of2 187

Unittests 187

Time for action-

writing

a unittest 188

Nosetests decorators 190

Time foraction-

decorating

tests 191

Docstrings

193

Timefor action

-executing

doctests 194

Summary

195

Chapter

9:

Plotting

with

Matplotlib

197

Simple

plots

198

Time for action-

plotting

a

polynomial

function

198

Plot format

string

200

Timeforaction-

plotting

a

polynomial

and itsderivative

200

Subplots

201

Timefor action-

plotting

a

polynomial

and its derivatives 201

Finance 204

Time for action-

plotting

a

year's

worth of stock

quotes

204

Histograms

207

Time for action-

charting

stock

price

distributions 207

Logarithmic

plots

209

Time foraction-

plotting

stock volume

209

Scatter

plots

211

Timefor action

-plotting price

and volume returnswith scatter

plot

211

Fill between 213

Time for action

-shading plot

regions

basedon acondition 213

Legend

and annotations 215

Time for action-

using legend

and annotations

215

Three dimensional

plots

218

Time foraction-

plotting

in three dimensions

219

Contour

plots

220

Time foraction-

drawing

afilled contour

plot

220

(8)

Animation 222

Time for action-

animating plots

222

Summary

223

Chapter

10:

When

NumPy

is Not

Enough

-

SciPy

and

Beyond

225

MATLABand Octave 225

Timeforaction

-saving

and

loading

a .mat file 226

Statistics 227

Time for action-

analyzing

random values 227

Samples' comparison

and SciKits 230

Time for action-

comparing

stock

log

returns 230

Signal processing

232

Time for action-

detecting

atrend in

QQQ

233

Fourier

analysis

235

Time for action

-filtering

adetrended

signal

236

Mathematical

optimization

238

Time for action

-fitting

toa sine 239

Numerical

integration

242

Timeforaction-

calculating

the Gaussian

integral

242

Interpolation

243

Time for action-

interpolating

inone dimension 243

Image

processing

245

Timefor action-

manipulating

Lena 245

Audio

processing

247

Time for action-

replaying

audio

clips

247

Summary

249

Chapter

11:

Playing

with

Pygame

251

Pygame

251

Time foraction-

installing Pygame

252

Hello World 252

Time foraction-

creating

a

simple

game 252

Animation 255

Time for action-

animating objects

with

NumPy

and

Pygame

255

Matplotlib

258

Time for action

-using

Matplotlib

in

Pygame

258

Surface

pixels

261

Time for action

-accessing

surface

pixel

data with

NumPy

262

Artificial

intelligence

263

Time for action

-clustering points

264

(9)

TableofContents

Time foraction-

drawing

the

Sierpinski

gasket

267

Simulation gamewith

PyGame

270

Time foraction-

simulating

life

270

Summary

274

Pop

Quiz

Answers 275

Index

277

References

Related documents

Proximity was classified as essential to a given factor if the brewery stated that the activity was occurring within the cluster area (inside the nine county area). It was

First, various files (executables, input data, etc.) are uploaded and installed on the selected compute nodes using the file transfer method speci- fied by the deployment plan

Another interesting finding is that, while execution times of sequential code do not vary signif- icantly between generic and non-generic implementations, the non-generic

The negation system of Yang Zhuang includes two standard negators and an aspectual negator, all of which occur before the verb; the negator meiz nearly always co-occurs with

Aplikasi network monitoring bertugas mengumpulkan statistik jaringan untuk beberapa kebutuhan seperti pelacakan flow dan jaringan dengan statistik paket yang luas ataupun juga

It provides the power supply for the charger board and voltage and current source for the charging battery.. For the voltage source for battery charging, the standard voltage of

The top performing companies leverage clear competencies in a number of key process areas to advance their strategy to personalize the email engagement with customers and

The most detailed data is stored once, and an incremental object by object generalization process is run and represented in a data structure, which can afterwards be used to