如何向量化:根据二进制向量为1的上一次设置值

时间:2011-03-19 11:52:01

标签: r finance trading xts

我有另一个R初学者问题......

如何在代码之后进行矢量化(避免循环):

# algorithm for getting entry prices (when signal > 0): look back from current
# position until you find first signal > 0,
# `mktdataclose` at that time is entry price
# `entryPrices` is an xts object representing entry prices
# if entryPrices are not available (is.null == TRUE) then wee need to reconstruct
# them from signal (xts object with 1 when entry signal triggered and 0 
# otherwise) and close prices available in mktdataclose (an xts object with the
# same length as signal and same dates just that it represents closing prices)

EntryPrices <- entryPrices
if (is.null(EntryPrices)) {
    # get entryprices as close prices on buy signal
    EntryPrices <- ifelse(signal > 0, mktdataclose, 0)
    entryPrice <- 0
    for (i in 1:NROW(signal)) {
        if (signal[i] > 0) entryPrice <- mktdataclose[i]
        EntryPrices[i] <- entryPrice
    }
}

我坚持认为SAS数据步骤和desperatley寻找保留等。我在哪里可以找到一些简单的exaples以了解sapply等(r帮助通过?sapply遗憾的是让我复杂...... :()

感谢您的帮助。

最佳, 萨莫。

3 个答案:

答案 0 :(得分:3)

如果我理解正确,您的问题是:您有两个长度为signal的{​​{1}}和mktdataclose向量,并且您想创建一个长度为n的新向量EntryPrices n mktdataclose[i]的值mktdataclose 上次时间signal在时间i或之前是1。你可以在没有for循环的情况下使用cummax执行此操作,cumsum这是一个经常出乎意料的有用函数(请注意,这个问题与之前的一些问题类似,使用此函数和set.seed(123) signal <- sample(0:1, 10, replace = TRUE) mktdataclose <- runif(10, 1, 10) 类似地解决了这些问题。 )。在这里,我们使用Gavin的数据:

signal

我们的问题是将indices <- cummax( seq_along(signal) * signal) 向量转换为适当索引的向量:

indices

这正是我们想要的EntryPrices,除了0.现在我们通过从indices提取非零mktdataclose的值来设置EntryPrices <- c( rep(0, sum(indices==0)), mktdataclose[ indices ]) > cbind(signal, indices, mktdataclose, EntryPrices) signal indices mktdataclose EntryPrices [1,] 0 0 9.611500 0.000000 [2,] 1 2 5.080007 5.080007 [3,] 0 2 7.098136 5.080007 [4,] 1 4 6.153701 6.153701 [5,] 1 5 1.926322 1.926322 [6,] 0 5 9.098425 1.926322 [7,] 1 7 3.214790 3.214790 [8,] 1 8 1.378536 1.378536 [9,] 1 9 3.951286 3.951286 [10,] 0 9 9.590533 3.951286 :< / p>

{{1}}

答案 1 :(得分:0)

因为信号是0和1我认为你可以用:

进行矢量化
EntryPrices * signal

答案 2 :(得分:0)

这是您可能会发现更直接的另一种解决方案。我正在使用Prasad的psudo数据。

> EntryPrices <- ifelse(signal > 0, mktdataclose, NA)
> EntryPrices <- na.locf(EntryPrices, na.rm=FALSE)
> cbind(signal,mktdataclose,EntryPrices)
      signal mktdataclose EntryPrices
 [1,]      0     9.611500          NA
 [2,]      1     5.080007    5.080007
 [3,]      0     7.098136    5.080007
 [4,]      1     6.153701    6.153701
 [5,]      1     1.926322    1.926322
 [6,]      0     9.098425    1.926322
 [7,]      1     3.214790    3.214790
 [8,]      1     1.378536    1.378536
 [9,]      1     3.951286    3.951286
[10,]      0     9.590533    3.951286