Home > Software engineering >  How to calculate Williams %R in RStudio?
How to calculate Williams %R in RStudio?

Time:03-22

I am trying to write a function to calculate Williams %R on data in R. Here is my code:

getSymbols('AMD', src = 'yahoo', from = '2018-01-01')

wr = function(high, low, close, n) {
  highh = runMax((high),n)
  lowl = runMin((low),n)
  -100 * ((highh - close) / (highh - lowl))
}

williampr = wr(AMD$AMD.High, AMD$AMD.Low, AMD$AMD.Close, n = 10)

After implementing a buy/sell/hold signal, it returns integer(0):

## 1 = BUY, 0 = HOLD, -1 = SELL
## implement Lag to shift the time back to the previous day
tradingSignal = Lag(
  ## if wpr is greater than 0.8, BUY
  ifelse(Lag(williampr) > 0.8 & williampr < 0.8,1,
  ## if wpr signal is less than 0.2, SELL, else, HOLD
  ifelse(Lag(williampr) > 0.2 & williampr < 0.2,-1,0)))
## make all missing values equal to 0
tradingSignal[is.na(tradingSignal)] = 0
## see how many SELL signals we have
which(tradingSignal == "-1")

What am I doing wrong?

CodePudding user response:

It would have been a good idea to identify that you were using the package quantmod in your question.

There are two things preventing this from working.

You didn't inspect what you expected! Your results in williampr are all negative. Additionally, you multiplied the values by 100, so 80% is 80, not .8. I removed -100 *.

I have done the same thing so many times.

wr = function(high, low, close, n) {
  highh = runMax((high),n)
  lowl = runMin((low),n)
  ((highh - close) / (highh - lowl))
}

That's it. It works now.

which(tradingSignal == "-1")
#  [1]   13   15   19   22   39   71   73   84   87  104  112  130  134  136  144  146  151  156  161  171  175
# [22]  179  217  230  255  268  288  305  307  316  346  358  380  386  404  449  458  463  468  488  492  494
# [43]  505  510  515  531  561  563  570  572  574  594  601  614  635  642  644  646  649  666  668  672  691
# [64]  696  698  719  729  733  739  746  784  807  819  828  856  861  872  877  896  900  922  940  954  968
# [85]  972  978  984  986 1004 1035 1048 1060 
  •  Tags:  
  • r
  • Related