【发布时间】:2014-06-16 02:11:43
【问题描述】:
我有一些用于获取股票价格和计算每月回报的代码。如果用于计算的价格在月底没有出现,我想放弃最后的回报。例如,运行下面的代码会返回 2014-06-13 的价格。而且,即使还没有满月,monthlyReturn 函数也会计算六月的回报。是否有一种简单的方法可以确保monthlyReturn 仅计算整月的回报,或者如果不是根据整月的价格计算,则将最后一个月从回报向量中删除?
library(quantmod)
symbols <- c('XLY', 'XLP', 'XLE', 'XLF', 'XLV', 'XLI', 'XLB', 'XLK', 'XLU')
Stock <- xts()
Prices <- xts()
for (i in 1:length(symbols)){
Stock <- getSymbols(symbols[i],auto.assign = FALSE)
Prices <- merge(Prices,Stock[,6])
}
returns <- do.call(cbind, lapply(Prices, monthlyReturn, leading=FALSE))
names(returns) <- symbols
我找到了这段代码,但它似乎有一些限制。有什么办法可以改善吗?
if(tail(index(x.xts),1) != as.Date(as.yearmon(tail(index(x.xts),1)), frac=1)){
x.m.xts = x.m.xts[-dim(x.m.xts)[1],]
}
# That test isn't quite right, but its close. It won't work on the first
# day of a new month when the last business day wasn't the last day of
# the month. It will work for the second day.
【问题讨论】:
-
你的例子不是很清楚。我假设您想更改
monthlyReturn函数的行为?也许您可以编辑您的问题以简化并清楚地指出您使用上述代码获得的内容与您想要获得的内容之间的差异。 -
抱歉 - 为了清楚起见,我尝试进行编辑。如果还不清楚,请告诉我。