Search code examples
rquantmodquantitative-finance

Using ifelse to create a running tally in R


I am trying to do some quantitative modeling in R. I'm not getting an error message, but the results are not what I actually need.

I am a newbie, but here is my complete code sample.

`library(quantmod)
#Building the data frame and xts to show dividends, splits and technical indicators
getSymbols(c("AMZN"))
Playground <- data.frame(AMZN)
Playground$date <- as.Date(row.names(Playground))
Playground$wday <- as.POSIXlt(Playground$date)$wday #day of the week
Playground$yday <- as.POSIXlt(Playground$date)$mday #day of the month
Playground$mon <- as.POSIXlt(Playground$date)$mon #month of the year
Playground$RSI <- RSI(Playground$AMZN.Adjusted, n = 5, maType="EMA") #can add Moving Average Type with maType = 
Playground$MACD <- MACD(AMZN, nFast = 12, nSlow = 26, nSig = 9)
Playground$Div <- getDividends('AMZN', from = "2007-01-01", to = Sys.Date(), src = "google", auto.assign = FALSE)
Playground$Split <- getSplits('AMZN', from = "2007-01-01", to = Sys.Date(), src = "google", auto.assign = FALSE)
Playground$BuySignal <- ifelse(Playground$RSI < 30 & Playground$MACD < 0, "Buy", "Hold")

All is well up until this point when I start using some logical conditions to come up with decision points.

Playground$boughts <- ifelse(Playground$BuySignal == "Buy", lag(Playground$boughts) + 1000, lag(Playground$boughts))

It will execute but the result will be nothing but NA. I suppose this is because you are trying to add NA to a number, but I'm not 100% sure. How do you tell the computer I want you to keep a running tally of how much you have bought?

Thanks so much for the help.


Solution

  • So we want ot buy 1000 shares every time a buy signal is generated?

    Your problem stems from MACD idicator. It actually generates two columns, macd and signal. You have to decide which one you want to keep.

    Playground$MACD <- MACD(AMZN, nFast = 12, nSlow = 26, nSig = 9)$signal
    

    This should solve the problem at hand.

    Also, please check the reference for ifelse. The class of return value can be tricky at times, and so the approach suggested by Floo0 is preferable.

    Also, I'd advocate using 1 and 0 instead of buy and sell to show weather you are holding . It makes the math much easier.

    And I'd strongly suggest reading some beginner tutorial on backtesting with PerformanceAnalytics. They make the going much much easier.

    BTW, you missed this line in the code:

    Playground$boughts<- 0
    

    Hope it helps.

    EDIT: And I forgot to mention the obvious. discard the first few rows where MACD will be NA Something like:

    Playground<- Playground[-c(1:26),]