joshuaulrich / TTR

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

SMA of 0 is negative #46

Closed shaojl7 closed 7 years ago

shaojl7 commented 7 years ago

Hi Joshua

Thanks for the TTR package, it is quite helpful!

However, while calculating the moving average using SMA, I noticed some unexpected behavior

rm(list = ls())
options(digits = 10)

library(TTR)
library(xts)

floating0 <- 0.0000000000000000e+00
xts_floating <- xts(c(-1.218755021e-02,-4.729404862e-03, -4.114582223e-03,
                  -3.579686583e-03, -3.114327332e-03, -8.708210015e-05,
                  rep(floating0,9),4.0245789683433897e-02), 
                order.by = Sys.Date() + c(1:16))
TTR::SMA(xts_floating,5)

I am expecting the rolling average of 0s to be 0 as well, however, it returns a negative number -2.602085214e-19 instead.

                        SMA
2017-05-25               NA
2017-05-26               NA
2017-05-27               NA
2017-05-28               NA
2017-05-29 -5.545110242e-03
2017-05-30 -3.125016620e-03
2017-05-31 -2.179135648e-03
2017-06-01 -1.356219203e-03
2017-06-02 -6.402818864e-04
2017-06-03 -1.741642003e-05
2017-06-04 -2.602085214e-19
2017-06-05 -2.602085214e-19
2017-06-06 -2.602085214e-19
2017-06-07 -2.602085214e-19
2017-06-08 -2.602085214e-19
2017-06-09  8.049157937e-03

My session info

R version 3.3.3 (2017-03-06)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_Singapore.1252  LC_CTYPE=English_Singapore.1252    LC_MONETARY=English_Singapore.1252 LC_NUMERIC=C                      
[5] LC_TIME=English_Singapore.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] xts_0.9-7  zoo_1.7-14 TTR_0.23-1

loaded via a namespace (and not attached):
[1] tools_3.3.3         Rcpp_0.12.9         grid_3.3.3          roll_1.0.6          RcppParallel_4.3.20 lattice_0.20-34    
braverock commented 7 years ago

The result you're seeing is below the machine precision, so it is numerically indistinguishable from 0. You have floating point numbers in your series, so you're doing floating point math, not integer math.

.Machine$double.eps
# [1] 2.220446e-16

see: What Every Computer Scientist Should Know About Floating Point Numbers

joshuaulrich commented 7 years ago

Also see the Kahan summation algorithm, which will be used in future versions of rolling window functions that will be in xts.