[R] Producing a SMA signal when closing price is above the moving average for 3 days

Douglas Karabasz douglas at sigmamonster.com
Tue Sep 4 05:23:40 CEST 2012


I have loaded price data for GE and then calculated a 50 day simple moving
average.  Then I have a created a ifelse statement that produce a 1 when
GE's closing price is above the simple moving average and a 0 when GE
Closing price is below the 50 day simple moving average.  

However, what I really want to do is to produce a 1 for when the price is
above the simple moving average for 3 days and I want it to keep the 1 until
the price moves back below the 50 day simple moving average for 3 days then
I want to return a 0 until the Price closes above the SMA for 3 days.  

Thank you,
Douglas


library(quantmod)  

getSymbols("GE")  # Get Price Data

GEsma  <- SMA(GE$GE.Close, n=50) # Simple Moving Average of the closing
price

GEsma[is.na(GEsma)] <- 50  # Make NA's to 50 so ifelse statement works
correctly

aboveSMA  <- ifelse(GE$GE.Close > GEsma, 1, 0)  # 1 when price is above 50
day moving average
# 0 When below moving average 

chartSeries(GE)  # Shows Price chart
addSMA(n=50)  #  adds 50 day moving average to chart



More information about the R-help mailing list