Question

I'm stuck with the following analysis:

library(quantstrat)

stock_size = 200
tickers = c("XOM", "MCD")
init.date = as.Date("2008-01-01")

usd = "USD"
currency(usd)
for(ticker in tickers){ 
  stock(ticker, currency=usd, multiplier = 1)
}

options("getSymbols.warning4.0"=FALSE)
getSymbols(tickers,from=init.date,to.assign=TRUE)

suppressWarnings(rm(strat, port, acct, ords))

port.name <- "MyPort"
port <- initPortf(port.name,tickers,initDate=init.date)
acct.name <- "MyAcct"
acct <- initAcct(acct.name,portfolios=port.name, initDate=init.date, initEq=35000)
ords <- initOrders(portfolio=port.name,initDate=init.date)

strat.name <- "MyStrat"
strat<- strategy(strat.name)
strat<- add.indicator(strategy = strat, name = "SMA", arguments = list(x=quote(Ad(mktdata)), n=20),label= "ma20" )
strat<- add.indicator(strategy = strat, name = "SMA", arguments = list(x=quote(Ad(mktdata)), n=50),label= "ma50")

strat<- add.signal(strat, name="sigCrossover", arguments = list(columns=c("ma20","ma50"), relationship="gte"), label="ma20.gt.ma50")
strat<- add.signal(strat, name="sigCrossover", arguments = list(column=c("ma20","ma50"), relationship="lt"), label="ma20.lt.ma50")

strat<- add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="ma20.gt.ma50", sigval=TRUE, orderqty=stock_size, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)
strat<- add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="ma20.lt.ma50", sigval=TRUE, orderqty='all', 
ordertype='market', orderside='long', pricemethod='market'), type='exit', path.dep=TRUE)

out<-try(applyStrategy(strategy=strat, portfolios=port.name))
charts.PerformanceSummary()

because I got this couple of errors:

Error in `colnames<-`(`*tmp*`, value = c("XOM.Adjusted.SMA.50", "XOM.Adjusted.SMA.20.ma20.SMA.50" : 
  length of 'dimnames' [2] not equal to array extent
Error in inherits(x, "xts") : argument "R" is missing, with no default

Can anyone help me to find what's wrong?

Was it helpful?

Solution

In the current version of TTR, the names of the columns returned by the MA-indicators are prefixed by the name of the input column. Eg. SMA(MCD.Adjusted, n=20) returns a column named MCD.Adjusted.SMA.20.

Ad() will return all column names that match the string Adjusted.

By the time your second SMA-indicator gets called, Ad() will match 2 column names (the original MCD.Adjusted column plus the output column for the first indicator MCD.Adjusted.SMA.20). This results in a dimension error, because in the current implementation SMA() can only handle one input column at the time.

The solution is to pass only the first match, using quote(Ad(mktdata)[,1]) in your argument list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top