# We will need the quantmod package for charting and pulling # data and the TTR package to calculate indicators # You can install packages via: install.packages("packageName") # install.packages(c("quantmod","TTR")) library(quantmod) library(TTR) #get historical GSPC data from file; #must be formatted in MM/DD/YY x=read.table("C:\\nareit.txt",header=TRUE) #or wherever our data is dates = as.Date(x$Date,"%m/%d/%y") #assumes dates are in MM/DD/YY format #transform it into a time series #data file must have a Date and Close column y=xts(matrix(x$Close,dimnames=list(index(x),'Close')),dates) #csv is already in monthly format gspc=y # Calculate the SMA 10 month #gspc = to.monthly(GSPC, indexAt='endof') #gspc = Cl(GSPC) sma10 <- SMA(Cl(gspc),10) #### Create the long (up) and short (dn) signals sigup <- ifelse(Cl(gspc) > sma10, 1, 0) sigdn <- ifelse(Cl(gspc) < sma10, -1, 0) sigbh = ifelse(Cl(gspc)>0,1,0) # Lag signals to align with days in market, # not days signals were generated #sigup <- Lag(sigup,1) # Use lag() to avoid Toby's error #sigdn <- Lag(sigdn,1) # Use lag() to avoid Toby's error sigup <- lag(sigup,1) # Note k=1 implies a move *forward* sigdn <- lag(sigdn,1) # Note k=1 implies a move *forward* sigbh = lag(sigbh,1) # Replace missing signals with no position # (generally just at beginning of series) sigup[is.na(sigup)] <- 0 sigdn[is.na(sigdn)] <- 0 sigbh[is.na(sigbh)] <- 0 # Combine both signals into one vector sig <- sigup + sigdn # Calculate Close-to-Close returns ret <- ROC(Cl(gspc)) ret[1] <- 0 # Calculate equity curves eq_up <- cumprod(1+ret*sigup) eq_dn <- cumprod(1+ret*sigdn*-1) eq_all <- cumprod(1+ret*sig) eq_bh = cumprod(1+ret*sigbh) # Replicate Michael's nice chart #plot.zoo( cbind(eq_up),ylab=c("Long"), col=c("green"),main="Simple SMA 200 Strategy on GSPC: 2000-01-02 through present" ) # Wait a few seconds before making next chart... #Sys.sleep(5) # Create a chart showing the S&P500 chartSeries(gspc, type="line") #add 10 wk SMA addTA(sma10,on=1,col=c("red")) # Add the total equity line addTA(eq_up, col=c("cyan")) addTA(eq_bh,on=2)# We will need the quantmod package for charting and pulling