joshuaulrich / TTR

Technical analysis and other functions to construct technical trading rules with R
GNU General Public License v2.0
330 stars 103 forks source link

Bug in runCov - n gets overwritten by Fortran routine? #10

Closed ta264 closed 9 years ago

ta264 commented 9 years ago

Something strange seems to happen in runCov when the window is an integer and cumulative=TRUE. For example:

data <- 1:1000

window = as.integer(100)
cov <- runCov(data, data, window, cumulative = TRUE)

window2 = 100
cov2 <- runCov(data, data, window2, cumulative = TRUE)

print(window)
tail(cov)

print(window2)
tail(cov2)

Gives the following output:

> print(window)
[1] 1000
> tail(cov)
[1]       NA       NA       NA       NA       NA 83416.67
> print(window2)
[1] 100
> tail(cov2)
[1] 82585.00 82751.00 82917.17 83083.50 83250.00 83416.67
> 

It looks like window has been replaced by length(data). cov only has one entry at the end whereas cov2 has all but the first 99 observations, as you would expect.

I think the culprit might be this line where n is being updated by the Fortran routine. This updated value will be passed back to the R function and so the first 999 values are set to NA here.

Similar things happen in the runMedian and runMAD functions.

My guess is that the as.integer() call here is causing a copy of n to be made in the second case which is why the answer in the second case is different. I'm not sure what the best solution is... Perhaps to take an explicit copy of n in the Fortran routine rather than updating the variable that's passed in?

joshuaulrich commented 9 years ago

Thanks for the report. This was indeed a bug, and is "fixed" by the deprecation of DUP = FALSE in .Fortran calls.