waszczek
waszczek

Reputation: 1

Function that adds new column with stock returns using dplyr

I just wanted to create a simple function that adds daily returns column to stock prices data frame.

As a manual stript this looks like this:

AAL <- mutate(AAL, logreturn = Delt(AAL$Price, type = "log"))
rownames(AAL) <- AAL[, 1]
AAL <- AAL[, 2:4]
AAL[1, 3] <- 0

And it works this way. However, I wanted to make a function that does the above by simply entering

head(AAL)
        Date  Price Volume
1 2013-06-28 7.5839  31308
2 2013-07-01 7.2093   1054
3 2013-07-02 7.3098    109
4 2013-07-03 7.0539   1275
5 2013-07-04 7.0448     22
6 2013-07-05 7.0357    110

add_returns(AAL)


head(AAL)
            Price Volume   Delt.1.log
2013-06-28 7.5839  31308  0.000000000
2013-07-01 7.2093   1054 -0.050655720
2013-07-02 7.3098    109  0.013844054
2013-07-03 7.0539   1275 -0.035635258
2013-07-04 7.0448     22 -0.001290899
2013-07-05 7.0357    110 -0.001292568

I tried to do it this way but it doesn't work:

add_return <- function(symbol){

  symbol <- mutate(eval(parse(text = paste0(symbol, collapse = "")), 
                   logreturn =
 Delt(eval(parse(text = paste0(symbol, "$Price", collapse = ""))), 
                                        type = "log"))

rownames(symbol) <- eval(parse(text = paste0(symbol, "$Date", collapse = "")))

symbol <- eval(parse(text = paste0(symbol, "[2:4]", collapse = "")))

eval(parse(text = paste0(symbol, "[1, 3]", collapse = ""))) <- 0

}

Upvotes: 0

Views: 384

Answers (1)

talat
talat

Reputation: 70266

If you only want to be able to pass the data set's name programmatically, you can do it quite easily, for example like this (almost exactly the same as in your "manual" skript):

add_return <- function(data) {
  data <- transform(data, logreturn = Delt(Price, type = "log"))
  rownames(data) <- data[, 1]
  data <- data[, 2:4]
  data[1, 3] <- 0
  return(data)
}

Then, you would call your function using:

add_return(AAL)
#            Price Volume   Delt.1.log
#2013-06-28 7.5839  31308  0.000000000
#2013-07-01 7.2093   1054 -0.050655720
#2013-07-02 7.3098    109  0.013844054
#2013-07-03 7.0539   1275 -0.035635258
#2013-07-04 7.0448     22 -0.001290899
#2013-07-05 7.0357    110 -0.001292568

Having said that, it would be a different story if you wanted your function to allow other inputs progammatically, like the column names to work on or the name of the new column etc. (In this case, you'd probably want to look at dplyr's non-standard evaluation vignette.) But judging by your question and attempt to formulate the function, that is not what you intended to do.


If you want to permanently change the data in the global environment, the standard R-way of doing it would be:

AAL <- add_return(AAL)

Assignment from inside a function to the global environment is usually not recommended, so I would just stick to this standard way which seems easy enough in this case.

Upvotes: 1

Related Questions