Webinar: An Introduction To R for Trading w/Ilya Kipnis - Matlab, R project and Python | futures io social day trading
futures io futures trading


Webinar: An Introduction To R for Trading w/Ilya Kipnis
Updated: Views / Replies:26,845 / 150
Created: by Big Mike Attachments:44

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
 44  
 
Thread Tools Search this Thread
 

Webinar: An Introduction To R for Trading w/Ilya Kipnis

  #81 (permalink)
Elite Member
Alesia E.U.
 
Futures Experience: Intermediate
Platform: Sierra chart
Favorite Futures: Futures
 
Posts: 166 since Feb 2011
Thanks: 139 given, 109 received

Hi

thanks @IlyaKipnis for the Webinair .
I downloaded it so i can code and understand better , also i can review each aspect more times .
i hope can be another webinair soon .

Reply With Quote
 
  #82 (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

Package Installation Issue (SOLVED)!


CaptainNegatory View Post
Hey Everyone,
Has anyone else on Mac had issues with Ilya's library install? When I run the following code in R I keep getting an error. I've now tried it with 3.0.3, 3.1.0, and the latest version, with no luck.

install.packages("quantstrat", repos="ht://R-Forge(dot)R-project(dot)org")

yields:

Warning in install.packages :
cannot open: HTTP status was '404 Not Found'
Warning in install.packages :
cannot open: HTTP status was '404 Not Found'
Warning in install.packages :
unable to access index for repository R-Forge(dot)R-project(dot)org/bin/macosx/contrib/3.1

package ‘quantstrat’ is available as a source package but not as a binary

Warning in install.packages :
package ‘quantstrat’ is not available (for R version 3.1.0)

Note that I had to edit the links otherwise the forum would not let me post.

For everyone who is curious how I FINALLY solved the issue, I've listed the steps below. It was a two day tedious process, but I finally got it all sorted, and look forward to using the packages.
  1. Completely Uninstall R and Everything Associated With It
  2. Install R V3.1.1 Mavericks
  3. Install gfortran V4.8 with the following command:
  4. Open R, and run these code lines first:
  5.  
    Code
    install.packages("Defaults”)
  6.  
    Code
    install.packages("devtools”)
  7.  
    Code
    install.packages("zoo”)
  8. After Succesful Install Run These Codes Line By Line:
  9.  
    Code
    install.packages("quantstrat", repos="http://R-Forge.R-project.org", type="source”)
  10.  
    Code
    install.packages("TTR", repos="http://R-Forge.R-project.org", type="source”)
  11. Last But Not Least, I Ran These
  12.  
    Code
    install_github(repo"IKTrading", username = "IlyaKipnis”)
  13.  
    Code
    install_github(repo"DSTrading", username = "IlyaKipnis”)
  14. Installed RStudio
All that said and done, everything installed and is now working properly. I’m not sure if it was the Macbook Update/gfortran 4.8/Using R to install everything first, but it’s working. This is what I’m going to recommend to other mac users on the tutorial forum that were having issues.
Regards,
C. Negatory

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



CaptainNegatory View Post
For everyone who is curious how I FINALLY solved the issue, I've listed the steps below. It was a two day tedious process, but I finally got it all sorted, and look forward to using the packages.
  1. Completely Uninstall R and Everything Associated With It
  2. Install R V3.1.1 Mavericks
  3. Install gfortran V4.8 with the following command:
  4. Open R, and run these code lines first:
  5.  
    Code
    install.packages("Defaults”)
  6.  
    Code
    install.packages("devtools”)
  7.  
    Code
    install.packages("zoo”)
  8. After Succesful Install Run These Codes Line By Line:
  9.  
    Code
    install.packages("quantstrat", repos="http://R-Forge.R-project.org", type="source”)
  10.  
    Code
    install.packages("TTR", repos="http://R-Forge.R-project.org", type="source”)
  11. Last But Not Least, I Ran These
  12.  
    Code
    install_github(repo"IKTrading", username = "IlyaKipnis”)
  13.  
    Code
    install_github(repo"DSTrading", username = "IlyaKipnis”)
  14. Installed RStudio
All that said and done, everything installed and is now working properly. I’m not sure if it was the Macbook Update/gfortran 4.8/Using R to install everything first, but it’s working. This is what I’m going to recommend to other mac users on the tutorial forum that were having issues.
Regards,
C. Negatory

Thank you so much for this. I suppose I'll use it as a reference from now on.

Reply With Quote
 
  #84 (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

Code From Video:

Hello Everyone,
Below is the code from the video, followed by the errors it throws. I got most of it, but I can't seem to iron out these last few bugs. Anyhow, if anybody wants it (or can fix it) here it is:

The Code:

 
Code
require("quantstrat")
require("IKTrading")
require("DSTrading")

options("getSymbols.warning4.0" = FALSE)
rm(list=ls(.blotter), envir = .blotter)
currency('USD')
Sys.setenv(TZ="UTC")

symbols <- "SPY"
suppressMessages(getSymbols(symbols, from = "1998-01-01", to = "2012-12-31"))
stock(symbols, currency = "USD", multiplier = 1)
initDate = "1990-01-01"

tradeSize <- 100000
initEq <- tradeSize * length(symbols)

strategy.st <- portfolio.st <- account.st <- "RSI_Strat_Test"
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
thresh1 = 10
thresh2 = 6

nSMAexit = 5
nSMAfilter = 200

period = 10
pctATR = .02
maxPct = .04

#indicators
add.indicator(strategy.st, name="lagATR", arguments = list(HLC = quote(HLC(mktdata))), n = period,
              label = "atrx")

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.indicator(strategy.st, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n = nSMAfilter),
              label = "filterMA"

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

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

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

add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh1","upTrend"), cross = TRUE),
           label = "longEntry1")

add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh2","upTrend"), cross = TRUE),
           label = "longEntry2")

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

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

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

add.rule(strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "longEntry2",
                          sigval = TRUE,
                          ordertype = "market",
                          orderside = "long",
                          replace = FALSE,
                          prefer = "Open",
                          osFun = osDollarATR,
                          tradeSize = tradeSize,
                          pctATR = pctATR,
                          maxPctATR = maxPct,
                          atrMod = "X"),
         type = "enter", path.dep = TRUE, label = "enterLong2")

add.rule(strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "exitLongNormal",
                          sigval = TRUE,
                          orderqty = "all",
                          ordertype = "market",
                          orderside = "long",
                          replace = FALSE,
                          prefer = "Open",
         type = "exit", path.dep = TRUE, label = "normalExitLong"))
         
add.rule(strategy.st, name = "ruleSignal",
        arguments = list(sigcol = "exitLongFilter",
                         sigval = TRUE,
                         orderqty = "all",
                         ordertype = "market",
                         orderside = "long",
                         replace = FALSE,
                         prefer = "Open",
         type = "exit", path.dep = TRUE, label = "filterExitLong"))
        
#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)

#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
The Errors:

 
Code
+ add.signal(strategy.st, name="sigComparison", 
Error: unexpected symbol in:
"#signals
add.signal"
>            arguments = list(columns = c("Close", "filterMA"),relationship = "gt"),
Error: unexpected ',' in "           arguments = list(columns = c("Close", "filterMA"),relationship = "gt"),"
>            label = "upTrend")
Error: unexpected ')' in "           label = "upTrend")"
> 
> add.signal(strategy.st, name="sigThreshold", arguments = list(column = "rsi", threshold = thresh1, relationship = "lt",
+            cross = FALSE), label = "rsiThresh1")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigThreshold", arguments = list(column = "rsi", threshold = thresh2, relationship = "lt",
+            cross = FALSE), label = "rsiThresh2")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh1","upTrend"), cross = TRUE),
+            label = "longEntry1")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh2","upTrend"), cross = TRUE),
+            label = "longEntry2")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigCrossover", arguments = list(columns = c("Close","quickMA"), relationship = "gt"),
+            label = "exitLongNormal")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigCrossover", arguments = list(columns = c("Close","filterMA"), relationship = "lt"),
+            label = "exitLongFilter")
[1] "RSI_Strat_Test"
> 
> #rules
> add.rule(strategy.st, name = "ruleSignal",
+          arguments = list(sigcol = "longEntry1",
+                           sigval = TRUE,
+                           ordertype = "market",
+                           orderside = "long",
+                           replace = FALSE,
+                           prefer = "Open",
+                           osFun = osDollarATR,
+                           tradeSize = tradeSize,
+                           pctATR = pctATR,
+                           maxPctATR = pctATR,
+                           atrMod = "X"),
+          type = "enter", path.dep = TRUE, label = "enterLong1")
[1] "RSI_Strat_Test"
> 
> add.rule(strategy.st, name = "ruleSignal",
+          arguments = list(sigcol = "longEntry2",
+                           sigval = TRUE,
+                           ordertype = "market",
+                           orderside = "long",
+                           replace = FALSE,
+                           prefer = "Open",
+                           osFun = osDollarATR,
+                           tradeSize = tradeSize,
+                           pctATR = pctATR,
+                           maxPctATR = maxPct,
+                           atrMod = "X"),
+          type = "enter", path.dep = TRUE, label = "enterLong2")
[1] "RSI_Strat_Test"
> 
> add.rule(strategy.st, name = "ruleSignal",
+          arguments = list(sigcol = "exitLongNormal",
+                           sigval = TRUE,
+                           orderqty = "all",
+                           ordertype = "market",
+                           orderside = "long",
+                           replace = FALSE,
+                           prefer = "Open",
+          type = "exit", path.dep = TRUE, label = "normalExitLong"))
[1] "RSI_Strat_Test"
>          
> add.rule(strategy.st, name = "ruleSignal",
+         arguments = list(sigcol = "exitLongFilter",
+                          sigval = TRUE,
+                          orderqty = "all",
+                          ordertype = "market",
+                          orderside = "long",
+                          replace = FALSE,
+                          prefer = "Open",
+          type = "exit", path.dep = TRUE, label = "filterExitLong"))
[1] "RSI_Strat_Test"
>         
> #apply strategy
> t1 <- Sys.time()
> out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st)
Error in colNums[i] <- match.names(columns[i], colnames(data)) : 
  replacement has length zero
In addition: Warning message:
In match.names(columns[i], colnames(data)) :
  all columns not located in upTrend for SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted atr.atrx EMA.rsi SMA.quickMA rsiThresh1 rsiThresh2
> t2 <- Sys.time()
> print(t2 - t1)
Time difference of 0.03470397 secs
> 
> #set up analytics
> updatePortf(portfolio.st)
[1] "RSI_Strat_Test"
> dateRange <- time(getPortfolio(portfolio.st)$summary[-1])
> updateAcct(portfolio.st, dateRange)
[1] "RSI_Strat_Test"
> updateEndEq(account.st)
[1] "RSI_Strat_Test"
> 
> #trade statistics
> tStats <- tradeStats(Portfolios = portfolio.st, use = "trades", inclZeroDays = FALSE)
> tStats[,4:ncol(tStats)] <- round(tStats[,4:ncol(tStats)], 2)
Error in 4:ncol(tStats) : argument of length 0
> print(data.frame(t(tStats[,-c(1,2)])))
Error in t.default(tStats[, -c(1, 2)]) : argument is not a matrix
> (aggPF <- sum(tStats$Gross.Profits) /-sum(tStats$Gross.Losses))
[1] NaN
> (aggCorrect <- mean(tStats$Percent.Positive))
[1] NA
Warning message:
In mean.default(tStats$Percent.Positive) :
  argument is not numeric or logical: returning NA
> (numTrades <- sum(tStats$Num.Trades))
[1] 0
> (meanAvgWLR <- mean(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio < Inf], na.rm = TRUE))
[1] NA
Warning message:
In mean.default(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio <  :
  argument is not numeric or logical: returning NA
> 
> #daily and duration statistics
> dStats <- dailyStats(Portfolios = portfolio.st, use = "Equity")
> rownames(dStats) <- gsub(".DailyEndEq", "", rownames(dStats))
> print(data.frame(t(dStats)))
                   SPY
Total.Net.Profit     0
Total.Days           0
Winning.Days         0
Losing.Days          0
Avg.Day.PL         NaN
Med.Day.PL          NA
Largest.Winner       0
Largest.Loser        0
Gross.Profits        0
Gross.Losses         0
Std.Dev.Daily.PL    NA
Percent.Positive   NaN
Percent.Negative   NaN
Profit.Factor      NaN
Avg.Win.Day        NaN
Med.Win.Day         NA
Avg.Losing.Day     NaN
Med.Losing.Day      NA
Avg.Daily.PL       NaN
Med.Daily.PL        NA
Std.Dev.Daily.PL.1  NA
Ann.Sharpe         NaN
Max.Drawdown         0
Profit.To.Max.Draw NaN
Avg.WinLoss.Ratio  NaN
Med.WinLoss.Ratio   NA
Max.Equity           0
Min.Equity           0
End.Equity           0
> durStats <- durationStatistics(Portfolio = portfolio.st, Symbols = sort(symbols))
Error in seq.int(trades$Start[i], trades$End[i]) : 
  'from' cannot be NA, NaN or infinite
> indivDurStats <- durationStatistics(Portfolio = portfolio.st, Symbols = sort(symbols), aggregate = FALSE)
Error in seq.int(trades$Start[i], trades$End[i]) : 
  'from' cannot be NA, NaN or infinite
> 
> #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)
  Symbol mktExposure
1    SPY           0
> print(mean(as.numeric(as.character(mktExposure$MktExposure))))
[1] NaN
> 
> #portfolio cash PL
> portString <- paste0("portfolio", portfolio.st)
> portPL <- .blotter[[portString]]$summary$Net.Trading.PL

Reply With Quote
The following user says Thank You to CaptainNegatory for this post:
 
  #85 (permalink)
Elite Member
Lagos, Nigeria
 
Futures Experience: Intermediate
Platform: NinjaTrader, SierraChart
Favorite Futures: Euro Currency & Oil
 
lolu's Avatar
 
Posts: 2,440 since Jun 2009
Thanks: 1,000 given, 1,595 received

For those still having their Snow Leopard and do not want to uninstall RStudio 3.1.1

Although, I have my free Mavericks kept in my Flash drive, I have not installed it 'cos I have various software and tools that require upgrade to new versions for them to run on Mavericks. So, I still have my Mac OS X 10.6.8 (Snow Leopard) on my Mac machine.

Since I already have RStudio 3.1.1 on my Mac, and I have been using it for quite a while, I do not want to downgrade to 3.0.3 in order to install IKTrading/DSTrading and the associated components. So I followed @evayxy method as in post #64 above, and successfully installed IKTrading/DSTrading and the relevant components. But I changed the order of installation and had to include PerformanceAnalytics_1.1.0.tgz as follows;

1. FinancialInstrument_1.1.9.tar.gz
2. PerformanceAnalytics_1.1.0.tgz
3. blotter_0.8.19.tar.gz
4. quantstrat_0.8.2.tar.gz

In addition to the above components installation, I had to install.packages("foreach").

Lolu

Reply With Quote
 
  #86 (permalink)
Elite Member
Lagos, Nigeria
 
Futures Experience: Intermediate
Platform: NinjaTrader, SierraChart
Favorite Futures: Euro Currency & Oil
 
lolu's Avatar
 
Posts: 2,440 since Jun 2009
Thanks: 1,000 given, 1,595 received


CaptainNegatory View Post
Hello Everyone,
Below is the code from the video, followed by the errors it throws. I got most of it, but I can't seem to iron out these last few bugs. Anyhow, if anybody wants it (or can fix it) here it is:

The Code:

 
Code
require("quantstrat")
require("IKTrading")
require("DSTrading")

options("getSymbols.warning4.0" = FALSE)
rm(list=ls(.blotter), envir = .blotter)
currency('USD')
Sys.setenv(TZ="UTC")

symbols <- "SPY"
suppressMessages(getSymbols(symbols, from = "1998-01-01", to = "2012-12-31"))
stock(symbols, currency = "USD", multiplier = 1)
initDate = "1990-01-01"

tradeSize <- 100000
initEq <- tradeSize * length(symbols)

strategy.st <- portfolio.st <- account.st <- "RSI_Strat_Test"
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
thresh1 = 10
thresh2 = 6

nSMAexit = 5
nSMAfilter = 200

period = 10
pctATR = .02
maxPct = .04

#indicators
add.indicator(strategy.st, name="lagATR", arguments = list(HLC = quote(HLC(mktdata))), n = period,
              label = "atrx")

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.indicator(strategy.st, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n = nSMAfilter),
              label = "filterMA"

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

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

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

add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh1","upTrend"), cross = TRUE),
           label = "longEntry1")

add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh2","upTrend"), cross = TRUE),
           label = "longEntry2")

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

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

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

add.rule(strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "longEntry2",
                          sigval = TRUE,
                          ordertype = "market",
                          orderside = "long",
                          replace = FALSE,
                          prefer = "Open",
                          osFun = osDollarATR,
                          tradeSize = tradeSize,
                          pctATR = pctATR,
                          maxPctATR = maxPct,
                          atrMod = "X"),
         type = "enter", path.dep = TRUE, label = "enterLong2")

add.rule(strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "exitLongNormal",
                          sigval = TRUE,
                          orderqty = "all",
                          ordertype = "market",
                          orderside = "long",
                          replace = FALSE,
                          prefer = "Open",
         type = "exit", path.dep = TRUE, label = "normalExitLong"))
         
add.rule(strategy.st, name = "ruleSignal",
        arguments = list(sigcol = "exitLongFilter",
                         sigval = TRUE,
                         orderqty = "all",
                         ordertype = "market",
                         orderside = "long",
                         replace = FALSE,
                         prefer = "Open",
         type = "exit", path.dep = TRUE, label = "filterExitLong"))
        
#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)

#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
The Errors:

 
Code
+ add.signal(strategy.st, name="sigComparison", 
Error: unexpected symbol in:
"#signals
add.signal"
>            arguments = list(columns = c("Close", "filterMA"),relationship = "gt"),
Error: unexpected ',' in "           arguments = list(columns = c("Close", "filterMA"),relationship = "gt"),"
>            label = "upTrend")
Error: unexpected ')' in "           label = "upTrend")"
> 
> add.signal(strategy.st, name="sigThreshold", arguments = list(column = "rsi", threshold = thresh1, relationship = "lt",
+            cross = FALSE), label = "rsiThresh1")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigThreshold", arguments = list(column = "rsi", threshold = thresh2, relationship = "lt",
+            cross = FALSE), label = "rsiThresh2")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh1","upTrend"), cross = TRUE),
+            label = "longEntry1")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigAND", arguments = list(columns = c("rsiThresh2","upTrend"), cross = TRUE),
+            label = "longEntry2")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigCrossover", arguments = list(columns = c("Close","quickMA"), relationship = "gt"),
+            label = "exitLongNormal")
[1] "RSI_Strat_Test"
> 
> add.signal(strategy.st, name="sigCrossover", arguments = list(columns = c("Close","filterMA"), relationship = "lt"),
+            label = "exitLongFilter")
[1] "RSI_Strat_Test"
> 
> #rules
> add.rule(strategy.st, name = "ruleSignal",
+          arguments = list(sigcol = "longEntry1",
+                           sigval = TRUE,
+                           ordertype = "market",
+                           orderside = "long",
+                           replace = FALSE,
+                           prefer = "Open",
+                           osFun = osDollarATR,
+                           tradeSize = tradeSize,
+                           pctATR = pctATR,
+                           maxPctATR = pctATR,
+                           atrMod = "X"),
+          type = "enter", path.dep = TRUE, label = "enterLong1")
[1] "RSI_Strat_Test"
> 
> add.rule(strategy.st, name = "ruleSignal",
+          arguments = list(sigcol = "longEntry2",
+                           sigval = TRUE,
+                           ordertype = "market",
+                           orderside = "long",
+                           replace = FALSE,
+                           prefer = "Open",
+                           osFun = osDollarATR,
+                           tradeSize = tradeSize,
+                           pctATR = pctATR,
+                           maxPctATR = maxPct,
+                           atrMod = "X"),
+          type = "enter", path.dep = TRUE, label = "enterLong2")
[1] "RSI_Strat_Test"
> 
> add.rule(strategy.st, name = "ruleSignal",
+          arguments = list(sigcol = "exitLongNormal",
+                           sigval = TRUE,
+                           orderqty = "all",
+                           ordertype = "market",
+                           orderside = "long",
+                           replace = FALSE,
+                           prefer = "Open",
+          type = "exit", path.dep = TRUE, label = "normalExitLong"))
[1] "RSI_Strat_Test"
>          
> add.rule(strategy.st, name = "ruleSignal",
+         arguments = list(sigcol = "exitLongFilter",
+                          sigval = TRUE,
+                          orderqty = "all",
+                          ordertype = "market",
+                          orderside = "long",
+                          replace = FALSE,
+                          prefer = "Open",
+          type = "exit", path.dep = TRUE, label = "filterExitLong"))
[1] "RSI_Strat_Test"
>         
> #apply strategy
> t1 <- Sys.time()
> out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st)
Error in colNums[i] <- match.names(columns[i], colnames(data)) : 
  replacement has length zero
In addition: Warning message:
In match.names(columns[i], colnames(data)) :
  all columns not located in upTrend for SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted atr.atrx EMA.rsi SMA.quickMA rsiThresh1 rsiThresh2
> t2 <- Sys.time()
> print(t2 - t1)
Time difference of 0.03470397 secs
> 
> #set up analytics
> updatePortf(portfolio.st)
[1] "RSI_Strat_Test"
> dateRange <- time(getPortfolio(portfolio.st)$summary[-1])
> updateAcct(portfolio.st, dateRange)
[1] "RSI_Strat_Test"
> updateEndEq(account.st)
[1] "RSI_Strat_Test"
> 
> #trade statistics
> tStats <- tradeStats(Portfolios = portfolio.st, use = "trades", inclZeroDays = FALSE)
> tStats[,4:ncol(tStats)] <- round(tStats[,4:ncol(tStats)], 2)
Error in 4:ncol(tStats) : argument of length 0
> print(data.frame(t(tStats[,-c(1,2)])))
Error in t.default(tStats[, -c(1, 2)]) : argument is not a matrix
> (aggPF <- sum(tStats$Gross.Profits) /-sum(tStats$Gross.Losses))
[1] NaN
> (aggCorrect <- mean(tStats$Percent.Positive))
[1] NA
Warning message:
In mean.default(tStats$Percent.Positive) :
  argument is not numeric or logical: returning NA
> (numTrades <- sum(tStats$Num.Trades))
[1] 0
> (meanAvgWLR <- mean(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio < Inf], na.rm = TRUE))
[1] NA
Warning message:
In mean.default(tStats$Avg.WinLoss.Ratio[tStats$Avg.WinLoss.Ratio <  :
  argument is not numeric or logical: returning NA
> 
> #daily and duration statistics
> dStats <- dailyStats(Portfolios = portfolio.st, use = "Equity")
> rownames(dStats) <- gsub(".DailyEndEq", "", rownames(dStats))
> print(data.frame(t(dStats)))
                   SPY
Total.Net.Profit     0
Total.Days           0
Winning.Days         0
Losing.Days          0
Avg.Day.PL         NaN
Med.Day.PL          NA
Largest.Winner       0
Largest.Loser        0
Gross.Profits        0
Gross.Losses         0
Std.Dev.Daily.PL    NA
Percent.Positive   NaN
Percent.Negative   NaN
Profit.Factor      NaN
Avg.Win.Day        NaN
Med.Win.Day         NA
Avg.Losing.Day     NaN
Med.Losing.Day      NA
Avg.Daily.PL       NaN
Med.Daily.PL        NA
Std.Dev.Daily.PL.1  NA
Ann.Sharpe         NaN
Max.Drawdown         0
Profit.To.Max.Draw NaN
Avg.WinLoss.Ratio  NaN
Med.WinLoss.Ratio   NA
Max.Equity           0
Min.Equity           0
End.Equity           0
> durStats <- durationStatistics(Portfolio = portfolio.st, Symbols = sort(symbols))
Error in seq.int(trades$Start[i], trades$End[i]) : 
  'from' cannot be NA, NaN or infinite
> indivDurStats <- durationStatistics(Portfolio = portfolio.st, Symbols = sort(symbols), aggregate = FALSE)
Error in seq.int(trades$Start[i], trades$End[i]) : 
  'from' cannot be NA, NaN or infinite
> 
> #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)
  Symbol mktExposure
1    SPY           0
> print(mean(as.numeric(as.character(mktExposure$MktExposure))))
[1] NaN
> 
> #portfolio cash PL
> portString <- paste0("portfolio", portfolio.st)
> portPL <- .blotter[[portString]]$summary$Net.Trading.PL

I got the following error messages when I ran the same script;

> source('~/.active-rstudio-document', echo=TRUE)
Error in source("~/.active-rstudio-document", echo = TRUE) :
~/.active-rstudio-document:52:15: unexpected symbol
51: #signals
52: add.signal
^


Lolu

Reply With Quote
 
  #87 (permalink)
Elite Member
Lagos, Nigeria
 
Futures Experience: Intermediate
Platform: NinjaTrader, SierraChart
Favorite Futures: Euro Currency & Oil
 
lolu's Avatar
 
Posts: 2,440 since Jun 2009
Thanks: 1,000 given, 1,595 received

@IlyaKipnis,

Could you please do a brief note on how to setup your IKTrading-master.zip, and probably the DSTrading-master.zip ?

Lolu

Reply With Quote
 
  #88 (permalink)
Elite Member
Alesia E.U.
 
Futures Experience: Intermediate
Platform: Sierra chart
Favorite Futures: Futures
 
Posts: 166 since Feb 2011
Thanks: 139 given, 109 received

Hi

@IlyaKipnis i'm sorry to annoy you
when i apply the strategy i receive this error:
 
Code
> 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
> t2 <- Sys.time()
> print(t2 - t1)
searching on google, seems related to to the name of one column , but i don't understand how to fix it



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

To those getting the errors at the applyStrategy portion:

Install TTR from R-forge.

install.packages("TTR", repos="http://R-Forge.R-project.org")

To those getting errors at the add.signal phase, with the unexpected ), I'm seeing an extra quotation in your pasted code.

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



lolu View Post
@IlyaKipnis,

Could you please do a brief note on how to setup your IKTrading-master.zip, and probably the DSTrading-master.zip ?

Lolu

You need devtools installed, and need to use the command install_github.

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

Reply



futures io > > > > Webinar: An Introduction To R for Trading w/Ilya Kipnis

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: Introduction to C# and Ninjascript Programming, Feb 23rd @ 1:00PM Eastern shodson The Elite Circle 67 December 2nd, 2014 08:44 PM
Webinar: FuturePath Trading and PhotonTrader introduction w/Damon Pavlatos Big Mike Reviews of Brokers and Data Feeds 47 February 7th, 2014 12:03 PM
Webinar: MultiCharts and Zen-Fire Introduction Big Mike MultiCharts 12 October 4th, 2012 02:15 PM
Webinar Trading Video: Live Trading and Technical Analysis of EuroStoxx 50 max-td Trading Reviews and Vendors 1 March 13th, 2010 07:35 AM
Introduction: Sim trading S&P with Ninja traders SOM123 Traders Hideout 5 December 13th, 2009 11:27 AM


All times are GMT -4. The time now is 12:18 AM.

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-13 in 0.15 seconds with 20 queries on phoenix via your IP 54.221.93.187