我在一张图中绘制两个时间序列时遇到问题。我从 Yahoo! 下载了两个时间序列金融。数据正常。我可以很好地分别绘制它们,但是当我想将它们绘制在一起以比较它们的动态时,R 没有创建我需要的图。我使用了 https://rpubs.com/odenipinedo/visualizing-time-series-data-in-R 中的脚本,但没有帮助。然而,这个网站上显示的情节是我需要的,也是R应该做的。
我个人认为问题在于日期所在的索引。由于图形需要 x 和 y,其中 y 是时间序列数据,x 应该是日期(例如 2022-02-20),但 R 与图形不匹配。
lapply(c("quantmod", "dplyr", "tidyr", "timeSeries", "ggplot2"), require, character.only = TRUE)
tickers <- c("TSN", "^GSPC")
start_date <- "2022-02-20"
portfolioPrices <- NULL
for (Ticker in tickers)
portfolioPrices <- cbind(portfolioPrices,
getSymbols(Ticker, from = start_date, src = "yahoo", auto.assign=FALSE)[,4])
portfolioPrices <- portfolioPrices[apply(portfolioPrices,1,function(x) all(!is.na(x))),]
colnames(portfolioPrices) <- tickers
portfolioReturns <- ROC(portfolioPrices, type = "discrete")
portfolioReturns <-as.timeSeries(portfolioPrices)
plot(portfolioReturns$TSN)
lines(portfolioReturns$`^GSPC`, col = "red")
axis(side = 4, at = pretty(portfolioReturns$`^GSPC`)
我检查了几个网站和 youtube 视频,但没有任何帮助。我尝试了 ggplot 和 ggseas 包,但它们也没有帮助。结果应该类似于这个截图:
这里有两个情节。
autoplot
加上重新排列一些元素、颜色、标题、背景面板;suppressPackageStartupMessages({
library(quantmod)
library(dplyr)
library(ggplot2)
})
tickers <- c("TSN", "^GSPC")
start_date <- "2022-02-20"
portfolioPrices <- NULL
for (Ticker in tickers) {
portfolioPrices <- cbind(portfolioPrices,
getSymbols(Ticker, from = start_date, src = "yahoo", auto.assign=FALSE)[,4])
}
head(portfolioPrices)
#> TSN.Close GSPC.Close
#> 2022-02-22 92.44 4304.76
#> 2022-02-23 91.99 4225.50
#> 2022-02-24 90.33 4288.70
#> 2022-02-25 93.37 4384.65
#> 2022-02-28 92.66 4373.94
#> 2022-03-01 93.83 4306.26
portfolioPrices <- portfolioPrices[apply(portfolioPrices,1,function(x) all(!is.na(x))),]
colnames(portfolioPrices) <- c("TSN", "GSPC")
portfolioReturns <- ROC(portfolioPrices, type = "discrete")
autoplot(portfolioReturns, facets = NULL) +
scale_color_manual(values = c(TSN = "black", GSPC = "red")) +
ggtitle("Stock Returns") +
theme_bw()
#> Warning: Removed 2 rows containing missing values (`geom_line()`).
Prices <- fortify(portfolioPrices)
(fac <- with(Prices, range(TSN)/range(GSPC)))
#> [1] 0.01676810 0.02124536
fac <- max(fac)
ggplot(data = Prices, aes(Index, TSN)) +
geom_line(aes(color = "TSN")) +
geom_line(aes(y = GSPC * fac, color = "GSPC")) +
scale_x_date(date_breaks = "1 year", date_labels = "%b %Y") +
scale_color_manual(values = c(TSN = "red", GSPC = "black")) +
scale_y_continuous(sec.axis = sec_axis(~ . / fac, name = "GSPC Close Prices")) +
labs(x = "Date", y = "TSN Close Price", color = "") +
ggtitle("Stock Price") +
theme_bw()
创建于 2023-02-23 与 reprex v2.0.2