1

我正在研究配对交易数据,下面的函数应该给 total.profit 值“k”。

optimal.k = function (k) {

u = m + k * s                           
l = m - k * s                                      
profit = 0                                               
profit = 0
total.profit = 0
i = 1
p = 0.001


while ( i <= length(r) ) {
    if ( r[i] >= u ) {
        buy.unit  = 1/East$Close[i]
        sell.unit = 1/South$Close[i]
            if ( i == length(r) ) {
                buy.price    = buy.unit  * East$Close[i]
                sell.price   = sell.unit * South$Close[i]
                profit       = sell.price - buy.price
                costs        = (sell.price + buy.price) * p
                total.profit = total.profit + profit - costs
                break
            }
            while ( r[i] > m ) {  ####################################   here
                i = i + 1
            }
        buy.price    = buy.unit  * East$Close[i]
        sell.price   = sell.unit * South$Close[i]
        profit       = sell.price - buy.price
        costs        = (sell.price + buy.price) * p
        total.profit = total.profit + profit - costs
    }
    if ( r[i] <= l ) {
        buy.unit  = 1/South$Close[i]
        sell.unit = 1/East$Close[i]
            if ( i == length(r) ) {
                buy.price    = buy.unit  * South$Close[i]
                sell.price   = sell.unit * East$Close[i]
                profit       = sell.price - buy.price
                costs        = (sell.price + buy.price) * p
                total.profit = total.profit + profit - costs
                break
            }
            while ( r[i] < m ) { 
                i = i + 1
            }
        buy.price    = buy.unit  * East$Close[i]
        sell.price   = sell.unit * South$Close[i]
        profit       = sell.price - buy.price
        costs        = (sell.price + buy.price) * p
        total.profit = total.profit + profit - costs
    }
    if ( i == length(r) ) stop
i = i + 1
}
print(total.profit)
}

如果我运行该函数,我会收到此错误消息。

optimize.k(1) while (r[i] > m) { 中的错误:需要 TRUE/FALSE 的缺失值

我不明白为什么 (r[i] > m) 是 NA 有谁知道它为什么会发生?

4

0 回答 0