将组添加到DF以收盘价

时间:2018-07-27 20:25:58

标签: r

我正在创建一个假设方案,在该方案中,我根据收盘价是涨还是跌来交易一只股票。如果股票收盘价较低,然后在前一天收盘,则我要添加一个“ S”(卖出);如果它收盘价高于前一天的收盘价,那么我要添加“ B”。因此,我想添加这些S和B标签,然后计算差额,即每日利润。

这是我正在测试的代码。

library(dplyr)
library(data.table)
library(quantmod)
library(zoo)

# enter tickers to download time-series data
e <- new.env()
getSymbols("SBUX", env = e)
pframe <- do.call(merge, as.list(e))
#head(pframe)


# get a subset of data
df = pframe$SBUX.Close

colnames(df)[1] <- "Close"
head(df)

# Assign groupings
addGrps <- df %>% mutate(Group = ifelse(Close < lead(Close), "S", "B"))

# create subsets
buys <- filter(addGrps, Group == "B")
sells <- filter(addGrps, Group == "S")


# find daily differences
dt2 <- df %>%
mutate(Diff = Close - lead(Close))

# get up and down price movements
ups <- filter(df2, Diff > 0 )
downs <- filter(df2, Diff <= 0 )

# cumulative sums of longs and shorts
longs<-cumsum(ups$Diff)
shorts<-cumsum(downs$Diff)

“ addGrps”之前的所有内容都可以正常工作。当我到达“ addGrps”行时,出现以下错误:'UseMethod(“ mutate_”)中的错误:   没有适用于'mutate_'的适用方法应用于类“ c('xts','zoo')”'

的对象

这只是优化交易的一个假设示例,如果您以某种方式知道在一天开始时股票将关闭的情况。显然这是不可能的。我只是想让这个概念生效。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

突变和过滤器不适用于动物园。 而是使用:

# Assign groupings
transform(df,Group = ifelse(Close < lead(Close), "S", "B"))
# create subsets
buys <- addGrps[addGrps$Group == "B"]
sells <- addGrps[addGrps$Group == "S"]


# find daily differences
df2 <- transform(df,Diff = Close - lead(Close))

# get up and down price movements
ups <- df2[df2$Diff > 0]
downs <- df2[df2$Diff <= 0]

# cumulative sums of longs and shorts
longs<-cumsum(ups$Diff)
shorts<-cumsum(downs$Diff)