Tuesday, 22 January 2019

Black Scholes "Option Payoff" versus "time" in Python

import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.family'] = 'serif'
from scipy.integrate import quad

def dN(x):
    ''' Probability density function of standard normal random variable x.'''
    return math.exp(-0.5 * x ** 2) / math.sqrt(2 * math.pi)
def N(d):
    ''' Cumulative density function of standard normal random variable x. '''
    return quad(lambda x: dN(x), -20, d, limit=50)[0]
def d1f(St, K, t, T, r, sigma):
    ''' Black-Scholes-Merton d1 function.
        Parameters see e.g. BSM_call_value function. '''
    d1 = (math.log(St / K) + (r + 0.5 * sigma ** 2)
        * (T - t)) / (sigma * math.sqrt(T - t))
    return d1
#
# Valuation Functions
#
def BSM_call_value(St, K, t, T, r, sigma): 
    ''' Calculates Black-Scholes-Merton European call option value.86 DERIVATIVES ANALYTICS WITH PYTHON
    Parameters
    ==========
    St: float
    stock/index level at time t
    K: float
    strike price
    t: float
    valuation date
    T: float
    date of maturity/time-to-maturity if t = 0; T > t
    r: float
    constant, risk-less short rate
    sigma: float
    volatility
    Returns
    =======
call_value: float
European call present value at t
    '''
    d1 = d1f(St, K, t, T, r, sigma)
    d2 = d1 - sigma * math.sqrt(T - t)
    call_value = St * N(d1) - math.exp(-r * (T - t)) * K * N(d2)
    return call_value
def BSM_put_value(St, K, t, T, r, sigma):
    ''' Calculates Black-Scholes-Merton European put option value.
    Parameters
    ==========
    St: float
    stock/index level at time t
    K: float
    strike price
    t: float
    valuation date
    T: float
    date of maturity/time-to-maturity if t = 0; T > t
    r: float
    constant, risk-less short rate
    sigma: float
    volatility
    Returns
    =======
    put_value: float
        European put present value at t
    '''
    put_value = BSM_call_value(St, K, t, T, r, sigma) \
        - St + math.exp(-r * (T - t)) * K
    return put_value
#
# Plotting European Option Values
#
def plot_values(function):
    ''' Plots European option values for different parameters c.p. '''
    plt.figure(figsize=(10, 8.3))
    points = 100
#
# Model Parameters
#
    St = 100.0 # index level
    K = 100.0 # option strike
    t = 0.0 # valuation date
    T = 1.0 # maturity date
    r = 0.05 # risk-less short rate
    sigma = 0.2 # volatility
# C(T) plot
    plt.subplot(222)
    tlist = np.linspace(0.0001, 1, points)
    vlist = [function(St, K, t, T, r, sigma) for T in tlist]
    plt.plot(tlist, vlist)
    plt.grid(True)
    plt.xlabel('maturity $T$')

Monday, 21 January 2019

Black-Scholes model in R

stock=10858.7
rf=0.0743
strike=stock-100
sigma=0.1281
TTM=0.0039683
d1<-(log(stock/strike)+(rf+0.5*sigma^2)*TTM)/(sigma*sqrt(TTM))
d2<-d1-(sigma*sqrt(TTM))
BS.call<-stock*pnorm(d1,mean=0,sd=1)-strike*exp(-rf*TTM)*pnorm(d2,mean=0,sd=1)
BS.call
BS.put<-BS.call-stock+strike*exp(-rf*TTM)
BS.put
for(TTM<0.08) 
  {
  TTM<-(TTM*2)
  }
d1<-(log(stock/strike)+(rf+0.5*sigma^2)*TTM)/(sigma*sqrt(TTM))
d2<-d1-(sigma*sqrt(TTM))
BS.call<-stock*pnorm(d1,mean=0,sd=1)-strike*exp(-rf*TTM)*pnorm(d2,mean=0,sd=1)
BS.call
BS.put<-BS.call-stock+strike*exp(-rf*TTM)
BS.put

MC simulation of Black Scholes in R


stock=398.79
sigma=0.32
strike=300
TTM=2.5
rf=0.01
num.sim<-100000
R<-(rf-0.5*sigma^2)*TTM
R
SD<-sigma*sqrt(TTM)
SD
TTM.price<-stock*exp(R+SD*rnorm(num.sim,0,1))
TTM.call<-pmax(0,TTM.price-strike)
PV.call<-TTM.call*(exp(-rf*TTM))
mean(PV.call)
TTM.put<-pmax(0,strike-TTM.price)
PV.put<-TTM.put*(exp(-rf*TTM))
mean(PV.put)
#Let's calculate Black-Scholes value fr call and put option#
d1<-(log(stock/strike)+(rf+0.5*sigma^2)*TTM)/(sigma*sqrt(TTM))
d2<-d1-(sigma*sqrt(TTM))
BS.call<-stock*pnorm(d1,mean=0,sd=1)-strike*exp(-rf*TTM)*pnorm(d2,mean=0,sd=1)
BS.call
BS.put<-BS.call-stock+strike*exp(-rf*TTM)
BS.put
 #”ctrl+shft+enter” to process#

Saturday, 19 January 2019

SPY versus BSM histogram plot in R

library("quantmod")
getSymbols("SPY")
#Stats of SPY
spy = Delt(as.numeric(SPY$SPY.Adjusted), k=20)
spy.mu= mean(spy, na.rm=TRUE)
spy.sd= sd(spy, na.rm=TRUE)
#Stats of SPY applied to Norm dist
norm = rnorm(1000, mean=spy.mu, sd=spy.sd)
#Visualize histograms
hist(spy, main="SPY versus Normal Distribution", breaks=50, col="blue", freq = FALSE, probability=TRUE)
hist(norm, col="yellow", breaks=50, add=T, freq = FALSE, probability=TRUE)

Thursday, 17 January 2019

Plotting data from 2 columns in R

***load the excel/txt file from R-Studio manually using import option**

plot(d5[c(9,6)])

//d5 is name of the file, 'c' implies column, 9 and 6 are column nos to be plotted//

Friday, 18 May 2018

MATLAB plot of data (spectro) with maximum indicator

load llspectro6.txt
x = llspectro6 (:,1);
y = llspectro6 (:,2);
[Peak, PeakIdx] = findpeaks(y);
plot(x,y, 'cyan', 'Linewidth', 2)
ylabel ('Intensity (Counts)')
xlabel ('Wavelength (nm)')
indexmin = find(min(y) == y);
xmin = x(indexmin);
ymin = y(indexmin);
indexmax = find(max(y) == y);
xmax = x(indexmax);
ymax = y(indexmax);
strmax = ['Maximum = ',num2str(xmax)];
text(xmax,ymax,strmax,'HorizontalAlignment','right');