# cython: language_level=3, cdivision=True from libc.math cimport log, sqrt, erf from scipy.stats import norm import cython cpdef double cnd_erf(double d): """ 2 * Phi where Phi is the cdf of a Normal """ cdef double RSQRT2 = 0.7071067811865475 return 1 + erf(RSQRT2 * d) cpdef double black(double F, double K, double T, double sigma, bint payer=True): cdef: double x = log(F / K) double sigmaT = sigma * sqrt(T) double d1 = (x + 0.5 * sigmaT * sigmaT) / sigmaT double d2 = (x - 0.5 * sigmaT * sigmaT) / sigmaT if payer: return 0.5 * (F * cnd_erf(d1) - K * cnd_erf(d2)) else: return 0.5 * (K * cnd_erf(-d2) - F * cnd_erf(-d1)) cpdef double Nx(double F, double K, double sigma, double T): return cnd_erf((log(F / K) - sigma ** 2 * T / 2) / (sigma * sqrt(T))) / 2 cpdef double bachelier(double F, double K, double T, double sigma): """ Bachelier formula for normal dynamics need to multiply by discount factor """ cdef double d1 = (F - K) / (sigma * sqrt(T)) return 0.5 * (F - K) * cnd_erf(d1) + sigma * sqrt(T) * norm.pdf(d1)