首页 > 解决方案 > 如何识别连续 5 次涨价的序列?

问题描述

我有一列过去 3 年的每日股价。现在,我想找到价格连续上涨 5 倍的序列,然后在我设置“买入”的位置创建一个新列。谁能帮助我如何生成这个?

这就是我尝试过的,但是如果没有太大意义,请抱歉,因为我是初学者

x <- FB[,"Close"] if (x<x+1, x+1<x+2, x+2<x+3, x+3<x+4, x+4<5) { FB$buy <- 1 } 

标签: rdplyrseq

解决方案


您对这篇文章的标签说dplyr,所以我将提供一种dplyr方法而不是基本R方法。这是一种蛮力方法,但应该很容易遵循。

library(dplyr) 

FB <- data.frame(
  "Close" = c(1,2,3,4,5,6,1,2,3,4,1,2,3,4,5,6),
  stringsAsFactors = FALSE
)

# Brute Force dplyr
x <- FB %>%
  mutate(buy = Close>lag(Close,1) & 
           lag(Close,1)>lag(Close,2) & 
           lag(Close,2)>lag(Close,3) & 
           lag(Close,3)>lag(Close,4) & 
           lag(Close,4)>lag(Close,5)
         ) %>%
  # If you really need a 1 instead of a True
  mutate(buy = as.numeric(buy)) # %>%
  # If there weren't 5 previous the result is NA
  # and you can impute something that makes sense
  # if anything makes sense.
  # mutate(buy = ifelse(is.na(buy),0,buy))
x
# Close buy
#     1  NA
#     2  NA
#     3  NA
#     4  NA
#     5  NA
#     6   1
#     1   0
#     2   0
#     3   0
#     4   0
#     1   0
#     2   0
#     3   0
#     4   0
#     5   0
#     6   1

推荐阅读