根据趋势行为

时间:2018-04-09 18:59:23

标签: r ggplot2 tidyquant

我有一个时间序列,并根据股价计算两个趋势。当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")

enter image description here

1 个答案:

答案 0 :(得分: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 package(v0.2.0)创建于2018-04-09。