贸易分类的刻度测试

时间:2018-07-25 16:48:24

标签: r if-statement trading

在写硕士论文时,我已经下载了交易数据:

  >head(Data1)
  PRICE PREVIOUS
1 100   99
2 98    100
3 100   98
4 100   100
5 100   100
6 101   100      

目标是添加一列,该列指示交易是由买方(“购买”)还是卖方(“出售”)发起的。规则如下:

  • 价格<上一个=>出售
  • 价格>上一个=>购买
  • 价格==上一个=>先前的分类

这是它的外观

      >head(Data1)
     PRICE PREVIOUS TICK
    1 100   99       Buy
    2 98    100      Sell
    3 100   98       Buy
    4 100   100      Buy
    5 100   100      Buy
    6 101   100      Buy

我写了以下代码:

Data1$TICK <- ifelse(Data1$PRICE == Data1$PREVIOUS, yes = shift(Data1[ ,3]), no = ifelse(Data1$PRICE>Data1$PREVIOUS, yes= "Buy", no = "Sell"))

但是,当我尝试执行代码时,得到警告:

  

[.data.frame(数据1,3)中的错误:未定义的列已选中

因此,我有两个问题:

  1. 此代码是否能够提供我想要获得的结果?
  2. 错误消息指的是什么?

2 个答案:

答案 0 :(得分:1)

library(tidyverse)
dat%>%
  mutate(m = sign(PRICE-PREVIOUS),
         m=replace(m,m == 0,NA))%>%
  fill(m)%>%
  mutate(m = if_else(m==1,"Buy","Sale"))
  PRICE PREVIOUS    m
1   100       99  Buy
2    98      100 Sale
3   100       98  Buy
4   100      100  Buy
5   100      100  Buy
6   101      100  Buy

答案 1 :(得分:1)

这里是使用base的简单方法。

data1 <- data.frame(PRICE = c(100,98,100,100,100,101), PREVIOUS = c(99,100,98,100,100,100))

tk <- c("Sell", NA, "Buy")[sign(data1$PRICE-data1$PREVIOUS)+2]
for(i in 2:length(tk)) if (is.na(tk[i])) tk[i] <- tk[i-1]

data1$TICK <- tk
print(data1)

#   PRICE PREVIOUS TICK
# 1   100       99  Buy
# 2    98      100 Sell
# 3   100       98  Buy
# 4   100      100  Buy
# 5   100      100  Buy
# 6   101      100  Buy

如果您认为它更直观,则可以:

tk <- c("Sell", "Prior", "Buy")[sign(data1$PRICE-data1$PREVIOUS)+2]
for(i in 2:length(tk)) if (tk[i] == "Prior") tk[i] <- tk[i-1]