Home > Net >  writing a if-else-then fucntion
writing a if-else-then fucntion

Time:11-22

I am trying to write a function to call a function from a package, snippets as below:

library(optionstrat)

# sameple detla 
# do not run 
# calldelta(s,x,sigma,t,r)
# putdelta(s,x,sigma,t,r)

x=10
sigma=0.25
t=0.25
r=0.05

delta<-function(option_type,stock_price) { 
    if (option_type="c") {
        delta<-calldelta(s,x,sigma,t,r)
    } else {
        delta<-putdelta(s,x,sigma,t,r)
    }
}

both calldelta and putdelta are built in functions from optionstrat package, and I would like to write a function so that if option_type="c", then return with a call delta value based on the stock price input. Likewise, if option_type!="c", then return with a put delta value based on the stock price input.

My end goal here is to come up with a function like delta(c,10) then return with a call delta value based on stock price 10. May I know how should I do from here? Thanks.

Update 1:

Now I try working with the below snippets:

x=10
sigma=0.25
t=0.25
r=0.05

stock_delta<-function(option_type,s) { 
    if (option_type="c") {
        delta<-calldelta(s,x,sigma,t,r)
    } else {
        delta<-putdelta(s,x,sigma,t,r)
    }
}

And again, if I define optiontype equals to c & s equals to 10, the same warning msg is returned...

Update 2:

Thanks to @akrun, now the function is created & now I would like to add one more return value from the delta function by adding:

calleval(s,x,sigma,t,r)$Gamma
puteval(s,x,sigma,t,r)$Gamma

The first line will return with the call gamma value & the latter will return with put gamma. May I know how do I string it with the function written previously?

CodePudding user response:

There are multiple issues in the function - 1) function arguments passed should match the arguments to the inner function, 2) = is assignment and == is comparison operator, 3) if the last statement is assigned to an object, it wouldn't print on the console. We may either need to return(delta) or in this case there is no need to create an object delta inside (when the function name is also the same), 4) Passing unquoted argument (c) checks for object name c and even have an additional issue as c is also a function name. Instead, pass a string "c" as is expected in the if condition

delta<-function(option_type,stock_price)
{

 if (option_type=="c")
    calldelta(stock_price,x,sigma,t,r)
else
    putdelta(stock_price,x,sigma,t,r)
}

-testing

> delta("c", 10)
[1] 0.5645439
  •  Tags:  
  • r
  • Related