Reputation: 863
Ref made to this post Similar question
I'm downloading a series of symbols and I need to calculate monthly returns for the adjusted close and I just can't seem to get it working. The earlier post I have ref to deal with the issue using ROC @Joshua Ulrich, but this is for daily returns. The other examples uses 'close', which is no good for me.
My starting point:
library('quantmod')
tickers <- c("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE",
"T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
#The following gives me what I need, but using Close instead of Adjusted
stocks_ret <- lapply(tickers, function(sym) monthlyReturn(type = 'log',(na.omit(getSymbols(sym, from='2013-01-01, auto.assign=FALSE)))))
Joshua Ulrich solution (works great, but I got no idea how to turn it into monthly returns):
# create environment to load data into
Data <- new.env()
getSymbols(c("^GSPC",Symbols), from="2007-01-01", env=Data)
# calculate returns, merge, and create data.frame (eapply loops over all
# objects in an environment, applies a function, and returns a list)
Returns <- eapply(Data, function(s) ROC(Ad(s), type="discrete"))
ReturnsDF <- as.data.frame(do.call(merge, Returns))
#adjust column names are re-order columns
colnames(ReturnsDF) <- gsub(".Adjusted","",colnames(ReturnsDF))
ReturnsDF <- ReturnsDF[,c("GSPC",Symbols)]
Then I tried:
Returns <- eapply(Data, function(s) ROC(Ad(s)[endpoints(tickers, on = 'months'),], type="discrete"))
The latter gives me an error message: " Error in try.xts(x, error = "must be either xts-coercible or timeBased")"
However, I cant find a solution to how I can calculate on MONTHLY basis instead og daily.. 'n=21' does not solve the issue..
Anyone??
Upvotes: 0
Views: 1128
Reputation: 614
Chris, this is one way for solving your question
library('quantmod')
library('dplyr')
tickers <- c("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE",
"T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
Stock_Data <- tickers %>% lapply(function(x) getSymbols(x,auto.assign=FALSE)) %>%
lapply(function(x) monthlyReturn(Ad(x)))
Upvotes: 2