Path: blob/master/src/FMNM/FFT.py
1700 views
#!/usr/bin/env python31# -*- coding: utf-8 -*-2"""3Created on Mon May 18 20:13:17 202045@author: cantaro866"""78import numpy as np9from scipy.fftpack import ifft10from scipy.interpolate import interp1d11from scipy.integrate import quad12from scipy.optimize import fsolve131415def fft_Lewis(K, S0, r, T, cf, interp="cubic"):16"""17K = vector of strike18S = spot price scalar19cf = characteristic function20interp can be cubic or linear21"""22N = 2**15 # FFT more efficient for N power of 223B = 500 # integration limit24dx = B / N25x = np.arange(N) * dx # the final value B is excluded2627weight = np.arange(N) # Simpson weights28weight = 3 + (-1) ** (weight + 1)29weight[0] = 130weight[N - 1] = 13132dk = 2 * np.pi / B33b = N * dk / 234ks = -b + dk * np.arange(N)3536integrand = np.exp(-1j * b * np.arange(N) * dx) * cf(x - 0.5j) * 1 / (x**2 + 0.25) * weight * dx / 337integral_value = np.real(ifft(integrand) * N)3839if interp == "linear":40spline_lin = interp1d(ks, integral_value, kind="linear")41prices = S0 - np.sqrt(S0 * K) * np.exp(-r * T) / np.pi * spline_lin(np.log(S0 / K))42elif interp == "cubic":43spline_cub = interp1d(ks, integral_value, kind="cubic")44prices = S0 - np.sqrt(S0 * K) * np.exp(-r * T) / np.pi * spline_cub(np.log(S0 / K))45return prices464748def IV_from_Lewis(K, S0, T, r, cf, disp=False):49"""Implied Volatility from the Lewis formula50K = strike; S0 = spot stock; T = time to maturity; r = interest rate51cf = characteristic function"""52k = np.log(S0 / K)5354def obj_fun(sig):55integrand = (56lambda u: np.real(57np.exp(u * k * 1j)58* (cf(u - 0.5j) - np.exp(1j * u * r * T + 0.5 * r * T) * np.exp(-0.5 * T * (u**2 + 0.25) * sig**2))59)60* 161/ (u**2 + 0.25)62)63int_value = quad(integrand, 1e-15, 2000, limit=2000, full_output=1)[0]64return int_value6566X0 = [0.2, 1, 2, 4, 0.0001] # set of initial guess points67for x0 in X0:68x, _, solved, msg = fsolve(69obj_fun,70[71x0,72],73full_output=True,74xtol=1e-4,75)76if solved == 1:77return x[0]78if disp is True:79print("Strike", K, msg)80return -1818283