What is the logic behind this backtesting code in R

I am new to R and I have found this simple backtesting code and can you explain me what is happening here.

library(quantmod)
library(PerformanceAnalytics)

s <- get(getSymbols('SPY'))["2012::"]
s$sma20 <- SMA(Cl(s) , 20) s$position <- ifelse(Cl(s) > s$sma20 , 1 , -1) myReturn <- lag(s$position) * dailyReturn(s)
charts.PerformanceSummary(cbind(dailyReturn(s),myReturn))


I know the code uses this strategy

    Buy
close > SMA20
sell
close < SMA20


But I have doubts especially in these lines

s$position <- ifelse(Cl(s) > s$sma20 , 1 , -1)
myReturn <- lag(s$position) * dailyReturn(s) charts.PerformanceSummary(cbind(dailyReturn(s),myReturn))  s$position <- ifelse(Cl(s) > s$sma20 , 1 , -1) if close price is greater than 20 days moving average then s$postion=1 else s$postion=-1, Buy why assign 1 and -1? why calculating dailyreturns and whats is happing with myReturn,cbind()? Also can you explain this results http://i.stack.imgur.com/B1h7E.png • Beware, this code would produce wrong results for the short side as I explained it at the last paragraph in this post Oct 7 '15 at 22:42 1 Answer When position = 1, then you are long the S&P ETF. When position is -1, your portfolio consist of a short position of -1 S&P ETF. You will therefore have a vector like$Pos = (1,1,1,1,1,-1,-1,-1,-1,1,1,1,-1,-1,-1, \ldots)\$, that will give you the evolution of your portfolio.

Your returns are then the daily returns on the S&P multiplied by your position.

Cbind is the command for binding two vector together by their columns. So you take the evolution of the S&P (dailyReturns) and column-bind them with the evolution of your portfolio (myReturn), and plot them using the PerformanceAnalytics package.