Thursday 24 January 2019

3D plot in python from a csv file

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from scipy.interpolate import griddata


Dim2 Dim1 Dim3
5 1 109.582
5 2 105.657
5 3 113.476
5 4 107.209
5 5 104.784
5 6 102.218
5 7 100.377
5 8 104.111
5 9 69.258
5 10 59.227
5 11 47.046
5 12 37.144
5 13 27.968
5 14 25.118
5 15 21
5 16 18.444
5 17 19.306
5 18 9.637
5 19 4.066
5 20 0.06
4 1 158.586
4 2 153.183
4 3 160.387
4 4 153.693
4 5 150.667
4 6 145.106
4 7 142.821
4 8 149.522
4 9 109.88
4 10 97.388
4 11 81.012
4 12 67.986
4 13 58.08
4 14 53.754
4 15 48.378
4 16 45.452
4 17 43.249
4 18 27.168
4 19 17.932
4 20 0.302
3 1 215.783
3 2 207.373
3 3 215.219
3 4 209.206
3 5 205.631
3 6 198.287
3 7 196.91
3 8 204.884
3 9 163.378
3 10 149.805
3 11 132.181
3 12 114.895
3 13 105.88
3 14 101.015
3 15 95.3
3 16 92.124
3 17 87.071
3 18 67.161
3 19 55.829
3 20 16.715
2 1 278.676
2 2 270.159
2 3 279.71
2 4 272.591
2 5 266.701
2 6 258.457
2 7 260.062
2 8 268.448
2 9 227.359
2 10 215.866
2 11 198.514
2 12 179.856
2 13 171.234
2 14 165.944
2 15 161.638
2 16 159.788
2 17 151.862
2 18 135.376
2 19 125.595
2 20 98.863
1 1 346.731
1 2 341.995
1 3 349.773
1 4 340.789
1 5 338.01
1 6 325.182
1 7 328.339
1 8 333.462
1 9 300.839
1 10 292.52
1 11 275.064
1 12 254.504
1 13 252.279
1 14 250.211
1 15 242.438
1 16 242.713
1 17 233.577
1 18 223.335
1 19 218.322
1 20 199.88
fig = plt.figure(figsize=plt.figaspect(0.5))
ax = fig.add_subplot(1, 2, 1, projection='3d')
# note this: you can skip rows!
my_data = np.genfromtxt('data.csv', delimiter=',',skip_header=1)
X = my_data[:,0]
Y = my_data[:,1]
Z = my_data[:,2]

xi = np.linspace(X.min(),X.max(),100)
yi = np.linspace(Y.min(),Y.max(),100)
# VERY IMPORTANT, to tell matplotlib how is your data organized
zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')

CS = plt.contour(xi,yi,zi,15,linewidths=0.5,color='k')
ax = fig.add_subplot(1, 2, 2, projection='3d')

xig, yig = np.meshgrid(xi, yi)

surf = ax.plot_surface(xig, yig, zi,
        linewidth=0)

plt.show()

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//