Matthew Oldham
Matthew Oldham

Reputation: 189

Using lapply with quantmod to get monthly returns

I have the following code, its intention is to download a selection of stocks and then calculate the monthly returns of those stocks. Everything goes ok until I use the lapply function. This example returns the same results for each stock. Other attempts were also wrong

NB symbols can also be like symbols <- c("AAPL", "GOOG", "GE")

tickerlist <- "sp5001.csv"  #CSV containing tickers on rows
startDate = as.Date("2013-10-01") #Specify what date to get the prices from
endDate = as.Date("2016-09-30")
stocksLst <- read.csv("sp5001.csv", header = F, stringsAsFactors = F)
symbols <- read.csv("sp5001.csv", header = F)$V1
symbols <-as.character(symbols)
nrstocks = length(stocksLst[,1])

data.env <- new.env()
getSymbols(symbols, env = data.env ,from= startDate ,to= endDate)
dataX <-do.call(merge, eapply(data.env, Ad)[symbols])

Temp <- lapply(symbols, function(symbols) {monthlyReturn(dataX)})
What_I_need <- do.call(merge.xts,Temp)

The What_I_need data.frame/xts looks like this - which is wrong.

            monthly.returns monthly.returns.1 monthly.returns.2
2013-10-31     0.071194294       0.071194294       0.071194294
2013-11-29     0.070052705       0.070052705       0.070052705
2013-12-31     0.008901793       0.008901793       0.008901793
2014-01-31    -0.107696737      -0.107696737      -0.107696737

Upvotes: 1

Views: 919

Answers (1)

hvollmeier
hvollmeier

Reputation: 2986

If you change the line where you create the variable Temp to :

Temp <- lapply(1:length(symbols), function(x) {monthlyReturn(dataX[,x])})

it works.

I think an easier to maintain, more flexible method to do this kind of calculations ( where you keep the correct column names as well ) is to use the package qmao (find it here) which has 2 very useful functions PF and RF which stand for PriceFrame and ReturnFrame. i.e.

    library(qmao)
    symbols <- c('AAPL','AMZN')
    data.env <- new.env()
    getSymbols(symbols, env = data.env ,from= startDate ,to= endDate)
    pf <- PF(symbols,env = data.env,silent=TRUE) # consolidated xts-object
    pfMth <- pf[endpoints(pf,on='months'),]   # get monthly endpoints
    pfMthRets <- ROC(pfMth,type='discrete')       
    tail(pfMthRets)
                      AAPL         AMZN
    2016-04-29 -0.13992110  0.111094283
    2016-05-31  0.07177292  0.095817020
    2016-06-30 -0.04265974 -0.009919871
    2016-07-29  0.09006276  0.060353265
    2016-08-31  0.02365190  0.013639745
    2016-09-30  0.06550429  0.088603187

Upvotes: 2

Related Questions