为一个xts对象填充基于buy的hold

时间:2021-07-15 12:37:19

The example below creates a buy signal (1) when a stock (IBM) has a greater than 10% daily drop in value.

下面的例子创建了一个buy信号(1),当一个股票(IBM)的日跌幅大于10%时。

It then creates a hold signal for 4 additional days. If the number of hold days were to increase, the code would become more unruly. Is there any way to rewrite the holdsig code using either an apply function or something of similar efficiency (i.e., not a for loop)?

然后,它会在4天内创建一个hold信号。如果持有天数增加,代码将变得更加难以控制。有什么方法可以使用apply函数或者类似的效率来重写holdsig代码吗?,而不是for循环)?

library(quantmod)
getSymbols("IBM")
buysig <- Lag(ifelse(dailyReturn(IBM) < -.10,1,0))
holdsig <- ifelse( Lag(sig) == 1 | Lag(sig, k=2) == 1 | Lag(sig, k=3) == 1 | Lag(sig, k=4) == 1, 1, 0)

Every time I feel like I'm getting better with apply, I take two steps backwards.

每当我觉得自己在应用上越来越好时,我就倒退了两步。

1 个解决方案

#1


3  

First, notice that Lag can take a vector of k values:

首先,注意滞后可以取一个k值向量:

head(Lag(buysig, k=1:4)
#            Lag.1 Lag.2 Lag.3 Lag.4
# 2007-01-03    NA    NA    NA    NA
# 2007-01-04    NA    NA    NA    NA
# 2007-01-05     0    NA    NA    NA
# 2007-01-08     0     0    NA    NA
# 2007-01-09     0     0     0    NA
# 2007-01-10     0     0     0     0

That makes things pretty easy: you can then check row-by-row (apply with MARGIN = 1) if any of the values is equal to 1:

这使得事情变得非常简单:如果任何值都等于1,那么您就可以对行逐行进行检查(应用MARGIN = 1)

apply(Lag(buysig, k=1:4) == 1, 1, any)

(and you can pass the output through as.numeric if you need to turn {TRUE,FALSE} into {1,0})

(可以将输出传递给as。如果需要将{TRUE,FALSE}转换为{1,0}的数值)

#1


3  

First, notice that Lag can take a vector of k values:

首先,注意滞后可以取一个k值向量:

head(Lag(buysig, k=1:4)
#            Lag.1 Lag.2 Lag.3 Lag.4
# 2007-01-03    NA    NA    NA    NA
# 2007-01-04    NA    NA    NA    NA
# 2007-01-05     0    NA    NA    NA
# 2007-01-08     0     0    NA    NA
# 2007-01-09     0     0     0    NA
# 2007-01-10     0     0     0     0

That makes things pretty easy: you can then check row-by-row (apply with MARGIN = 1) if any of the values is equal to 1:

这使得事情变得非常简单:如果任何值都等于1,那么您就可以对行逐行进行检查(应用MARGIN = 1)

apply(Lag(buysig, k=1:4) == 1, 1, any)

(and you can pass the output through as.numeric if you need to turn {TRUE,FALSE} into {1,0})

(可以将输出传递给as。如果需要将{TRUE,FALSE}转换为{1,0}的数值)