How to use uniroot to solve a user-defined function (UDF) in a dataframe?How to sort a dataframe by multiple column(s)How do I replace NA values with zeros in an R dataframe?How to change the order of DataFrame columns?How to drop rows of Pandas DataFrame whose value in certain columns is NaNHow do I get the row count of a pandas DataFrame?How to iterate over rows in a DataFrame in Pandas?R: Volatility function that interprets NAsr - trying to make a function write to the same dataframeSpark Scala - How to group dataframe rows and apply complex function to the groups?Pass data frame as argument, and return vector in R

Is there any evidence to support the claim that the United States was "suckered into WW1" by Zionists, made by Benjamin Freedman in his 1961 speech?

On studying Computer Science vs. Software Engineering to become a proficient coder

Increase height of laser cut design file for enclosure

Does Lawful Interception of 4G / the proposed 5G provide a back door for hackers as well?

Can 'sudo apt-get remove [write]' destroy my Ubuntu?

find not returning expected files

As programers say: Strive to be lazy

semanage not changing file context

Why do Thanos's punches not kill Captain America or at least cause some mortal injuries?

Renting a house to a graduate student in my department

How are Core iX names like Core i5, i7 related to Haswell, Ivy Bridge?

Why did God specifically target the firstborn in the 10th plague (Exodus 12:29-36)?

Noob at soldering, can anyone explain why my circuit won't work?

Can I do brevets (long distance rides) on my hybrid bike? If yes, how to start?

Should these notes be played as a chord or one after another?

Why in a Ethernet LAN, a packet sniffer can obtain all packets sent over the LAN?

Ubuntu won't let me edit or delete .vimrc file

What are some possible reasons that a father's name is missing from a birth certificate - England?

What does i386 mean on macOS Mojave?

Why can't RGB or bicolour LEDs produce a decent yellow?

Looking for a simple way to manipulate one column of a matrix

Remove everything except csv file Bash Script

How could we transfer large amounts of energy sourced in space to Earth?

Was the Highlands Ranch shooting the 115th mass shooting in the US in 2019



How to use uniroot to solve a user-defined function (UDF) in a dataframe?


How to sort a dataframe by multiple column(s)How do I replace NA values with zeros in an R dataframe?How to change the order of DataFrame columns?How to drop rows of Pandas DataFrame whose value in certain columns is NaNHow do I get the row count of a pandas DataFrame?How to iterate over rows in a DataFrame in Pandas?R: Volatility function that interprets NAsr - trying to make a function write to the same dataframeSpark Scala - How to group dataframe rows and apply complex function to the groups?Pass data frame as argument, and return vector in R






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















I have a dataframe and want to use uniroot on each row to solve Implied Volatility based on Black-Scholes formula. What is the correct way to use uniroot.all to solve for each row? It should produce a new column vector of results.



The code below has this error




"Error in S/K : non-numeric argument to binary operator"




. I suspect the trouble comes when uniroot is trying to solve multiple rows instead of each row one-by-one.



I've tried to modify to a vectorized version of the bscall function but this doesn't seem to best way to do it.



df <- data.frame( strike = c(80,120,100,100), 
type = c("C", "C", "C","C"),
optionPrice = c(22,3,7,9),
futurePrice = c(100, 100,100,100),
time_to_expiry = c(0.1, 0.1,1,1.2))

bscall <-
function (S,K,r,T,sig)
d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
d2 <- d1 - sig*sqrt(T)
price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
return(price)



apply(df, 1,
function(z) uniroot.all( function(x) bscall(z[4],z[1],r,z[5],x) - z[3], interval = c(0,1) ))









share|improve this question






























    -1















    I have a dataframe and want to use uniroot on each row to solve Implied Volatility based on Black-Scholes formula. What is the correct way to use uniroot.all to solve for each row? It should produce a new column vector of results.



    The code below has this error




    "Error in S/K : non-numeric argument to binary operator"




    . I suspect the trouble comes when uniroot is trying to solve multiple rows instead of each row one-by-one.



    I've tried to modify to a vectorized version of the bscall function but this doesn't seem to best way to do it.



    df <- data.frame( strike = c(80,120,100,100), 
    type = c("C", "C", "C","C"),
    optionPrice = c(22,3,7,9),
    futurePrice = c(100, 100,100,100),
    time_to_expiry = c(0.1, 0.1,1,1.2))

    bscall <-
    function (S,K,r,T,sig)
    d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
    d2 <- d1 - sig*sqrt(T)
    price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
    return(price)



    apply(df, 1,
    function(z) uniroot.all( function(x) bscall(z[4],z[1],r,z[5],x) - z[3], interval = c(0,1) ))









    share|improve this question


























      -1












      -1








      -1








      I have a dataframe and want to use uniroot on each row to solve Implied Volatility based on Black-Scholes formula. What is the correct way to use uniroot.all to solve for each row? It should produce a new column vector of results.



      The code below has this error




      "Error in S/K : non-numeric argument to binary operator"




      . I suspect the trouble comes when uniroot is trying to solve multiple rows instead of each row one-by-one.



      I've tried to modify to a vectorized version of the bscall function but this doesn't seem to best way to do it.



      df <- data.frame( strike = c(80,120,100,100), 
      type = c("C", "C", "C","C"),
      optionPrice = c(22,3,7,9),
      futurePrice = c(100, 100,100,100),
      time_to_expiry = c(0.1, 0.1,1,1.2))

      bscall <-
      function (S,K,r,T,sig)
      d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
      d2 <- d1 - sig*sqrt(T)
      price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
      return(price)



      apply(df, 1,
      function(z) uniroot.all( function(x) bscall(z[4],z[1],r,z[5],x) - z[3], interval = c(0,1) ))









      share|improve this question
















      I have a dataframe and want to use uniroot on each row to solve Implied Volatility based on Black-Scholes formula. What is the correct way to use uniroot.all to solve for each row? It should produce a new column vector of results.



      The code below has this error




      "Error in S/K : non-numeric argument to binary operator"




      . I suspect the trouble comes when uniroot is trying to solve multiple rows instead of each row one-by-one.



      I've tried to modify to a vectorized version of the bscall function but this doesn't seem to best way to do it.



      df <- data.frame( strike = c(80,120,100,100), 
      type = c("C", "C", "C","C"),
      optionPrice = c(22,3,7,9),
      futurePrice = c(100, 100,100,100),
      time_to_expiry = c(0.1, 0.1,1,1.2))

      bscall <-
      function (S,K,r,T,sig)
      d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
      d2 <- d1 - sig*sqrt(T)
      price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
      return(price)



      apply(df, 1,
      function(z) uniroot.all( function(x) bscall(z[4],z[1],r,z[5],x) - z[3], interval = c(0,1) ))






      r dataframe user-defined-functions






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 23 at 10:54









      LocoGris

      2,8182828




      2,8182828










      asked Mar 23 at 10:45









      Joel PangJoel Pang

      11




      11






















          2 Answers
          2






          active

          oldest

          votes


















          0














          The first row of df is 80, "C", 22, 100, 0.1. It contains a character string. Therefore, when you do apply(df, 1, ....), the rows are coerced to character vectors:



          df <- data.frame( strike = c(80,120,100,100), 
          type = c("C", "C", "C","C"),
          optionPrice = c(22,3,7,9),
          futurePrice = c(100, 100,100,100),
          time_to_expiry = c(0.1, 0.1,1,1.2))

          apply(df, 1, function(z) z)
          # [,1] [,2] [,3] [,4]
          # strike " 80" "120" "100" "100"
          # type "C" "C" "C" "C"
          # optionPrice "22" " 3" " 7" " 9"
          # futurePrice "100" "100" "100" "100"
          # time_to_expiry "0.1" "0.1" "1.0" "1.2"





          share|improve this answer






























            0














            First: you should include the library statement you used for package rootSolve.
            Where are variables r and sig defined?



            There is no need for uniroot.all as you can see by inspecting function bscall. There is no need for iteration; price is calculated directly from the input.



            Define df as follows taking into account the first answer.



            df <- data.frame( strike = c(80,120,100,100), 
            # type = c("C", "C", "C","C"),
            optionPrice = c(22,3,7,9),
            futurePrice = c(100, 100,100,100),
            time_to_expiry = c(0.1, 0.1,1,1.2))


            Column type has been commented out.



            Define your function bscall as



            bscall <-
            function (S,K,r,T,sig)
            d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
            d2 <- d1 - sig*sqrt(T)
            price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
            return(price)



            Give r and sig a value



            r <- .05
            sig <- 1


            Apply your function to rows of df (indices into z changed because of change to df)



            apply(df, 1,
            function(z) bscall(z[3],z[1],r,z[4],sig) - z[2])


            giving



            [1] 2.258107 3.168623 32.840162 34.366636


            as answer.



            The rest is up to you.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55312889%2fhow-to-use-uniroot-to-solve-a-user-defined-function-udf-in-a-dataframe%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              The first row of df is 80, "C", 22, 100, 0.1. It contains a character string. Therefore, when you do apply(df, 1, ....), the rows are coerced to character vectors:



              df <- data.frame( strike = c(80,120,100,100), 
              type = c("C", "C", "C","C"),
              optionPrice = c(22,3,7,9),
              futurePrice = c(100, 100,100,100),
              time_to_expiry = c(0.1, 0.1,1,1.2))

              apply(df, 1, function(z) z)
              # [,1] [,2] [,3] [,4]
              # strike " 80" "120" "100" "100"
              # type "C" "C" "C" "C"
              # optionPrice "22" " 3" " 7" " 9"
              # futurePrice "100" "100" "100" "100"
              # time_to_expiry "0.1" "0.1" "1.0" "1.2"





              share|improve this answer



























                0














                The first row of df is 80, "C", 22, 100, 0.1. It contains a character string. Therefore, when you do apply(df, 1, ....), the rows are coerced to character vectors:



                df <- data.frame( strike = c(80,120,100,100), 
                type = c("C", "C", "C","C"),
                optionPrice = c(22,3,7,9),
                futurePrice = c(100, 100,100,100),
                time_to_expiry = c(0.1, 0.1,1,1.2))

                apply(df, 1, function(z) z)
                # [,1] [,2] [,3] [,4]
                # strike " 80" "120" "100" "100"
                # type "C" "C" "C" "C"
                # optionPrice "22" " 3" " 7" " 9"
                # futurePrice "100" "100" "100" "100"
                # time_to_expiry "0.1" "0.1" "1.0" "1.2"





                share|improve this answer

























                  0












                  0








                  0







                  The first row of df is 80, "C", 22, 100, 0.1. It contains a character string. Therefore, when you do apply(df, 1, ....), the rows are coerced to character vectors:



                  df <- data.frame( strike = c(80,120,100,100), 
                  type = c("C", "C", "C","C"),
                  optionPrice = c(22,3,7,9),
                  futurePrice = c(100, 100,100,100),
                  time_to_expiry = c(0.1, 0.1,1,1.2))

                  apply(df, 1, function(z) z)
                  # [,1] [,2] [,3] [,4]
                  # strike " 80" "120" "100" "100"
                  # type "C" "C" "C" "C"
                  # optionPrice "22" " 3" " 7" " 9"
                  # futurePrice "100" "100" "100" "100"
                  # time_to_expiry "0.1" "0.1" "1.0" "1.2"





                  share|improve this answer













                  The first row of df is 80, "C", 22, 100, 0.1. It contains a character string. Therefore, when you do apply(df, 1, ....), the rows are coerced to character vectors:



                  df <- data.frame( strike = c(80,120,100,100), 
                  type = c("C", "C", "C","C"),
                  optionPrice = c(22,3,7,9),
                  futurePrice = c(100, 100,100,100),
                  time_to_expiry = c(0.1, 0.1,1,1.2))

                  apply(df, 1, function(z) z)
                  # [,1] [,2] [,3] [,4]
                  # strike " 80" "120" "100" "100"
                  # type "C" "C" "C" "C"
                  # optionPrice "22" " 3" " 7" " 9"
                  # futurePrice "100" "100" "100" "100"
                  # time_to_expiry "0.1" "0.1" "1.0" "1.2"






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 23 at 11:23









                  Stéphane LaurentStéphane Laurent

                  17.3k756100




                  17.3k756100























                      0














                      First: you should include the library statement you used for package rootSolve.
                      Where are variables r and sig defined?



                      There is no need for uniroot.all as you can see by inspecting function bscall. There is no need for iteration; price is calculated directly from the input.



                      Define df as follows taking into account the first answer.



                      df <- data.frame( strike = c(80,120,100,100), 
                      # type = c("C", "C", "C","C"),
                      optionPrice = c(22,3,7,9),
                      futurePrice = c(100, 100,100,100),
                      time_to_expiry = c(0.1, 0.1,1,1.2))


                      Column type has been commented out.



                      Define your function bscall as



                      bscall <-
                      function (S,K,r,T,sig)
                      d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
                      d2 <- d1 - sig*sqrt(T)
                      price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
                      return(price)



                      Give r and sig a value



                      r <- .05
                      sig <- 1


                      Apply your function to rows of df (indices into z changed because of change to df)



                      apply(df, 1,
                      function(z) bscall(z[3],z[1],r,z[4],sig) - z[2])


                      giving



                      [1] 2.258107 3.168623 32.840162 34.366636


                      as answer.



                      The rest is up to you.






                      share|improve this answer



























                        0














                        First: you should include the library statement you used for package rootSolve.
                        Where are variables r and sig defined?



                        There is no need for uniroot.all as you can see by inspecting function bscall. There is no need for iteration; price is calculated directly from the input.



                        Define df as follows taking into account the first answer.



                        df <- data.frame( strike = c(80,120,100,100), 
                        # type = c("C", "C", "C","C"),
                        optionPrice = c(22,3,7,9),
                        futurePrice = c(100, 100,100,100),
                        time_to_expiry = c(0.1, 0.1,1,1.2))


                        Column type has been commented out.



                        Define your function bscall as



                        bscall <-
                        function (S,K,r,T,sig)
                        d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
                        d2 <- d1 - sig*sqrt(T)
                        price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
                        return(price)



                        Give r and sig a value



                        r <- .05
                        sig <- 1


                        Apply your function to rows of df (indices into z changed because of change to df)



                        apply(df, 1,
                        function(z) bscall(z[3],z[1],r,z[4],sig) - z[2])


                        giving



                        [1] 2.258107 3.168623 32.840162 34.366636


                        as answer.



                        The rest is up to you.






                        share|improve this answer

























                          0












                          0








                          0







                          First: you should include the library statement you used for package rootSolve.
                          Where are variables r and sig defined?



                          There is no need for uniroot.all as you can see by inspecting function bscall. There is no need for iteration; price is calculated directly from the input.



                          Define df as follows taking into account the first answer.



                          df <- data.frame( strike = c(80,120,100,100), 
                          # type = c("C", "C", "C","C"),
                          optionPrice = c(22,3,7,9),
                          futurePrice = c(100, 100,100,100),
                          time_to_expiry = c(0.1, 0.1,1,1.2))


                          Column type has been commented out.



                          Define your function bscall as



                          bscall <-
                          function (S,K,r,T,sig)
                          d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
                          d2 <- d1 - sig*sqrt(T)
                          price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
                          return(price)



                          Give r and sig a value



                          r <- .05
                          sig <- 1


                          Apply your function to rows of df (indices into z changed because of change to df)



                          apply(df, 1,
                          function(z) bscall(z[3],z[1],r,z[4],sig) - z[2])


                          giving



                          [1] 2.258107 3.168623 32.840162 34.366636


                          as answer.



                          The rest is up to you.






                          share|improve this answer













                          First: you should include the library statement you used for package rootSolve.
                          Where are variables r and sig defined?



                          There is no need for uniroot.all as you can see by inspecting function bscall. There is no need for iteration; price is calculated directly from the input.



                          Define df as follows taking into account the first answer.



                          df <- data.frame( strike = c(80,120,100,100), 
                          # type = c("C", "C", "C","C"),
                          optionPrice = c(22,3,7,9),
                          futurePrice = c(100, 100,100,100),
                          time_to_expiry = c(0.1, 0.1,1,1.2))


                          Column type has been commented out.



                          Define your function bscall as



                          bscall <-
                          function (S,K,r,T,sig)
                          d1 <- (log(S/K)+(r+0.5*sig^2)*T) / (sig*sqrt(T))
                          d2 <- d1 - sig*sqrt(T)
                          price <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
                          return(price)



                          Give r and sig a value



                          r <- .05
                          sig <- 1


                          Apply your function to rows of df (indices into z changed because of change to df)



                          apply(df, 1,
                          function(z) bscall(z[3],z[1],r,z[4],sig) - z[2])


                          giving



                          [1] 2.258107 3.168623 32.840162 34.366636


                          as answer.



                          The rest is up to you.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 23 at 12:43









                          BhasBhas

                          1,451198




                          1,451198



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55312889%2fhow-to-use-uniroot-to-solve-a-user-defined-function-udf-in-a-dataframe%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript