Path: blob/master/src/FMNM/probabilities.py
1700 views
#!/usr/bin/env python31# -*- coding: utf-8 -*-2"""3Created on Mon Oct 7 18:33:39 201945@author: cantaro866"""78import numpy as np9from scipy.integrate import quad10from functools import partial11from FMNM.CF import cf_Heston_good12import scipy.special as scps13from math import factorial141516def Q1(k, cf, right_lim):17"""18P(X<k) - Probability to be in the money under the stock numeraire.19cf: characteristic function20right_lim: right limit of integration21"""2223def integrand(u):24return np.real((np.exp(-u * k * 1j) / (u * 1j)) * cf(u - 1j) / cf(-1.0000000000001j))2526return 1 / 2 + 1 / np.pi * quad(integrand, 1e-15, right_lim, limit=2000)[0]272829def Q2(k, cf, right_lim):30"""31P(X<k) - Probability to be in the money under the money market numeraire32cf: characteristic function33right_lim: right limit of integration34"""3536def integrand(u):37return np.real(np.exp(-u * k * 1j) / (u * 1j) * cf(u))3839return 1 / 2 + 1 / np.pi * quad(integrand, 1e-15, right_lim, limit=2000)[0]404142def Gil_Pelaez_pdf(x, cf, right_lim):43"""44Gil Pelaez formula for the inversion of the characteristic function45INPUT46- x: is a number47- right_lim: is the right extreme of integration48- cf: is the characteristic function49OUTPUT50- the value of the density at x.51"""5253def integrand(u):54return np.real(np.exp(-u * x * 1j) * cf(u))5556return 1 / np.pi * quad(integrand, 1e-15, right_lim)[0]575859def Heston_pdf(i, t, v0, mu, theta, sigma, kappa, rho):60"""61Heston density by Fourier inversion.62"""63cf_H_b_good = partial(64cf_Heston_good,65t=t,66v0=v0,67mu=mu,68theta=theta,69sigma=sigma,70kappa=kappa,71rho=rho,72)73return Gil_Pelaez_pdf(i, cf_H_b_good, np.inf)747576def VG_pdf(x, T, c, theta, sigma, kappa):77"""78Variance Gamma density function79"""80return (81282* np.exp(theta * (x - c) / sigma**2)83/ (kappa ** (T / kappa) * np.sqrt(2 * np.pi) * sigma * scps.gamma(T / kappa))84* ((x - c) ** 2 / (2 * sigma**2 / kappa + theta**2)) ** (T / (2 * kappa) - 1 / 4)85* scps.kv(86T / kappa - 1 / 2,87sigma ** (-2) * np.sqrt((x - c) ** 2 * (2 * sigma**2 / kappa + theta**2)),88)89)909192def Merton_pdf(x, T, mu, sig, lam, muJ, sigJ):93"""94Merton density function95"""96tot = 097for k in range(20):98tot += (99(lam * T) ** k100* np.exp(-((x - mu * T - k * muJ) ** 2) / (2 * (T * sig**2 + k * sigJ**2)))101/ (factorial(k) * np.sqrt(2 * np.pi * (sig**2 * T + k * sigJ**2)))102)103return np.exp(-lam * T) * tot104105106def NIG_pdf(x, T, c, theta, sigma, kappa):107"""108Merton density function109"""110A = theta / (sigma**2)111B = np.sqrt(theta**2 + sigma**2 / kappa) / sigma**2112C = T / np.pi * np.exp(T / kappa) * np.sqrt(theta**2 / (kappa * sigma**2) + 1 / kappa**2)113return (114C115* np.exp(A * (x - c * T))116* scps.kv(1, B * np.sqrt((x - c * T) ** 2 + T**2 * sigma**2 / kappa))117/ np.sqrt((x - c * T) ** 2 + T**2 * sigma**2 / kappa)118)119120121