1

I'm working on pairs trading data and following function should give total.profit with value "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)
}

If I run the function, I get this error message.

optimal.k(1) Error in while (r[i] > m) { : missing value where TRUE/FALSE needed

I don't get it why (r[i] > m) is NA Does anyone know why it occurs?

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • You don't appear to give `m` a value before you do the comparison –  Oct 31 '13 at 05:03
  • 1
    Actually I defined m = mean(r) above that code. And since "u" and "l" are computed by m, the first "if" statement of function would be problematic if i didn't give "m". – user2940047 Nov 01 '13 at 21:18
  • This question has been answered at this thread: http://stackoverflow.com/questions/7355187/error-in-if-while-condition-missing-value-where-true-false-needed – pengchy Jul 04 '16 at 02:27

0 Answers0