No Strategies Work In R: Demos Included... - Matlab, R project and Python | futures io social day trading
futures io futures trading


No Strategies Work In R: Demos Included...
Updated: Views / Replies:1,811 / 9
Created: by CaptainNegatory Attachments:0

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

Reply
 
Thread Tools Search this Thread
 

No Strategies Work In R: Demos Included...

  #1 (permalink)
Trading Apprentice
New York City, New York
 
Futures Experience: Advanced
Platform: NinjaTrader, TOS
Favorite Futures: Options, Equities, Futures
 
Posts: 18 since Sep 2014
Thanks: 2 given, 5 received

No Strategies Work In R: Demos Included...

Hello Everyone,
After going through hell and back I have finally gotten R to install with Quantstrat and all the neccesities. However, when I try to run ANY strategy, they all fail in some way or another, but the errors that are thrown back to me are 95% code related. Can someone fix the below code or send me a strategy I can test that they know is working? My specs are below. Also, I have tried setting my working directory to "demo" and "DSTrading" but neither works. Thanks in advance.
  1. MAC OSX 10.9.4 Mavericks
  2. R Studio
  3. R 3.1.1
  4. Gfortran 4.8

Code:
 
Code
setwd("demo")
require(DSTrading)
require(IKTrading)
require(quantstrat)
require(PerformanceAnalytics)

initDate="1990-01-01"
from="2003-01-01"
to="2010-12-31"
options(width=70)
verbose=TRUE

source("demoData.R")

#trade sizing and initial equity settings
tradeSize <- 100000
initEq <- tradeSize*length(symbols)

strategy.st <- portfolio.st <- account.st <- "Cycle_RSI_I"
rm.strat(portfolio.st)
rm.strat(strategy.st)
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='USD',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)

#parameters
nRSI=2
RSIentry=10
RSIexit=70

nSMA=200

period=10
pctATR=.04

#indicators
add.indicator(strategy.st, name="lagATR", 
              arguments=list(HLC=quote(HLC(mktdata)), n=period), 
              label="atrX")
add.indicator(strategy.st, name="SMA",
              arguments=list(x=quote(Cl(mktdata)), n=nSMA),
              label="SMA")
add.indicator(strategy.st, name="CycleRSI",
              arguments=list(x=quote(Cl(mktdata)), n=nRSI),
              label="RSI")

#signals
add.signal(strategy.st, name="sigComparison",
           arguments=list(columns=c("Close", "SMA"), relationship="gt"),
           label="ClGtSMA")

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="CycleRSI.RSI", threshold=RSIentry, 
                          relationship="lt", cross=FALSE),
           label="RSIltEntryThresh")

add.signal(strategy.st, name="sigAND",
           arguments=list(columns=c("ClGtSMA", "RSIltEntryThresh"), 
                          cross=TRUE),
           label="longEntry")

add.signal(strategy.st, name="sigCrossover",
           arguments=list(columns=c("Close", "SMA"), relationship="lt"),
           label="exitSMA")

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="CycleRSI.RSI", threshold=RSIexit,
                          relationship="gt", cross=TRUE),
           label="longExit")

#rules
#rules
add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="longEntry", sigval=TRUE, 
                        ordertype="market", 
                        orderside="long", replace=FALSE, 
                        prefer="Open", osFUN=osDollarATR,
                        tradeSize=tradeSize, pctATR=pctATR, 
                        atrMod="X"), 
         type="enter", path.dep=TRUE)

add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="longExit", sigval=TRUE, 
                        orderqty="all", ordertype="market", 
                        orderside="long", replace=FALSE, 
                        prefer="Open"), 
         type="exit", path.dep=TRUE)

add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="exitSMA", sigval=TRUE, 
                        orderqty="all", ordertype="market", 
                        orderside="long", replace=FALSE, 
                        prefer="Open"), 
         type="exit", path.dep=TRUE)

#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
t2 <- Sys.time()
print(t2-t1)

#set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)


#trade statistics
tStats <- tradeStats(Portfolios = portfolio.st, use="trades", inclZeroDays=FALSE)
tStats[,4:ncol(tStats)] <- round(tStats[,4:ncol(tStats)], 2)
print(data.frame(t(tStats[,-c(1,2)])))
(aggPF <- sum(tStats$Gross.Profits)/-sum(tStats$Gross.Losses))
(aggCorrect <- mean(tStats$Percent.Positive))
(numTrades <- sum(tStats$Num.Trades))
(meanAvgWLR <- mean(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio < Inf], na.rm=TRUE))

#daily and duration statistics
dStats <- dailyStats(Portfolios = portfolio.st, use="Equity")
rownames(dStats) <- gsub(".DailyEndEq","", rownames(dStats))
print(data.frame(t(dStats)))
durStats <- durationStatistics(Portfolio=portfolio.st, Symbols=sort(symbols))
indivDurStats <- durationStatistics(Portfolio=portfolio.st, Symbols=sort(symbols), aggregate=FALSE)
print(t(durStats))
print(t(indivDurStats))

#market exposure
tmp <- list()
length(tmp) <- length(symbols)
for(i in 1:nrow(dStats)) {
  totalDays <- nrow(get(rownames(dStats)[i]))
  mktExposure <- dStats$Total.Days[i]/totalDays
  tmp[[i]] <- c(rownames(dStats)[i], round(mktExposure, 3))
}
mktExposure <- data.frame(do.call(rbind, tmp))
colnames(mktExposure) <- c("Symbol","MktExposure")
print(mktExposure)
print(mean(as.numeric(as.character(mktExposure$MktExposure))))

#portfolio cash PL
portString <- paste0("portfolio.", portfolio.st)
portPL <- .blotter[[portString]]$summary$Net.Trading.PL

#Cash Sharpe
(SharpeRatio.annualized(portPL, geometric=FALSE))

#Portfolio comparisons to SPY
instRets <- PortfReturns(account.st)

#Correlations
instCors <- cor(instRets)
diag(instRets) <- NA
corMeans <- rowMeans(instCors, na.rm=TRUE)
names(corMeans) <- gsub(".DailyEndEq", "", names(corMeans))
print(round(corMeans,3))
mean(corMeans)

portfRets <- xts(rowMeans(instRets)*ncol(instRets), order.by=index(instRets))
portfRets <- portfRets[!is.na(portfRets)]
cumPortfRets <- cumprod(1+portfRets)
firstNonZeroDay <- as.character(index(portfRets)[min(which(portfRets!=0))])
getSymbols("SPY", from=firstNonZeroDay, to=to)
SPYrets <- diff(log(Cl(SPY)))[-1]
cumSPYrets <- cumprod(1+SPYrets)
comparison <- cbind(cumPortfRets, cumSPYrets)
colnames(comparison)  <- c("strategy", "SPY")
chart.TimeSeries(comparison, legend.loc = "topleft",
                 colors=c("green","red"))
chart.RelativePerformance(portfRets,SPYrets)

SharpeRatio.annualized(portfRets)
Return.annualized(portfRets)
maxDrawdown(portfRets)

chart.Posn(portfolio.st, "XLB")
sma <- SMA(Cl(XLB), n=nSMA)
add_TA(sma, on=1, lwd=2, col="blue")
rsi <- CycleRSI(Cl(XLB), n=nRSI)
add_TA(rsi, col="blue")
atr <- lagATR(HLC=HLC(XLB), n=period)
add_TA(atr, col="purple")

agg.chart.ME(portfolio.st, symbols, type="MAE", scale="cash")

agg.chart.ME(portfolio.st, symbols, type="MFE", scale="cash")
Errors:
 
Code
> setwd("demo")
> require(DSTrading)
> require(IKTrading)
> require(quantstrat)
> require(PerformanceAnalytics)
> 
> initDate="1990-01-01"
> from="2003-01-01"
> to="2010-12-31"
> options(width=70)
> verbose=TRUE
> source("demoData.R")
Error in as.environment(pos) : 
  no item called ".blotter" on the search list
In addition: Warning message:
In ls(.blotter) : ‘.blotter’ converted to character string
> #trade sizing and initial equity settings
> tradeSize <- 100000
> initEq <- tradeSize*length(symbols)
> 
> strategy.st <- portfolio.st <- account.st <- "Cycle_RSI_I"
> rm.strat(portfolio.st)
Error in rm(list = paste("order_book", name, sep = "."), pos = .strategy) : 
  object '.strategy' not found
Error in rm(list = paste(c("account", "portfolio"), name, sep = "."),  : 
  object '.blotter' not found
Error in rm(list = name, pos = .strategy) : object '.strategy' not found
> rm.strat(strategy.st)
Error in rm(list = paste("order_book", name, sep = "."), pos = .strategy) : 
  object '.strategy' not found
Error in rm(list = paste(c("account", "portfolio"), name, sep = "."),  : 
  object '.blotter' not found
Error in rm(list = name, pos = .strategy) : object '.strategy' not found
> initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
Error in exists(paste("portfolio", name, sep = "."), envir = .blotter,  : 
  object '.blotter' not found
> initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='USD',initEq=initEq)
Error in exists(paste("account", name, sep = "."), envir = .blotter, inherits = TRUE) : 
  object '.blotter' not found
> initOrders(portfolio.st, initDate=initDate)
Error in .getPortfolio(portfolio) : 
  Portfolio Cycle_RSI_I  not found, use initPortf() to create a new portfolio
> strategy(strategy.st, store=TRUE)
Error in assign(strat$name, strat, envir = as.environment(.strategy)) : 
  object '.strategy' not found
> 
> #parameters
> nRSI=2
> RSIentry=10
> RSIexit=70
> 
> nSMA=200
> 
> period=10
> pctATR=.04
> 
> #indicators
> add.indicator(strategy.st, name="lagATR", 
+               arguments=list(HLC=quote(HLC(mktdata)), n=period), 
+               label="atrX")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.indicator(strategy.st, name = "lagATR", arguments = list(HLC = quote(HLC(mktdata)),  : 
  You must supply an object or the name of an object of type 'strategy'.
> add.indicator(strategy.st, name="SMA",
+               arguments=list(x=quote(Cl(mktdata)), n=nSMA),
+               label="SMA")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.indicator(strategy.st, name = "SMA", arguments = list(x = quote(Cl(mktdata)),  : 
  You must supply an object or the name of an object of type 'strategy'.
> add.indicator(strategy.st, name="CycleRSI",
+               arguments=list(x=quote(Cl(mktdata)), n=nRSI),
+               label="RSI")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.indicator(strategy.st, name = "CycleRSI", arguments = list(x = quote(Cl(mktdata)),  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> #signals
> add.signal(strategy.st, name="sigComparison",
+            arguments=list(columns=c("Close", "SMA"), relationship="gt"),
+            label="ClGtSMA")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.signal(strategy.st, name = "sigComparison", arguments = list(columns = c("Close",  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> add.signal(strategy.st, name="sigThreshold",
+            arguments=list(column="CycleRSI.RSI", threshold=RSIentry, 
+                           relationship="lt", cross=FALSE),
+            label="RSIltEntryThresh")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.signal(strategy.st, name = "sigThreshold", arguments = list(column = "CycleRSI.RSI",  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> add.signal(strategy.st, name="sigAND",
+            arguments=list(columns=c("ClGtSMA", "RSIltEntryThresh"), 
+                           cross=TRUE),
+            label="longEntry")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.signal(strategy.st, name = "sigAND", arguments = list(columns = c("ClGtSMA",  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> add.signal(strategy.st, name="sigCrossover",
+            arguments=list(columns=c("Close", "SMA"), relationship="lt"),
+            label="exitSMA")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.signal(strategy.st, name = "sigCrossover", arguments = list(columns = c("Close",  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> add.signal(strategy.st, name="sigThreshold",
+            arguments=list(column="CycleRSI.RSI", threshold=RSIexit,
+                           relationship="gt", cross=TRUE),
+            label="longExit")
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.signal(strategy.st, name = "sigThreshold", arguments = list(column = "CycleRSI.RSI",  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> #rules
> #rules
> add.rule(strategy.st, name="ruleSignal", 
+          arguments=list(sigcol="longEntry", sigval=TRUE, 
+                         ordertype="market", 
+                         orderside="long", replace=FALSE, 
+                         prefer="Open", osFUN=osDollarATR,
+                         tradeSize=tradeSize, pctATR=pctATR, 
+                         atrMod="X"), 
+          type="enter", path.dep=TRUE)
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.rule(strategy.st, name = "ruleSignal", arguments = list(sigcol = "longEntry",  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> add.rule(strategy.st, name="ruleSignal", 
+          arguments=list(sigcol="longExit", sigval=TRUE, 
+                         orderqty="all", ordertype="market", 
+                         orderside="long", replace=FALSE, 
+                         prefer="Open"), 
+          type="exit", path.dep=TRUE)
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.rule(strategy.st, name = "ruleSignal", arguments = list(sigcol = "longExit",  : 
  You must supply an object or the name of an object of type 'strategy'.
> 
> add.rule(strategy.st, name="ruleSignal", 
+          arguments=list(sigcol="exitSMA", sigval=TRUE, 
+                         orderqty="all", ordertype="market", 
+                         orderside="long", replace=FALSE, 
+                         prefer="Open"), 
+          type="exit", path.dep=TRUE)
Error in get(as.character(x), pos = envir, inherits = TRUE) : 
  object '.strategy' not found
Error in add.rule(strategy.st, name = "ruleSignal", arguments = list(sigcol = "exitSMA",  : 
  You must supply an object or the name of an object of type 'strategy'.
>

Reply With Quote
 
  #2 (permalink)
Quick Summary
Quick Summary Post

Quick Summary is created and edited by users like you... Add FAQ's, Links and other Relevant Information by clicking the edit button in the lower right hand corner of this message.

 
  #3 (permalink)
Site Administrator
Manta, Ecuador
 
Futures Experience: Advanced
Platform: My own custom solution
Favorite Futures: E-mini ES S&P 500
 
Big Mike's Avatar
 
Posts: 46,240 since Jun 2009
Thanks: 29,353 given, 83,234 received


You can confirm your Mac is the problem by installing Windows or Debian in a VM, then reinstalling R. If it works, like I assume it will, then you'll have to look at your Mac installation. One possibility is the compiler, since it isn't gcc++

Mike

Due to time constraints, please do not PM me if your question can be resolved or answered on the forum.

Need help?
1) Stop changing things. No new indicators, charts, or methods. Be consistent with what is in front of you first.
2) Start a journal and post to it daily with the trades you made to show your strengths and weaknesses.
3) Set goals for yourself to reach daily. Make them about how you trade, not how much money you make.
4) Accept responsibility for your actions. Stop looking elsewhere to explain away poor performance.
5) Where to start as a trader? Watch this webinar and read this thread for hundreds of questions and answers.
6)
Help using the forum? Watch this video to learn general tips on using the site.

If you want
to support our community, become an Elite Member.

Reply With Quote
 
  #4 (permalink)
Trading Apprentice
New York City, New York
 
Futures Experience: Advanced
Platform: NinjaTrader, TOS
Favorite Futures: Options, Equities, Futures
 
Posts: 18 since Sep 2014
Thanks: 2 given, 5 received


Big Mike View Post
You can confirm your Mac is the problem by installing Windows or Debian in a VM, then reinstalling R. If it works, like I assume it will, then you'll have to look at your Mac installation. One possibility is the compiler, since it isn't gcc++

Mike

Fortunately and unfortunately, I get the same or very similar errors in the Windows side. Code and errors below:

Code:
 
Code
require(DSTrading)
require(IKTrading)
require(quantstrat)
require(PerformanceAnalytics)

initDate="1990-01-01"
from="2003-01-01"
to="2010-12-31"
options(width=70)
verbose=TRUE

source("demoData.R")

#trade sizing and initial equity settings
tradeSize <- 100000
initEq <- tradeSize*length(symbols)

strategy.st <- portfolio.st <- account.st <- "Cycle_RSI_I"
rm.strat(portfolio.st)
rm.strat(strategy.st)
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='USD',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)

#parameters
nRSI=2
RSIentry=10
RSIexit=70

nSMA=200

period=10
pctATR=.04

#indicators
add.indicator(strategy.st, name="lagATR", 
              arguments=list(HLC=quote(HLC(mktdata)), n=period), 
              label="atrX")
add.indicator(strategy.st, name="SMA",
              arguments=list(x=quote(Cl(mktdata)), n=nSMA),
              label="SMA")
add.indicator(strategy.st, name="CycleRSI",
              arguments=list(x=quote(Cl(mktdata)), n=nRSI),
              label="RSI")

#signals
add.signal(strategy.st, name="sigComparison",
           arguments=list(columns=c("Close", "SMA"), relationship="gt"),
           label="ClGtSMA")

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="CycleRSI.RSI", threshold=RSIentry, 
                          relationship="lt", cross=FALSE),
           label="RSIltEntryThresh")

add.signal(strategy.st, name="sigAND",
           arguments=list(columns=c("ClGtSMA", "RSIltEntryThresh"), 
                          cross=TRUE),
           label="longEntry")

add.signal(strategy.st, name="sigCrossover",
           arguments=list(columns=c("Close", "SMA"), relationship="lt"),
           label="exitSMA")

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="CycleRSI.RSI", threshold=RSIexit,
                          relationship="gt", cross=TRUE),
           label="longExit")

#rules
#rules
add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="longEntry", sigval=TRUE, 
                        ordertype="market", 
                        orderside="long", replace=FALSE, 
                        prefer="Open", osFUN=osDollarATR,
                        tradeSize=tradeSize, pctATR=pctATR, 
                        atrMod="X"), 
         type="enter", path.dep=TRUE)

add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="longExit", sigval=TRUE, 
                        orderqty="all", ordertype="market", 
                        orderside="long", replace=FALSE, 
                        prefer="Open"), 
         type="exit", path.dep=TRUE)

add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="exitSMA", sigval=TRUE, 
                        orderqty="all", ordertype="market", 
                        orderside="long", replace=FALSE, 
                        prefer="Open"), 
         type="exit", path.dep=TRUE)

#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
t2 <- Sys.time()
print(t2-t1)

#set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)


#trade statistics
tStats <- tradeStats(Portfolios = portfolio.st, use="trades", inclZeroDays=FALSE)
tStats[,4:ncol(tStats)] <- round(tStats[,4:ncol(tStats)], 2)
print(data.frame(t(tStats[,-c(1,2)])))
(aggPF <- sum(tStats$Gross.Profits)/-sum(tStats$Gross.Losses))
(aggCorrect <- mean(tStats$Percent.Positive))
(numTrades <- sum(tStats$Num.Trades))
(meanAvgWLR <- mean(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio < Inf], na.rm=TRUE))

#daily and duration statistics
dStats <- dailyStats(Portfolios = portfolio.st, use="Equity")
rownames(dStats) <- gsub(".DailyEndEq","", rownames(dStats))
print(data.frame(t(dStats)))
durStats <- durationStatistics(Portfolio=portfolio.st, Symbols=sort(symbols))
indivDurStats <- durationStatistics(Portfolio=portfolio.st, Symbols=sort(symbols), aggregate=FALSE)
print(t(durStats))
print(t(indivDurStats))

#market exposure
tmp <- list()
length(tmp) <- length(symbols)
for(i in 1:nrow(dStats)) {
  totalDays <- nrow(get(rownames(dStats)[i]))
  mktExposure <- dStats$Total.Days[i]/totalDays
  tmp[[i]] <- c(rownames(dStats)[i], round(mktExposure, 3))
}
mktExposure <- data.frame(do.call(rbind, tmp))
colnames(mktExposure) <- c("Symbol","MktExposure")
print(mktExposure)
print(mean(as.numeric(as.character(mktExposure$MktExposure))))

#portfolio cash PL
portString <- paste0("portfolio.", portfolio.st)
portPL <- .blotter[[portString]]$summary$Net.Trading.PL

#Cash Sharpe
(SharpeRatio.annualized(portPL, geometric=FALSE))

#Portfolio comparisons to SPY
instRets <- PortfReturns(account.st)

#Correlations
instCors <- cor(instRets)
diag(instRets) <- NA
corMeans <- rowMeans(instCors, na.rm=TRUE)
names(corMeans) <- gsub(".DailyEndEq", "", names(corMeans))
print(round(corMeans,3))
mean(corMeans)

portfRets <- xts(rowMeans(instRets)*ncol(instRets), order.by=index(instRets))
portfRets <- portfRets[!is.na(portfRets)]
cumPortfRets <- cumprod(1+portfRets)
firstNonZeroDay <- as.character(index(portfRets)[min(which(portfRets!=0))])
getSymbols("SPY", from=firstNonZeroDay, to=to)
SPYrets <- diff(log(Cl(SPY)))[-1]
cumSPYrets <- cumprod(1+SPYrets)
comparison <- cbind(cumPortfRets, cumSPYrets)
colnames(comparison)  <- c("strategy", "SPY")
chart.TimeSeries(comparison, legend.loc = "topleft",
                 colors=c("green","red"))
chart.RelativePerformance(portfRets,SPYrets)

SharpeRatio.annualized(portfRets)
Return.annualized(portfRets)
maxDrawdown(portfRets)

chart.Posn(portfolio.st, "XLB")
sma <- SMA(Cl(XLB), n=nSMA)
add_TA(sma, on=1, lwd=2, col="blue")
rsi <- CycleRSI(Cl(XLB), n=nRSI)
add_TA(rsi, col="blue")
atr <- lagATR(HLC=HLC(XLB), n=period)
add_TA(atr, col="purple")

agg.chart.ME(portfolio.st, symbols, type="MAE", scale="cash")

agg.chart.ME(portfolio.st, symbols, type="MFE", scale="cash")
Errors:
 
Code
> setwd("~/R/win-library/3.1/DSTrading/demo")
> #apply strategy
> t1 <- Sys.time()
> out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
Error in is.strategy(strategy) : object 'strategy.st' not found
> t2 <- Sys.time()
> print(t2-t1)
Time difference of 0.0009999275 secs
> 
> #set up analytics
> updatePortf(portfolio.st)
Error in updatePortf(portfolio.st) : object 'portfolio.st' not found
> dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
Error in getPortfolio(portfolio.st) : object 'portfolio.st' not found
> updateAcct(portfolio.st,dateRange)
Error in getAccount(name) : object 'portfolio.st' not found
> updateEndEq(account.st)
Error in updateEndEq(account.st) : object 'account.st' not found
> 
> 
> #trade statistics
> tStats <- tradeStats(Portfolios = portfolio.st, use="trades", inclZeroDays=FALSE)
Error in tradeStats(Portfolios = portfolio.st, use = "trades", inclZeroDays = FALSE) : 
  object 'portfolio.st' not found
> tStats[,4:ncol(tStats)] <- round(tStats[,4:ncol(tStats)], 2)
Error: object 'tStats' not found
> print(data.frame(t(tStats[,-c(1,2)])))
Error in t(tStats[, -c(1, 2)]) : object 'tStats' not found
> (aggPF <- sum(tStats$Gross.Profits)/-sum(tStats$Gross.Losses))
Error: object 'tStats' not found
> (aggCorrect <- mean(tStats$Percent.Positive))
Error in mean(tStats$Percent.Positive) : object 'tStats' not found
> (numTrades <- sum(tStats$Num.Trades))
Error: object 'tStats' not found
> (meanAvgWLR <- mean(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio < Inf], na.rm=TRUE))
Error in mean(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio < Inf],  : 
  object 'tStats' not found
> 
> #daily and duration statistics
> dStats <- dailyStats(Portfolios = portfolio.st, use="Equity")
Error in dailyEqPL(Portfolios) : object 'portfolio.st' not found
> rownames(dStats) <- gsub(".DailyEndEq","", rownames(dStats))
Error in rownames(dStats) : object 'dStats' not found
> print(data.frame(t(dStats)))
Error in t(dStats) : object 'dStats' not found
> durStats <- durationStatistics(Portfolio=portfolio.st, Symbols=sort(symbols))
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
  'x' must be atomic
> indivDurStats <- durationStatistics(Portfolio=portfolio.st, Symbols=sort(symbols), aggregate=FALSE)
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
  'x' must be atomic
> print(t(durStats))
Error in t(durStats) : object 'durStats' not found
> print(t(indivDurStats))
Error in t(indivDurStats) : object 'indivDurStats' not found
> 
> #market exposure
> tmp <- list()
> length(tmp) <- length(symbols)
> for(i in 1:nrow(dStats)) {
+   totalDays <- nrow(get(rownames(dStats)[i]))
+   mktExposure <- dStats$Total.Days[i]/totalDays
+   tmp[[i]] <- c(rownames(dStats)[i], round(mktExposure, 3))
+ }
Error in nrow(dStats) : object 'dStats' not found
> mktExposure <- data.frame(do.call(rbind, tmp))
> colnames(mktExposure) <- c("Symbol","MktExposure")
Error in `colnames<-`(`*tmp*`, value = c("Symbol", "MktExposure")) : 
  'names' attribute [2] must be the same length as the vector [0]
> print(mktExposure)
data frame with 0 columns and 0 rows
> print(mean(as.numeric(as.character(mktExposure$MktExposure))))
[1] NaN
> 
> #portfolio cash PL
> portString <- paste0("portfolio.", portfolio.st)
Error in paste0("portfolio.", portfolio.st) : 
  object 'portfolio.st' not found
> portPL <- .blotter[[portString]]$summary$Net.Trading.PL
Error: object 'portString' not found
> 
> #Cash Sharpe
> (SharpeRatio.annualized(portPL, geometric=FALSE))
Error in inherits(x, "xts") : object 'portPL' not found
> 
> #Portfolio comparisons to SPY
> instRets <- PortfReturns(account.st)
Error in PortfReturns(account.st) : object 'account.st' not found
> 
> #Correlations
> instCors <- cor(instRets)
Error in is.data.frame(x) : object 'instRets' not found
> diag(instRets) <- NA
Error in diag(instRets) <- NA : object 'instRets' not found
> corMeans <- rowMeans(instCors, na.rm=TRUE)
Error in is.data.frame(x) : object 'instCors' not found
> names(corMeans) <- gsub(".DailyEndEq", "", names(corMeans))
Error in gsub(".DailyEndEq", "", names(corMeans)) : 
  object 'corMeans' not found
> print(round(corMeans,3))
Error in print(round(corMeans, 3)) : object 'corMeans' not found
> mean(corMeans)
Error in mean(corMeans) : object 'corMeans' not found
> 
> portfRets <- xts(rowMeans(instRets)*ncol(instRets), order.by=index(instRets))
Error in is.data.frame(x) : object 'instRets' not found
> portfRets <- portfRets[!is.na(portfRets)]
Error: object 'portfRets' not found
> cumPortfRets <- cumprod(1+portfRets)
Error: object 'portfRets' not found
> firstNonZeroDay <- as.character(index(portfRets)[min(which(portfRets!=0))])
Error in index(portfRets) : object 'portfRets' not found
> getSymbols("SPY", from=firstNonZeroDay, to=to)
Error in do.call(paste("getSymbols.", symbol.source, sep = ""), list(Symbols = current.symbols,  : 
  object 'firstNonZeroDay' not found
> SPYrets <- diff(log(Cl(SPY)))[-1]
Error in has.Cl(x) : object 'SPY' not found
> cumSPYrets <- cumprod(1+SPYrets)
Error: object 'SPYrets' not found
> comparison <- cbind(cumPortfRets, cumSPYrets)
Error in cbind(cumPortfRets, cumSPYrets) : 
  object 'cumPortfRets' not found
> colnames(comparison)  <- c("strategy", "SPY")
Error in colnames(comparison) <- c("strategy", "SPY") : 
  object 'comparison' not found
> chart.TimeSeries(comparison, legend.loc = "topleft",
+                  colors=c("green","red"))
Error in inherits(x, "xts") : object 'comparison' not found
> chart.RelativePerformance(portfRets,SPYrets)
Error in inherits(x, "xts") : object 'portfRets' not found
> 
> SharpeRatio.annualized(portfRets)
Error in inherits(x, "xts") : object 'portfRets' not found
> Return.annualized(portfRets)
Error in is.vector(R) : object 'portfRets' not found
> maxDrawdown(portfRets)
Error in is.vector(R) : object 'portfRets' not found
> 
> chart.Posn(portfolio.st, "XLB")
Error in chart.Posn(portfolio.st, "XLB") : 
  object 'portfolio.st' not found
> sma <- SMA(Cl(XLB), n=nSMA)
Error in has.Cl(x) : object 'XLB' not found
> add_TA(sma, on=1, lwd=2, col="blue")
Error in add_TA(sma, on = 1, lwd = 2, col = "blue") : 
  object 'sma' not found
> rsi <- CycleRSI(Cl(XLB), n=nRSI)
Error in has.Cl(x) : object 'XLB' not found
> add_TA(rsi, col="blue")
Error in add_TA(rsi, col = "blue") : object 'rsi' not found
> atr <- lagATR(HLC=HLC(XLB), n=period)
Error in has.Hi(x) : object 'XLB' not found
> add_TA(atr, col="purple")
Error in add_TA(atr, col = "purple") : object 'atr' not found
> 
> agg.chart.ME(portfolio.st, symbols, type="MAE", scale="cash")
Error in for (Symbol in Symbols) { : invalid for() loop sequence
> 
> agg.chart.ME(portfolio.st, symbols, type="MFE", scale="cash")
Error in for (Symbol in Symbols) { : invalid for() loop sequence
>

Reply With Quote
 
  #5 (permalink)
Site Administrator
Manta, Ecuador
 
Futures Experience: Advanced
Platform: My own custom solution
Favorite Futures: E-mini ES S&P 500
 
Big Mike's Avatar
 
Posts: 46,240 since Jun 2009
Thanks: 29,353 given, 83,234 received

Why are your removing the strat the line after you define it?

Just read the code and you will see the errors.

Sent from my LG Optimus G Pro

Due to time constraints, please do not PM me if your question can be resolved or answered on the forum.

Need help?
1) Stop changing things. No new indicators, charts, or methods. Be consistent with what is in front of you first.
2) Start a journal and post to it daily with the trades you made to show your strengths and weaknesses.
3) Set goals for yourself to reach daily. Make them about how you trade, not how much money you make.
4) Accept responsibility for your actions. Stop looking elsewhere to explain away poor performance.
5) Where to start as a trader? Watch this webinar and read this thread for hundreds of questions and answers.
6)
Help using the forum? Watch this video to learn general tips on using the site.

If you want
to support our community, become an Elite Member.

Reply With Quote
 
  #6 (permalink)
Elite Member
Philadelphia + NJ/US
 
Futures Experience: Beginner
Platform: quantstrat
Favorite Futures: ETFs
 
Posts: 52 since Aug 2014
Thanks: 4 given, 39 received


Big Mike View Post
Why are your removing the strat the line after you define it?

Just read the code and you will see the errors.

Sent from my LG Optimus G Pro

The strategy.st is just a string. The strategy is defined after removing it, in the line strategy(strategy.st, store=TRUE)

There are plenty of standalone demos in the demo directory of quantstrat itself. Do *any* of those work for you?

Reply With Quote
The following user says Thank You to IlyaKipnis for this post:
 
  #7 (permalink)
Elite Member
Philadelphia + NJ/US
 
Futures Experience: Beginner
Platform: quantstrat
Favorite Futures: ETFs
 
Posts: 52 since Aug 2014
Thanks: 4 given, 39 received

I just built this strategy from scratch and tested it on a clean environment. This is a self-contained running strategy.

 
Code
rm(list=ls())
require(quantstrat)

initDate <- "1990-01-01"
from="2000-01-01"
to="2010-01-01"
options(width=70)

options("getSymbols.warning4.0"=FALSE)
currency('USD')
Sys.setenv(TZ="UTC")
symbols <- "SPY"
getSymbols(symbols, from=from, to=to, src="yahoo")
stock(symbols, currency="USD", multiplier=1)

initEq <- 100000
strategy.st <- portfolio.st <- account.st <- "toyStrat"
rm.strat(portfolio.st)
rm.strat(strategy.st)
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='USD',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)

#parameters
nRSI = 2
thresh = 5

nSMAexit = 5

add.indicator(strategy.st, name="RSI",
              arguments=list(price=quote(Cl(mktdata)), n=nRSI),
              label="rsi")

add.indicator(strategy.st, name="SMA",
              arguments=list(x=quote(Cl(mktdata)), n=nSMAexit),
              label="quickMA")

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="rsi", threshold=thresh,
                          relationship="lt", cross=FALSE),
           label="longEntry")

add.signal(strategy.st, name="sigCrossover",
           arguments=list(columns=c("Close", "quickMA"), relationship="gt"),
           label="longExit")

add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="longEntry", sigval=TRUE, orderqty=100, ordertype="market", 
                        orderside="long", replace=FALSE, prefer="Open"), 
         type="exit", path.dep=TRUE)

add.rule(strategy.st, name="ruleSignal", 
         arguments=list(sigcol="longExit", sigval=TRUE, orderqty="all", ordertype="market", 
                        orderside="long", replace=FALSE, prefer="Open"), 
         type="exit", path.dep=TRUE)

#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
t2 <- Sys.time()
print(t2-t1)

#set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)


#trade statistics
tStats <- tradeStats(Portfolios = portfolio.st, use="trades", inclZeroDays=FALSE)
tStats[,4:ncol(tStats)] <- round(tStats[,4:ncol(tStats)], 2)
print(data.frame(t(tStats[,-c(1,2)])))
chart.Posn(portfolio.st, "SPY")
Here's the output I get:

 
Code
> print(data.frame(t(tStats[,-c(1,2)])))
                        SPY
Num.Txns             197.00
Num.Trades            67.00
Net.Trading.PL     14996.00
Avg.Trade.PL         223.82
Med.Trade.PL         150.00
Largest.Winner      3885.00
Largest.Loser      -1236.00
Gross.Profits      19674.00
Gross.Losses       -4678.00
Std.Dev.Trade.PL     606.29
Percent.Positive      79.10
Percent.Negative      20.90
Profit.Factor          4.21
Avg.Win.Trade        371.21
Med.Win.Trade        230.00
Avg.Losing.Trade    -334.14
Med.Losing.Trade    -152.50
Avg.Daily.PL         223.82
Med.Daily.PL         150.00
Std.Dev.Daily.PL     606.29
Ann.Sharpe             5.86
Max.Drawdown       -4221.00
Profit.To.Max.Draw     3.55
Avg.WinLoss.Ratio      1.11
Med.WinLoss.Ratio      1.51
Max.Equity         15031.00
Min.Equity          -187.00
End.Equity         14996.00

Reply With Quote
The following user says Thank You to IlyaKipnis for this post:
 
  #8 (permalink)
Elite Member
Singapore
 
Futures Experience: Beginner
Platform: Multicharts, R
Favorite Futures: EUR / USD
 
Posts: 185 since Feb 2010
Thanks: 106 given, 98 received

I ran IlyaKipnis's code on my Mac R installation and it works, got the same results.

I haven't had to do anything special to get this to work on the Mac

Not sure whether this helps to solve the problem...

Reply With Quote
 
  #9 (permalink)
Trading Apprentice
Chicago IL
 
Futures Experience: Advanced
Platform: MetaTrader, Other
Favorite Futures: Bonds
 
Posts: 1 since Apr 2015
Thanks: 1 given, 0 received

Very curious whether OP figured out his problem

I'm new to using R, I have a strat programmed for ConnorsRSI that continuously gives me object reject errors. Here is what I get when I tried Ilya's code:


 
Code
> #apply strategy
> t1 <- Sys.time()
> out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
Error in `colnames<-`(`*tmp*`, value = c("SPY.Close.SMA.5", "SPY.Close.EMA.2.rsi.SMA.5" : 
  length of 'dimnames' [2] not equal to array extent


This is where the first error occurs and following this none of the code works. The tStats object returns NULL.
I believe this has something to do with my installation of quantstrat. Can anyone shed any light on this?

Also, as a disclaimer, I apologize for the terrible format for code. I just happened to stumble upon this Forum and was excited to see someone else had come up against the same problem, so please forgive my formatting.

Reply With Quote
 
  #10 (permalink)
Elite Member
Philadelphia + NJ/US
 
Futures Experience: Beginner
Platform: quantstrat
Favorite Futures: ETFs
 
Posts: 52 since Aug 2014
Thanks: 4 given, 39 received



bt1729 View Post
I'm new to using R, I have a strat programmed for ConnorsRSI that continuously gives me object reject errors. Here is what I get when I tried Ilya's code:


 
Code
> #apply strategy
> t1 <- Sys.time()
> out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
Error in `colnames<-`(`*tmp*`, value = c("SPY.Close.SMA.5", "SPY.Close.EMA.2.rsi.SMA.5" : 
  length of 'dimnames' [2] not equal to array extent


This is where the first error occurs and following this none of the code works. The tStats object returns NULL.
I believe this has something to do with my installation of quantstrat. Can anyone shed any light on this?

Also, as a disclaimer, I apologize for the terrible format for code. I just happened to stumble upon this Forum and was excited to see someone else had come up against the same problem, so please forgive my formatting.

Check your indicator names. Also, google Nuts and Bolts of Quantstrat. I wrote it to try and get people up and running with the basics. Of course, nothing beats the 2013 R/Finance Quantstrat presentation by the package's authors, one of whom is an elite algo trading director in Chicago.

Reply With Quote
The following user says Thank You to IlyaKipnis for this post:

Reply



futures io > > > > No Strategies Work In R: Demos Included...

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Jigsaw Trading: TBA

Elite only

FuturesTrader71: TBA

Elite only

NinjaTrader: TBA

Jan 18

RandBots: TBA

Jan 23

GFF Brokers & CME Group: Futures & Bitcoin

Elite only

Adam Grimes: TBA

Elite only

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
Webinar: Designing an Algo Trading System from A-to-Z, code included (Kevin Davey) Big Mike Elite Automated Trading 82 April 21st, 2017 09:51 AM
Are filled limit orders included in footprint / volume ladder charts? tinus NinjaTrader 1 June 13th, 2013 08:54 AM
any rithmic demos ? shanemcdonald28 MultiCharts 0 April 17th, 2013 08:12 PM
NT8 "out of the box" indicators, what should be included? Big Mike NinjaTrader 14 March 8th, 2013 07:05 PM
Anti-American Demos in Afghanistan Cities GridKing News and Current Events 0 February 22nd, 2012 02:24 AM


All times are GMT -4. The time now is 01:59 PM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
All information is for educational use only and is not investment advice.
There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
no new posts
Page generated 2017-12-15 in 0.13 seconds with 19 queries on phoenix via your IP 54.82.56.95