R 累积复合股票收益率

R 累积复合股票收益率,r,ggplot2,quantmod,R,Ggplot2,Quantmod,我需要从3种不同的股票中创建100美元的持有回报 我制作了一个包含通用电气、IBM和雅虎NYA指数股票的数据框架: stocks <- as.xts(data.frame(GE = GE[,6], IBM = IBM[,6], NYA = NYA[,6])) 股票我以前解决过类似的问题。这是一个经过改编的版本: library(PerformanceAnalytics) library(quantmod) library(purrr) library(magrittr) library(

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

我制作了一个包含通用电气、IBM和雅虎NYA指数股票的数据框架:

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

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

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")
库(性能分析)
图书馆(quantmod)
图书馆(purrr)
图书馆(magrittr)
图书馆(GG2)

欢迎来到stack overflow。请通过添加以下内容改进您的问题:1。一些样本数据。2.您试图解决问题或实现所需目标的代码。3.您在代码和4中观察到的错误或意外行为。预期结果。帮助我们帮助您您好,欢迎访问堆栈溢出。这是一个关于规划而非定量金融的论坛。为了增加你得到好答案的机会,你应该清楚地解释你持有回报的意思。否则,试着在这里问你的问题:谢谢。现在,OP可以复制您的答案,并将其作为自己的答案提交给家庭作业。@JimG。你怎么知道的?我只是想发布可复制的代码来帮助他。对不起,欢迎来到SO!你的回答似乎还可以。这个问题不好@吉姆·G。。IMO这是一个编程论坛,问题可能是问题,而不是答案。
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")