1
$\begingroup$

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))

enter image description here

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

$\endgroup$
  • 2
    $\begingroup$ Beware, this code would produce wrong results for the short side as I explained it at the last paragraph in this post $\endgroup$ – Sergey Bushmanov Oct 7 '15 at 22:42
2
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.