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 ...

Get NumPy Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.