参考此帖Similar question
我正在下载一系列符号,我需要计算调整后收盘的月度回报,而我似乎无法使其正常运行。我之前的帖子是使用ROC @Joshua Ulrich来解决这个问题,但这是为了每日回报。其他例子使用' close',这对我没有好处。
我的出发点:
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解决方案(效果很好,但我不知道如何将其转化为月度回报):
# 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)]
然后我尝试了:
Returns <- eapply(Data, function(s) ROC(Ad(s)[endpoints(tickers, on = 'months'),], type="discrete"))
后者给我一个错误信息:&#34; try.xts出错(x,错误=&#34;必须是xts-coercible或timeBased&#34;)&#34;
但是,我无法找到一个解决方案,我可以每月计算一次,而不是每天...&#39; n = 21&#39;没有解决问题..
任何??
答案 0 :(得分:2)
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)))