Let me compute European call option and American put option as a practice(R)
####Sample code####
##European Call###
europecall<-function(s0,k_call,vol,T,n,r)
{
dt<-T/n
u<-exp(vol*sqrt(dt))
d<-exp(-vol*sqrt(dt))
a<-exp(r*dt)
p<-(a-d)/(u-d)
strikeprice<-array(NA,c(n+1,n+1))
strikeprice[1,1]<s0
for(j in 2:(n+1))###j is step number
{
for(i in 1:j)###i is u step
{
stikeprice[i,j]<-s0*u^(j-2*i+1)
}
}
ECV<-array(NA,c(n+1,n+1))
for(i in 1:(n+1))
{
ECV[i,(n+1)]<-max(strikeprice[i,(n+1)]-k_call,0)
}
for(j in n:1)
{
for(i in 1:j)
{
ECV[i,j]<-(p*ECV[i,j+1]+(1-p)*ECV[i+1,j+1])*exp(-r*dt)
}
}
return(ECV[1,1])
}
##American Put##
apbt<-function(s0,k_put,vol,T,n,r)
{
dt<-T/n
u<-exp(vol*sqrt(dt))
d<- exp(-vol*sqrt(dt))
a<-exp(r*dt)
p<-(a-d)/(u-d)
STKP<-array(NA,c(n+1,n+1))
STKP[1,1]<-s0
for(j in 2:(n+1))
{
for(i in 1:j)
{
STKP[i,j]<-s0*u^(j-2*i+1)
}
}
APV<-array(NA,c(n+1,n+1))
for(i in 1:(n+1))
{
APV[i,n+1]<-max(k_put-STKP[i,n+1],0)
}
for(j in n:1)
{
for(i in 1:j)
{
epv<-(p*APV[i,j+1]+(1-p)*APV[i+1,j+1])*exp(-r*dt)
APV[i,j]<-max(k_put-STKP[i,j],epv) #choose whether to exercise the option earlier
}
}
return(APV[1,1])
}
##Something I need to mention, I build this j steps binomial tree in a half upper matrix. The final column is a geometric progression, q=1/u^2###
没有评论:
发表评论