Home > Net >  Why I cannot use the natural logarithm function with the data set?
Why I cannot use the natural logarithm function with the data set?

Time:03-31

I've got a code that works with the Data Set. I found out that it doesn't want to work with the ln(x) function. The data set can be found here.

LY <- ln(Apple$Close - Apple$Open)

Warning in log(x) : NaNs produced

Could you please help me to fix this problem?

CodePudding user response:

Since stocks can go down as well as up (unfortunately), Close can be less than Open and Close - Open can be negative. It just doesn't make sense to take the natural log of a negative number; it's like dividing by zero, or more precisely like taking the square root of a negative number.

Actually, you can take the logarithm of a complex number with a negative real part:

log(as.complex(-1))
## [1] 0 3.141593i

... but "i times pi" is probably not a very useful result for further data analysis ...

(in R, log() takes the natural logarithm. While the SciViews package provides ln() as a synonym, you might as well just get used to using log() - this is a convention across most programming languages ...)

Depending on what you're trying to do, the logarithm of the close/open ratio can be a useful value (log(Close/Open)): this is negative when Close < Open, positive when Close > Open). As @jpiversen points out, this is called the logarithmic return; as @KarelZe points out, log(Close/Open) is mathematically equivalent to log(Close) - log(Open) (which might be what your professor wanted ... ???)

CodePudding user response:

Are you looking for logarithmic return? In that case the formula would be:

log(Apple$Close / Apple$Open)

Since A / B for two positive values is always positive, this will not create NaNs.

  • Related