r - 如何识别连续 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 }
解决方案
您对这篇文章的标签说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
推荐阅读
- javascript - 如何在没有 localStorage 的情况下保留令牌信息?反应 + 还原
- python - 使用 Pandas 展平嵌套字典
- visual-studio-code - Visual Studio 代码扩展开发 - 如何覆盖顶部菜单 F5 部署
- html - 背景图像上的位置按钮
- python - 加载先前训练的模型时奇怪的损失波动
- r - 在 R 中为每组添加缺失的行
- python - 在python中动态生成URL
- javascript - 从对象数组创建选项元素
- ios - 持久存储协调器核心数据错误:NSSQLiteErrorDomain = 522
- angular - Angular FormArray 绑定错误:找不到带有路径的控件:'addressess -> 0 -> street'