0

我有一个时间序列,并根据股价计算了两个趋势。当 SMA.15(蓝线)与 SMA.15(红线)交叉时我试图在图上添加类似 ˄ 的标签

AAPL %>%
    select(date, close, SMA.15, SMA.50) %>%
    gather(key = type, value = price, close:SMA.50) %>%
    ggplot(aes(x = date, y = price, col = type)) +
    geom_line() +
    theme(legend.position="bottom") +
    ggtitle("Simple Moving Averages with tidyquant") +
    xlab("") + 
    ylab("Stock Price")

在此处输入图像描述

4

1 回答 1

2

这是使用ggplot2::economics数据集的示例。我缩放这些值,以便它们一起绘制有意义,并使用滚动平均值平滑。然后,您可以通过查找变量接近的日期来查看一些候选交叉点。在这里,我选择第二行并添加一个小的 y 调整,以便^指向交叉点而不是交叉点。

library(tidyverse)
ts <- economics %>%
  mutate_at(vars(psavert, pce, unemploy), ~ `attributes<-`(scale(.), NULL)) %>%
  mutate_at(vars(psavert, pce, unemploy), ~ RcppRoll::roll_mean(., 5, fill = NA)) %>%
  select(date, psavert, pce, unemploy)

pts <- ts %>%
  mutate(diff = abs(pce - unemploy)) %>%
  arrange(diff)
head(pts, 3)
#> # A tibble: 3 x 5
#>   date       psavert     pce unemploy     diff
#>   <date>       <dbl>   <dbl>    <dbl>    <dbl>
#> 1 1988-07-01 -0.0181 -0.415   -0.415  0.000596
#> 2 2012-08-01 -0.383   1.75     1.76   0.00191 
#> 3 1994-09-01 -0.530  -0.0122  -0.0180 0.00577

ggplot(ts %>% gather(type, value, psavert:unemploy)) +
  geom_line(aes(x = date, y = value, col = type)) +
  annotate("text", x = pts$date[2], y = pts$pce[2] - 0.1, label = "^")
#> Warning: Removed 12 rows containing missing values (geom_path).

reprex 包(v0.2.0)于 2018 年 4 月 9 日创建。

于 2018-04-09T21:04:42.933 回答