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:3,187 / 10
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 100,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...

  #11 (permalink)
Hradec Králové + Czech republic
 
 
Posts: 1 since Feb 2018
Thanks: 0 given, 0 received


CaptainNegatory View Post
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'.
>

Hello,

as far as I understand, there are two problems - first - not correctly installed or loaded quantstrat package and the second is the part with getting data for SPY:

getSymbols("SPY", from=firstNonZeroDay, to=to) - the "from" parametr is NA, because there is no firstNonZeroDay -> all portfRets are zero....

Hope that it will help someone, I have just digg it for a while...

Best regards,
R.

Reply With Quote

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)
 

futures io is celebrating 10-years w/ over $18,000 in prizes!

Right now
 

$1,000 in Amazon Gift Cards being given away right now from GFF Brokers

Right now
 

$250 Amazon Gift Cards with our "Thanks Contest" challenge!

Right now
 

Show us your trading desks and win over $5,000 in prizes w/Jigsaw Trading

August
 

Webinar: Suri Duddella (TBA)

Elite only
 

Webinar: Richard Bailey (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 08:51 AM
Are filled limit orders included in footprint / volume ladder charts? tinus NinjaTrader 1 June 13th, 2013 07:54 AM
any rithmic demos ? shanemcdonald28 MultiCharts 0 April 17th, 2013 07:12 PM
NT8 "out of the box" indicators, what should be included? Big Mike NinjaTrader 14 March 8th, 2013 06:05 PM
Anti-American Demos in Afghanistan Cities GridKing News and Current Events 0 February 22nd, 2012 01:24 AM


All times are GMT -4. The time now is 06:43 PM. (this page content is cached, log in for real-time version)

Copyright © 2019 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