问题:在一个图表中绘制两个时间序列的问题。

huangapple go评论71阅读模式
英文:

Issue with plotting two time series in one graph

问题

我有一个绘制两个时间序列在一个图中的问题。我已经从Yahoo! Finance下载了两个时间序列。数据没问题。我可以分别绘制它们,但是当我想要将它们绘制在一起以比较它们的动态时,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包,但它们也没有帮助。结果应该类似于这个截图:图片描述

英文:

I have an issue with plotting two time series in one graph. I have downloaded two time series from Yahoo! Finance. Data is OK. I can plot them separately well, but when I want to plot them together to compare their dynamics, R did not create plot I needed. I used scripts from https://rpubs.com/odenipinedo/visualizing-time-series-data-in-R but it did not help. However, the plot that is shown on this website is what I need and what should be done by R.

I personally think the problem is with index, where the dates are located. As graph needs x and y, where y are time series data, x should be dates (e.g. 2022-02-20), but R did not match graphs.

lapply(c(&quot;quantmod&quot;, &quot;dplyr&quot;, &quot;tidyr&quot;, &quot;timeSeries&quot;, &quot;ggplot2&quot;), require, character.only = TRUE)

tickers &lt;- c(&quot;TSN&quot;, &quot;^GSPC&quot;)
start_date &lt;- &quot;2022-02-20&quot;

portfolioPrices &lt;- NULL
for (Ticker in tickers) 
  portfolioPrices &lt;- cbind(portfolioPrices,
                           getSymbols(Ticker, from = start_date, src = &quot;yahoo&quot;, auto.assign=FALSE)[,4])

portfolioPrices &lt;- portfolioPrices[apply(portfolioPrices,1,function(x) all(!is.na(x))),]
colnames(portfolioPrices) &lt;- tickers
portfolioReturns &lt;- ROC(portfolioPrices, type = &quot;discrete&quot;)
portfolioReturns &lt;-as.timeSeries(portfolioPrices)

plot(portfolioReturns$TSN)
lines(portfolioReturns$`^GSPC`, col = &quot;red&quot;)
axis(side = 4, at = pretty(portfolioReturns$`^GSPC`)

enter image description here))

I have checked several websites and youtube videos, but nothing helped. I tried ggplot and ggseas packages, but they did not help either. The result should be similar to this screenshot:enter image description here

答案1

得分: 1

以下是代码部分的翻译:

  1. 返回图表只是一个调用autoplot的操作,再加上一些元素的重新排列、颜色、标题和背景面板;
  2. 价格图是一个双Y轴图。右边的Y轴的刻度是根据数据计算的一个因子来缩放。
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

英文:

Here are two plots.

  1. The returns plot is simply a call to autoplot plus rearrange some elements, color, title, background panel;
  2. the prices plot is a two y axis plot. The right hand y axis is scaled by a factor computed from the data.
suppressPackageStartupMessages({
  library(quantmod)
  library(dplyr)
  library(ggplot2)
})

tickers &lt;- c(&quot;TSN&quot;, &quot;^GSPC&quot;)
start_date &lt;- &quot;2022-02-20&quot;

portfolioPrices &lt;- NULL
for (Ticker in tickers) {
  portfolioPrices &lt;- cbind(portfolioPrices,
                           getSymbols(Ticker, from = start_date, src = &quot;yahoo&quot;, auto.assign=FALSE)[,4])
}
head(portfolioPrices)
#&gt;            TSN.Close GSPC.Close
#&gt; 2022-02-22     92.44    4304.76
#&gt; 2022-02-23     91.99    4225.50
#&gt; 2022-02-24     90.33    4288.70
#&gt; 2022-02-25     93.37    4384.65
#&gt; 2022-02-28     92.66    4373.94
#&gt; 2022-03-01     93.83    4306.26

portfolioPrices &lt;- portfolioPrices[apply(portfolioPrices,1,function(x) all(!is.na(x))),]
colnames(portfolioPrices) &lt;- c(&quot;TSN&quot;, &quot;GSPC&quot;)
portfolioReturns &lt;- ROC(portfolioPrices, type = &quot;discrete&quot;)

autoplot(portfolioReturns, facets = NULL) +
  scale_color_manual(values = c(TSN = &quot;black&quot;, GSPC = &quot;red&quot;)) +
  ggtitle(&quot;Stock Returns&quot;) +
  theme_bw()
#&gt; Warning: Removed 2 rows containing missing values (`geom_line()`).

问题:在一个图表中绘制两个时间序列的问题。<!-- -->


Prices &lt;- fortify(portfolioPrices)
(fac &lt;- with(Prices, range(TSN)/range(GSPC)))
#&gt; [1] 0.01676810 0.02124536
fac &lt;- max(fac)

ggplot(data = Prices, aes(Index, TSN)) +
  geom_line(aes(color = &quot;TSN&quot;)) +
  geom_line(aes(y = GSPC * fac, color = &quot;GSPC&quot;)) +
  scale_x_date(date_breaks = &quot;1 year&quot;, date_labels = &quot;%b %Y&quot;) +
  scale_color_manual(values = c(TSN = &quot;red&quot;, GSPC = &quot;black&quot;)) +
  scale_y_continuous(sec.axis = sec_axis(~ . / fac, name = &quot;GSPC Close Prices&quot;)) +
  labs(x = &quot;Date&quot;, y = &quot;TSN Close Price&quot;, color = &quot;&quot;) +
  ggtitle(&quot;Stock Price&quot;) +
  theme_bw()

问题:在一个图表中绘制两个时间序列的问题。<!-- -->

<sup>Created on 2023-02-23 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年2月23日 19:58:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定