I am trying to tell whether a specific column value is greater than .77, but this code returns 1 if the value is greater then 0. Is there any way to use a known function (not a custom one) to do a simple greater then check?
library(PerformanceAnalytics)
library(quantmod)
library(lattice)
startDate <- '2010-01-01' # start of data
endDate <- '2015-05-01' # end of data
.blotter<-new.env()
.strategy<-new.env()
Sys.setenv(TZ="EST") # set time zone
symbols<-c("GOOG")
data<-getSymbols(symbols, from=startDate, to=endDate, index.class="POSIXct",env=NULL)
library(quantstrat)
initDate <- '2009-12-31'
initEq <- 1e6
currency("USD")
stock(symbols, currency="USD", multiplier=1)
rm.strat("multiAsset.bb1") # remove portfolio, account, orderbook if re-run
initPortf(name="multiAsset.bb1", symbols, initDate=initDate)
initAcct(name="multiAsset.bb1", portfolios="multiAsset.bb1",initDate=initDate, initEq=initEq)
initOrders(portfolio="multiAsset.bb1", initDate=initDate)
strategy("bbands", store=TRUE)
#Indicators are applied before signals and rules, and the output of indicators may be used as inputs to construct signals or fire rules
#mktdata is the time series object that holds the current symbols data during evaluation (pg 55)
add.indicator("bbands", name = "BBands",arguments = list(HLC = quote(HLC(mktdata)), maType='SMA'), label='bbInd')
test <- applyIndicators("bbands", mktdata=data)
head(test, 10)
add.signal("bbands", name="sigThreshold", arguments=list(columns=c("pctB.bbInd",".77"),relationship="gt"),label="H.gt.UpperBand")
test <- applySignals("bbands", mktdata=test) #DOESNT WORK
head(test, 10)
Error:
Error in match.names(column, colnames(data)) :
argument "column" is missing, with no default
My solution was to change:
add.signal("bbands", name="sigThreshold", arguments=list(columns=c("pctB.bbInd",".77"),relationship="gt"),label="H.gt.UpperBand")
to:
add.signal("bbands", name="sigThreshold", arguments=list(threshold=.77,column="pctB.bbInd",relationship="gt"),label="H.gt.UpperBand")
Related
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
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)
I believe this is a formatting issue with my indicator. Can someone tell me what im doing wrong here?
#....omitted the portfolio initialization above
#returns change from past day, or NA if one of the values is invalid
changeDaily<-function(x,y){if(is.na(x+y)==T){return(NA)};ifelse(x-y>0,"UP","DOWN")}
#creates column called lagPredict which uses the function changeDaily
add.indicator(strat, name = "changeDaily",arguments = list(HLC = quote(mktdata),Cl(mktdata),Lag(Cl(mktdata))), label='lagPredict')
error:
Error in has.Cl(x) : object 'mktdata' not found
Traceback:
traceback()
3: has.Cl(x)
2: Cl(mktdata)
1: add.indicator(strat, name = "changeDaily", arguments = list(HLC = quote(mktdata),
Cl(mktdata), Lag(Cl(mktdata))), label = "lagPredict")
Complete code:
source("forex.functions.R")
startDate <- '2010-01-01' # start of data
endDate <- '2015-05-01' # end of data
symbols<-c("USD/EUR")
portfolio<-acct<-strat<-"simpleLookAhead"
initSetup(symbols,portfolio,acct,strat)
dump<-lapply(symbols,function(x)forex.weeklyOHLC(x))
symbols<-gsub("/","",symbols)
#############################################################
#returns change from past day, or NA if one of the values is invalid
changeDaily<-function(x,y){if(is.na(x+y)==T){return(NA)};ifelse(x-y>0,"UP","DOWN")}
#creates column called lagPredict which uses the function changeDaily to return UP or DOWN in reference to yesterdays price
add.indicator(strat, name = "changeDaily",arguments = list(HLC = quote(mktdata),Cl(mktdata),Lag(Cl(mktdata))), label='lagPredict')
forex.functions.R
library(PerformanceAnalytics)
library(quantmod)
library(lattice)
library(IKTrading)
library(quantstrat)
Sys.setenv(TZ="EST") # set time zone
if (!exists('.blotter')) .blotter <- new.env()
if (!exists('.strategy')) .strategy <- new.env()
forex.weeklyOHLC<-function(ss){
ss<-getSymbols(ss,src="oanda",from=startDate,to=endDate)
x<-get(ss)
#x<-adjustOHLC(x,symbol.name=symbol) #calls get Splits which calls getSymbols which fails bc src != oanda
x<-to.weekly(x,indexAt='lastof',drop.time=TRUE)
indexFormat(x)<-'%Y-%m-%d'
colnames(x)<-gsub("x",ss,colnames(x))
assign(ss,x)
}
initSetup<-function(symbols,portfolio, acct, strat){
initDate <- '2009-12-31'
initEq <- 1e6
currency("USD")
stock(symbols, currency="USD", multiplier=1)
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)
}
You need to quote all the objects in the arguments list in the call to add.indicator to prevent them from being evaluated. You also need to specify the correct arguments to pass to your changeDaily function. You pass HLC, but changeDaily does not have a HLC argument.
Your add.indicator call should look something like this:
add.indicator(strat, name = "changeDaily",
arguments = list(x = quote(Cl(mktdata)), y = quote(Lag(Cl(mktdata)))),
label = 'lagPredict')
What is the correct method to have signals reference other signals? Is it not intended functionality? I cant seem to find a way to do it in my code.
library(PerformanceAnalytics)
library(quantmod)
library(lattice)
startDate <- '2010-01-01' # start of data
endDate <- '2015-05-01' # end of data
.blotter<-new.env()
.strategy<-new.env()
Sys.setenv(TZ="EST") # set time zone
symbols<-c("GOOG")
data<-getSymbols(symbols, from=startDate, to=endDate, index.class="POSIXct",env=NULL)
library(quantstrat)
initDate <- '2009-12-31'
initEq <- 1e6
currency("USD")
stock(symbols, currency="USD", multiplier=1)
rm.strat("multiAsset.bb1") # remove portfolio, account, orderbook if re-run
initPortf(name="multiAsset.bb1", symbols, initDate=initDate)
initAcct(name="multiAsset.bb1", portfolios="multiAsset.bb1",initDate=initDate, initEq=initEq)
initOrders(portfolio="multiAsset.bb1", initDate=initDate)
strategy("bbands", store=TRUE)
#Indicators are applied before signals and rules, and the output of indicators may be used as inputs to construct signals or fire rules
#mktdata is the time series object that holds the current symbols data during evaluation (pg 55)
add.indicator("bbands", name = "BBands",arguments = list(HLC = quote(HLC(mktdata)), maType='SMA'), label='bbInd')
test <- applyIndicators("bbands", mktdata=data)
head(test, 10)
add.signal("bbands", name="sigThreshold", arguments=list(columns=c("pctB.bbInd",".77"),relationship="gt"),label="H.gt.UpperBand")
add.signal("bbands", name="sigThreshold", arguments=list(columns=c("H.gt.UpperBand","0"),relationship="gt"),label="true.upper.band")
test <- applySignals("bbands", mktdata=test)
head(test, 10)
Error
Error in match.names(column, colnames(data)) :
argument "column" is missing, with no default
Note that this is a generalized example. It would be trivial to make the first signal an indicator and avoid this problem in this specific case.
You've passed the wrong arguments to sigThreshold. This corrected code works as expected, with the second signal using the H.gt.UpperBand column (singular) from the first signal. The missing arguments in your code for the sigThreshold function are column (singular) and threshold.
library(quantstrat)
startDate <- '2010-01-01' # start of data
endDate <- '2015-05-01' # end of data
Sys.setenv(TZ="EST") # set time zone
symbols<-c("GOOG")
data<-getSymbols.yahoo(symbols, from=startDate, to=endDate, index.class="POSIXct",auto.assign=FALSE)
initDate <- '2009-12-31'
initEq <- 1e6
currency("USD")
stock(symbols, currency="USD", multiplier=1)
rm.strat("multiAsset.bb1") # remove portfolio, account, orderbook if re-run
initPortf(name="multiAsset.bb1", symbols, initDate=initDate)
initAcct(name="multiAsset.bb1", portfolios="multiAsset.bb1",initDate=initDate, initEq=initEq)
initOrders(portfolio="multiAsset.bb1", initDate=initDate)
strategy("bbands", store=TRUE)
#Indicators are applied before signals and rules, and the output of indicators may be used as inputs to construct signals or fire rules
#mktdata is the time series object that holds the current symbols data during evaluation (pg 55)
add.indicator("bbands"
, name = "BBands"
, arguments = list(HLC = quote(HLC(mktdata))
, maType='SMA')
, label='bbInd')
test <- applyIndicators("bbands", mktdata=data)
head(test, 10)
add.signal("bbands"
, name="sigThreshold"
, arguments=list(column="pctB.bbInd"
, threshold=.77
, relationship="gt")
, label="H.gt.UpperBand")
add.signal("bbands"
, name="sigThreshold"
, arguments=list(column="H.gt.UpperBand"
, threshold=0
, relationship="gt")
,label="true.upper.band")
test <- applySignals("bbands", mktdata=test)
head(test, 10)
Hello I am working on a pairs trading strategy. Currently I am on the process of back-testing any pair I've found under certain assumptions. For this I'm using the "quantstrat" package in R. I've found it very difficult to understand what exactly is going on within the applyStrategy function, specially after I experienced the following:
I ran a demo code for two pairs:
suppressWarnings(rm("order_book.pair1",pos=.strategy))
suppressWarnings(rm("account.pairs", "portfolio.pair1", pos=.blotter))
suppressWarnings(rm("startDate", "endDate", "startDate", "initEq", "SD", "N",
"symb1", "symb2", "portfolio1.st", "account.st",
"pairStrat", "out1"))
initDate <- '2015-04-21'
endDate <- '2016-04-21'
startDate <- '2015-04-22'
initEq <- 100000
MaxPos <- 1500 #max position in stockA;
lvls <- 3 #how many times to fade; Each order's qty will = MaxPos/lvls
symb1 <- 'SYY' #change these to try other pairs
symb2 <- 'SRE' #if you change them, make sure position limits still make sense
portfolio1.st <- 'pair1'
account.st <- 'pairs'
getSymbols(c(symb1, symb2), from=startDate, to=endDate, adjust=TRUE)
alignSymbols <- function(symbols, env=.GlobalEnv) {
# This is a simplified version of qmao::alignSymbols()
if (length(symbols) < 2)
stop("Must provide at least 2 symbols")
if (any(!is.character(symbols)))
stop("Symbols must be vector of character strings.")
ff <- get(symbols[1],env=env)
for (sym in symbols[-1]) {
tmp.sym <- get(sym,env=env)
ff <- merge(ff, tmp.sym, all=FALSE)
}
for (sym in symbols) {
assign(sym,ff[,grep(sym, colnames(ff))], env=env)
}
symbols
}
alignSymbols(c(symb1, symb2))
currency("USD")
stock(symb1, currency="USD", multiplier=1)
stock(symb2, currency="USD", multiplier=1)
initPortf(name=portfolio1.st, c(symb1,symb2))
initAcct(account.st, portfolios=portfolio1.st, initEq=initEq)
initOrders(portfolio=portfolio1.st)
The rest of the code is available here (https://r-forge.r-project.org/scm/viewvc.php/pkg/quantstrat/demo/pair_trade.R?view=markup&root=blotter)
After running the "strategy" I calculate the cumulative return and obtain a total of -0.05818081.
Now, if the next thing I do is run again the last part of the code:
out1<-applyStrategy(strategy=pairStrat, portfolios=portfolio1.st)
updatePortf(Portfolio=portfolio1.st,
Dates=paste("::", as.Date(Sys.time()), sep=''))
updateAcct(account.st, Dates=paste(startDate, endDate, sep="::"))
updateEndEq(account.st, Dates=paste(startDate, endDate, sep="::"))
getEndEq(account.st, Sys.time())
dev.new()
chart.Posn(Portfolio=portfolio1.st, Symbol=symb1)
dev.new()
chart.Posn(Portfolio=portfolio1.st, Symbol=symb2)
dev.new()
chartSeries(Cl(get(symb1))/Cl(get(symb2)), TA="addBBands(n=N,sd=SD)")
ret1 <- PortfReturns(account.st)
ret1$total <- rowSums(ret1)
Return.cumulative(ret1)
then I get -0.9044952 as the cumulative return. I know that if I want to obtain the -0.05818081 return again, then I need to restart the portfolio. However, what I am looking for is help understanding what the effects are of running
applyStrategy()
twice as explained in this comment. Help will be really appreciated!
I wrote the following codes and got an error message when apply the strategy:
Error in eval(expr, envir, enclos) : object 'Close' not found
sounds like the strategy can not find column "Close" price,
while the last line of code "head(mktdata)" clearly gives XLB.Close as column name of Close.
by the way, I intentionally left out the add.indicator() function which is not needed.
could anyone help? thanks
last line of code output has XLB.Close as column name:
head(mktdata)
XLB.Open XLB.High XLB.Low XLB.Close XLB.Volume XLB.Adjusted
2010-01-04 30.66197 31.06374 30.54327 31.06374 8287681 30.31
the strategy codes using quantstrat:
------------------------------------------------------------------------
library(quantstrat)
startDate <- '2010-01-01' # start of data
endDate <- '2013-07-31' # end of data
symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
Sys.setenv(TZ="UTC") # set time zone
getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"),
from=startDate, to=endDate, adjust=TRUE)
initDate <- '2009-12-31'
initEq <- 1e6
currency("USD")
stock(symbols, currency="USD",multiplier=1)
head(XLB)
Lowcut1<-1.001
Lowcut2<-1.002
rm.strat("multiINTRO") # remove portfolio, account, orderbook if re-run
initPortf(name="multiINTRO", symbols, initDate=initDate)
initAcct(name="multiINTRO", portfolios="multiINTRO",
initDate=initDate, initEq=initEq)
initOrders(portfolio="multiINTRO", initDate=initDate)
strategy("multiINTRO", store=TRUE)
summary(getStrategy("multiINTRO"))
add.signal("multiINTRO", name="sigFormula",
arguments=list(columns=c("Close","Low"),
formula="(Close > Lowcut1*Low) & (Close< Lowcut2*Low)",
cross=FALSE),store=TRUE,env=globalenv(),
label="longLowenter") ##Long entry
add.rule("multiINTRO", name="ruleSignal",
arguments=list(sigcol="longLowenter", sigval=TRUE, orderqty=100,
ordertype="market", orderside="long"), type="enter") ## Long enter
out<-try(applyStrategy("multiINTRO",portfolios="multiINTRO"))
head(mktdata)
head(mktdata) clearly gives "XLB.Close" as column name, and "XLB.Close" != "Close". Use quantmod's Cl and Lo column extractors on market data to get the columns you want.
Also, your formula argument is wrong because it's character string, not a formula. Your strategy runs for me if I change your add.signal call to:
add.signal("multiINTRO", name="sigFormula",
arguments=list(formula=longLowenter ~ Cl(mktdata) > Lowcut1*Lo(mktdata) & Cl(mktdata)< Lowcut2*Lo(mktdata), cross=FALSE), store=TRUE, env=globalenv(),
label="longLowenter") ##Long entry