quantmod - Using ifelse to create a running tally in R -
i trying quantitative modeling in r. i'm not getting error message, results not need.
i newbie, here complete code sample.
`library(quantmod) #building data frame , xts show dividends, splits , 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 week playground$yday <- as.posixlt(playground$date)$mday #day of month playground$mon <- as.posixlt(playground$date)$mon #month of year playground$rsi <- rsi(playground$amzn.adjusted, n = 5, matype="ema") #can add moving average type matype = playground$macd <- macd(amzn, nfast = 12, nslow = 26, nsig = 9) playground$div <- getdividends('amzn', = "2007-01-01", = sys.date(), src = "google", auto.assign = false) playground$split <- getsplits('amzn', = "2007-01-01", = sys.date(), src = "google", auto.assign = false) playground$buysignal <- ifelse(playground$rsi < 30 & playground$macd < 0, "buy", "hold")
all until point when start using logical conditions come decision points.
playground$boughts <- ifelse(playground$buysignal == "buy", lag(playground$boughts) + 1000, lag(playground$boughts))
it execute result nothing na. suppose because trying add na number, i'm not 100% sure. how tell computer want keep running tally of how have bought?
thanks help.
so want ot buy 1000 shares every time buy signal generated?
your problem stems macd idicator. generates 2 columns, macd , signal. have decide 1 want keep.
playground$macd <- macd(amzn, nfast = 12, nslow = 26, nsig = 9)$signal
this should solve problem @ hand.
also, please check reference ifelse. class of return value can tricky @ times, , approach suggested floo0 preferable.
also, i'd advocate using 1 , 0 instead of buy , sell show weather holding . makes math easier.
and i'd suggest reading beginner tutorial on backtesting performanceanalytics. make going much easier.
btw, missed line in code:
playground$boughts<- 0
hope helps.
edit: , forgot mention obvious. discard first few rows macd na like:
playground<- playground[-c(1:26),]
Comments
Post a Comment