【发布时间】:2023-03-08 20:25:01
【问题描述】:
我想使用 apply 来迭代一个矩阵,将开盘价和最高价与一个限制进行比较。
我最初使用了一个 while 循环,但它很慢,所以转而应用。
我已尝试为以下 StartRow +1。
Summary <- matrix(data=NA, nrow=1, ncol=1)
Overall <- matrix(data=NA, nrow=1, ncol=2)
Open <- matrix(data=NA, nrow=1, ncol=1)
MSingle <- function(x, StartingRow=1, Limit=0.01, StopLoss=0.01){
Open = x[1]
High = x[2]
Low = x[3]
#If the difference between High and Open exceeds Limit the function ends.
if (!is.na(High-Open[StartingRow]) > Limit){
Summary <<- 1
Open <<- Open
Row <<- cbind(Summary, Open)
Overall <<- rbind(Overall, Row)
}
#If the difference between Open and Low exceeds the Stoploss the function ends.
else if (!is.na(Open[StartingRow]-Low) > StopLoss){
Summary <<- 0
Open <<- Open
Row <<- cbind(Summary, Open)
Overall <<- rbind(Overall, Row)
}
#If neither of these are met then I want to compare the original Open price at time t...
#...with the high and low prices at time t+1, t+2, and so on, until either of the first two...
#...conditions is met.
else{
StartingRow = StartingRow + 1
}
}
apply(EUR_USD2, 1, MSingle)
更正:这最初是 lapply,但在我复制代码时这是一个错误,所描述的结果来自 apply。
矩阵 EUR_USD2 示例
Open High Low Close
[1,] 1.20037 1.20100 1.20037 1.20100
[2,] 1.20083 1.20095 1.20017 1.20030
[3,] 1.20035 1.20043 1.20035 1.20043
[4,] 1.20041 1.20050 1.20031 1.20046
[5,] 1.20049 1.20049 1.20046 1.20048`
[6,] 1.20050 1.20050 1.20048 1.20048
[7,] 1.20050 1.20069 1.20032 1.20048
[8,] 1.20048 1.20054 1.20027 1.20050
[9,] 1.20051 1.20087 1.20047 1.20087
[10,] 1.20082 1.20097 1.20076 1.20094
预期结果:
High[1] = 1.20100
Open[1] = 1.20037
Difference is 0.00063 (which is < Limit)
因此,我想保留相同的 Open[1],但移至 High[2]。
High[2] = 1.20095
Open[1] = 1.20037
差值为 0.00058(即
申请结果:
Summary Open
NA NA
Open 1 1.20037
Open 1 1.20083
Open 1 1.20035
Open 1 1.20041
Open 1 1.20049
Open 1 1.20050
Open 1 1.20050
Open 1 1.20048
Open 1 1.20051
然而,这个结果只是比较了同一时期的(高开)和限价。
我想将 High-Open(差异)与 Limit 进行比较。如果这超出了限制,则满足第一个条件。如果条件不满足,那么我想保留相同的开盘价,但将其与下一个时期的最高价进行比较,然后再次测试限价。
只有这样我才想申请比较从第 2 时段到限价的开盘价和最高价。
在满足条件之前,开盘价必须保持不变。目前应用的是比较 High(t=1)-Open(t=1) 与 Limit 但不将 Open 与任何未来期间的高值进行比较。
【问题讨论】:
-
我已经尝试过 lapply、sapply 和 apply。更正:我得到的结果是直接应用。我将更改原始代码。我也会调查
-
完成。抱歉,我已经尝试了很多变化,我不知道我是来还是去。
-
结果与上面的结果类似,1表示先达到Limit,0表示先达到Stoploss。然而,上面的结果只考虑了你所说的那个特定的行。