如何识别连续5次涨价的序列?
How to identify sequences of price increasing for 5 times in a row?
我有一列过去 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 }
你的这个 post 标签说 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
我有一列过去 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 }
你的这个 post 标签说 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