r——累计复合股票收益



我需要从3只不同的股票中创建100美元的持有回报。

我制作了一个数据框架,其中包含通用电气、IBM和从雅虎获得的NYA指数:

stocks <- as.xts(data.frame(GE = GE[,6], IBM = IBM[,6], NYA = NYA[,6]))

然后,我找到了他们的退货:

stocks_return <- diff(log(stocks))

现在我需要的是创建一个图表,显示如果我投资100美元,所有三个时间序列的持有回报。

我以前解决过类似的问题。这是一个改编版本:

library(PerformanceAnalytics)
library(quantmod)
library(purrr)
library(magrittr)
library(ggplot2)
date <- "2019-01-01"

stocks <- c("GE",
"IBM",
"^NYA")
#get the data
prices  <- stocks %>%
map(~ getSymbols(., auto.assign = FALSE, from = date))
#get adjusted data
precios_ajustados <- prices %>%
map(., Ad)
#calculate returns for each adjusted prices
returns <- precios_ajustados %>%
map(~
Return.calculate(.x)
)
#insert 100 in the first observation (made NA by Return.calculate()) to simulate the investment
for (i in 1:length(stocks)) {
names(returns[[i]]) <- stocks[i]
returns[[i]][1, 1]  <- 100
returns[[i]][-1, 1] <- returns[[i]][-1, 1] + 1 #adding a one so that the cumulative return reflects ups and downs.
}
returns <- returns %>% map(~ cumprod(.)) #for every stock return, calculate the cumulative product.
returns <- set_names(returns, stocks) #settings names for easy calling
plot(returns$IBM)
lines(returns$GE, col = "red")
lines(returns$`^NYA`, col = "blue")

您可以在下载所需的库之前直接获取代码。

最新更新