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