Reputation: 9763
I'm having trouble writing a custom indicator function for use with quanstrat::add.indicator
Error:
Error in inherits(x, "xts") : object 'price' not found
My code:
library(quantstrat)
symbols<-getSymbols("USD/EUR",src="oanda")
strat<-acct<-portfolio<-"tempTest"
initEq<-1000
initDate <- '2009-12-31'
currency("USD")
exchange_rate(symbols, currency="USD")
rm.strat(strat) # remove portfolio, account, orderbook if re-run
initPortf(name=portfolio, symbols, initDate=Sys.Date())
initAcct(name=acct, portfolios=portfolio,initDate=Sys.Date(), initEq=initEq)
initOrders(portfolio=portfolio, initDate=Sys.Date())
strategy(strat, store=TRUE)
colnames(USDEUR)<-"Close"
#################################################################################################
RSI.lagged<-function(lag=1,n=2,...){
RSI <- RSI(price)
RSI <- lag(RSI, lag)
out <- RSI$rsi
colnames(out) <- "rsi"
return(out)
}
########RSI indicator
####THIS IS LAGGED TO PREVENT FOREKNOWLEDGE
add.indicator(strat, name="RSI.lagged", arguments=list(price = quote(Cl(mktdata)), n=2), label="rsiIndLagged")
test <- applyIndicators(strat, mktdata=USDEUR)
After adding the parameter price
to the RSI.lagged function eg RSI.lagged<-function(lag=1,n=2,price,...)
I get the error:
Error in `colnames<-`(`*tmp*`, value = "rsi") : attempt to set 'colnames' on an object with less than two dimensions
Upvotes: 1
Views: 1342
Reputation: 6891
You were trying to access the name of a column that does not exist. Try this instead to get your indicator to work:
RSI.lagged<-function(price, lag=1,n=2,...){
# Stick in a browser to see your problem more clearly:
# browser()
rsi <- RSI(price)
rsi <- lag(rsi, lag)
# This column name does not exist: "rsi". The name of the column gets the default "EMA"
# tail(rsi)
# EMA
# 2017-11-04 63.48806
# 2017-11-05 66.43532
# 2017-11-06 64.41188
# 2017-11-07 66.02659
# 2017-11-08 67.96394
# 2017-11-09 66.08134
colnames(rsi) <- "rsi"
return(out)
}
(Aside, also strongly suggest you do not try using Oanda data to backtest with,as the prices aren't "real"; they are a weighted average price for each day. See: Exact time stamp on quantmod currency (FX) data)
Upvotes: 3