首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何识别连续5次涨价的序列?

如何识别连续5次涨价的序列?
EN

Stack Overflow用户
提问于 2020-11-07 05:12:44
回答 1查看 26关注 0票数 0

我有一个过去3年的每日股票价格专栏。现在,我想找出价格连续上涨5倍的序列,然后创建一个新列,其中我设置了“buy”。有人能帮我生成这个吗?

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

代码语言:javascript
复制
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 } 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-07 06:04:18

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

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64721652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档