aboutsummaryrefslogtreecommitdiffstats
path: root/python/analytics/black.py
blob: 781732d9cb6e2f9fb2ec6c10d966d076d5258d30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from math import log, sqrt, erf
from numba import jit, float64, boolean
from scipy.stats import norm
import math


def d1(F, K, sigma, T):
    return (log(F / K) + sigma ** 2 * T / 2) / (sigma * math.sqrt(T))


def d2(F, K, sigma, T):
    return d1(F, K, sigma, T) - sigma * math.sqrt(T)


@jit(cache=True, nopython=True)
def d12(F, K, sigma, T):
    sigmaT = sigma * sqrt(T)
    d1 = log(F / K) / sigmaT
    d2 = d1
    d1 += 0.5 * sigmaT
    d2 -= 0.5 * sigmaT
    return d1, d2


@jit(float64(float64), cache=True, nopython=True)
def cnd_erf(d):
    """ 2 * Phi where Phi is the cdf of a Normal """
    RSQRT2 = 0.7071067811865475
    return 1 + erf(RSQRT2 * d)


@jit(float64(float64, float64, float64, float64, boolean), cache=True, nopython=True)
def black(F, K, T, sigma, payer=True):
    d1, d2 = d12(F, K, sigma, T)
    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))


@jit(float64(float64, float64, float64, float64), cache=True, nopython=True)
def Nx(F, K, sigma, T):
    return cnd_erf((log(F / K) - sigma ** 2 * T / 2) / (sigma * sqrt(T))) / 2


def bachelier(F, K, T, sigma):
    """ Bachelier formula for normal dynamics

    need to multiply by discount factor
    """
    d1 = (F - K) / (sigma * sqrt(T))
    return 0.5 * (F - K) * cnd_erf(d1) + sigma * sqrt(T) * norm.pdf(d1)