Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

writing a if-else-then fucntion

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading