Skip to content

inbuilt crossover function for backtesting

6 messages · Joshua Ulrich, boredstoog

#
I am trying to built a simple moving average cross over strategy for
backtesting. I have installed TTR and quantmod, quantstrat for that purpose.
indicators. I want to know whether any inbuilt crossover function (not
greater '>' or lesser '<') is available for R.

Example

sma10<-SMA(close,10)
sma30<-SMA(close,30)

buy<-Crossover(sma10,sma30)
sell<-Crossover(sma30,sma10)






--
View this message in context: http://r.789695.n4.nabble.com/inbuilt-crossover-function-for-backtesting-tp4710918.html
Sent from the R help mailing list archive at Nabble.com.
#
On Sun, Aug 9, 2015 at 3:46 AM, boredstoog via R-help
<r-help at r-project.org> wrote:
help.search("crossover") would have lead you to quantstrat::sigCrossover.

require(quantstrat)
getSymbols("SPY")
SPY$sma10 <- SMA(Cl(SPY),10)
SPY$sma30 <- SMA(Cl(SPY),30)
buy <- sigCrossover("buy", SPY, c("sma10","sma30"), "gt")
sell <- sigCrossover("sell", SPY, c("sma30","sma10"), "lt")

  
    
#
Thanks Joshua for the quick reply to the mail and once more sorry for
bothering with another doubt. So i have modified your code :) for
backtesting and this is the code

*
library(quantmod)
library(tseries)
require(quantstrat)
library(PerformanceAnalytics)
sym <- get(getSymbols('SPY'))["2013::"]
sym$sma10 <- SMA(Cl(sym),10) 
sym$sma30 <- SMA(Cl(sym),30)
buy <- sigCrossover("buy", SPY, c("sma10","sma30"), "gt") 
sell <- sigCrossover("sell", SPY, c("sma30","sma10"), "lt") 
if (buy==TRUE){
    sym$pos<-1
} else if (sell==TRUE){
   sym$pos<--1
} 
myReturn <- lag(sym$pos) * dailyReturn(sym)
charts.PerformanceSummary(cbind(dailyReturn(sym),myReturn))*


But the above code is returing this error

*Error in if (buy == TRUE) { : missing value where TRUE/FALSE needed
In addition: Warning message:
In if (buy == TRUE) { :
  the condition has length > 1 and only the first element will be used
Error in hasTsp(x) : attempt to set an attribute on NULL
Warning message:
In to_period(xx, period = on.opts[[period]], ...) :
  missing values removed from data*

Any idea what is hapennning



--
View this message in context: http://r.789695.n4.nabble.com/inbuilt-crossover-function-for-backtesting-tp4710918p4710949.html
Sent from the R help mailing list archive at Nabble.com.
#
On Mon, Aug 10, 2015 at 11:02 AM, boredstoog via R-help
<r-help at r-project.org> wrote:
There are several errors in your code.  Rather than enumerate them and
show you how to fix each one; I suggest you simply use quantstrat as
it was intended, rather than attempt to circumvent/re-invent it.

See demo('macd') and modify the demo source code to suit your purposes.