Book Image

NumPy Essentials

By : Leo (Liang-Huan) Chin, Tanmay Dutta, Shane Holloway
Book Image

NumPy Essentials

By: Leo (Liang-Huan) Chin, Tanmay Dutta, Shane Holloway

Overview of this book

In today’s world of science and technology, it’s all about speed and flexibility. When it comes to scientific computing, NumPy tops the list. NumPy gives you both the speed and high productivity you need. This book will walk you through NumPy using clear, step-by-step examples and just the right amount of theory. We will guide you through wider applications of NumPy in scientific computing and will then focus on the fundamentals of NumPy, including array objects, functions, and matrices, each of them explained with practical examples. You will then learn about different NumPy modules while performing mathematical operations such as calculating the Fourier Transform; solving linear systems of equations, interpolation, extrapolation, regression, and curve fitting; and evaluating integrals and derivatives. We will also introduce you to using Cython with NumPy arrays and writing extension modules for NumPy code using the C API. This book will give you exposure to the vast NumPy library and help you build efficient, high-speed programs using a wide range of mathematical features.
Table of Contents (16 chapters)
NumPy Essentials
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface

NumPy and Cython


Cython has built-in support to provide faster access to NumPy arrays. These facilities make Cython an ideal candidate to optimize NumPy code. For this section, we will study code that calculates the price of the European option, a financial instrument using the Monte-Carlo technique. Knowledge of finance is not expected; however, we assume you have a basic understanding of Monte-Carlo simulations:

defprice_european(strike = 100, S0 = 100, time = 1.0,  
rate = 0.5, mu = 0.2, steps = 50,  
N = 10000, option = "call"): 
 
dt = time / steps 
rand = np.random.standard_normal((steps + 1, N)) 
S = np.zeros((steps+1, N)); 
S[0] = S0 
 
for t in range(1,steps+1): 
S[t] = S[t-1] * np.exp((rate-0.5 * mu ** 2) * dt 
+ mu * np.sqrt(dt) * rand[t]) 
price_call = (np.exp(-rate * time) 
* np.sum(np.maximum(S[-1] - strike, 0))/N) 
price_put = (np.exp(-rate * time) 
* np.sum(np.maximum(strike - S[-1], 0))/N) 
 ...