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,847 / 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

  #131 (permalink)
Trading Apprentice
Nashville TN/USA
 
Futures Experience: Intermediate
Platform: TOS
Favorite Futures: Currency
 
Posts: 2 since Oct 2014
Thanks: 2 given, 0 received


IlyaKipnis View Post
I have not seen that error message before. You may want to check if your data is an xts/zoo type object.

Thanks for the quick response Ilya. The data type is xts indexed by POSIXlt, POSIXt with the correct time zone. When the same data but in minute bars is used, there isn't an error. May just need to use timed bars instead of volume/tick based bars.

Reply With Quote
 
  #132 (permalink)
Elite Member
seoul, Korea
 
Futures Experience: Intermediate
Platform: Multicharts
Broker/Data: CQG, DTN IQfeed
Favorite Futures: YM 6E
 
treydog999's Avatar
 
Posts: 894 since Jul 2012
Thanks: 291 given, 1,006 received

Is quantstrat a vectorized or event based back tester?

@IlyaKipnis

I have been working with quantstrat recently, but i am pretty confused with how it is actually processing the trades and market data. The reason is that event based is supposed to be more realistic than vectorized testing. I was reading that the indicators and signals are processed in a vectorized manner for faster back testing. When you see market data after applyIndicators/applySignals the values are all listed there for the entire trading span.

But there is no indication as to if the apply strategy is event based or vectorized. It seems like it may be event based just in how the output for the backtest comes out. However I could be incorrect.

Does quantstrat pass every day individually through to build up the strategy performance? In your opinion is there a significant difference between vectorized backtesting and event based back testing results realism?

thx

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



treydog999 View Post
@IlyaKipnis

I have been working with quantstrat recently, but i am pretty confused with how it is actually processing the trades and market data. The reason is that event based is supposed to be more realistic than vectorized testing. I was reading that the indicators and signals are processed in a vectorized manner for faster back testing. When you see market data after applyIndicators/applySignals the values are all listed there for the entire trading span.

But there is no indication as to if the apply strategy is event based or vectorized. It seems like it may be event based just in how the output for the backtest comes out. However I could be incorrect.

Does quantstrat pass every day individually through to build up the strategy performance? In your opinion is there a significant difference between vectorized backtesting and event based back testing results realism?

thx

quantstrat loops through signals individually.

Reply With Quote
The following user says Thank You to IlyaKipnis for this post:
 
  #134 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received

cant install package Defaults

> install.packages("Defaults")
Installing package into ‘C:/Users/tmgike/Documents/R/win-library/3.1’
(as ‘lib’ is unspecified)
Warning in install.packages :
package ‘Defaults’ is not available (for R version 3.1.2)

Anyone know where I can download the package version that works with 3.1.2?

Reply With Quote
 
  #135 (permalink)
 Vendor: sentimentrader.com 
Tulsa, OK
 
Futures Experience: Advanced
Platform: Tradestation, TOS, Python
Broker/Data: IQFeed, Tradestation, TOS
Favorite Futures: ES, SPY, Options
 
ericbrown's Avatar
 
Posts: 201 since Jan 2011
Thanks: 339 given, 234 received


donedge View Post
> install.packages("Defaults")
Installing package into ‘C:/Users/tmgike/Documents/R/win-library/3.1’
(as ‘lib’ is unspecified)
Warning in install.packages :
package ‘Defaults’ is not available (for R version 3.1.2)

Anyone know where I can download the package version that works with 3.1.2?

You can pull it down from the archives and install locally. It doesn't look like it has been updated since before R v.3.1.0

Index of /src/contrib/Archive/Defaults

Reply With Quote
 
  #136 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received


ericbrown View Post
You can pull it down from the archives and install locally. It doesn't look like it has been updated since before R v.3.1.0

Index of /src/contrib/Archive/Defaults

Thank you @Eric Brown!

Reply With Quote
 
  #137 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 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

Hi @CaptainNegatory,

Have you been able to get it compiled and done?

I am also testing to run the code. I found some stuff in the code that maybe is wrong.
=======================================
require("quantstrat")
require("IKTrading")
require("DSTrading")

I think it should look like this:
require(quantstrat)
require(IKTrading)
require(DSTrading)

and I'm not sure if DSTrading is required in this strategy as @IlyaKipnis is not using in his I believe.
=======================================
add.indicator(strategy.st, name="lagATR", arguments = list(HLC = quote(HLC(mktdata))), n = period,
label = "atrx")

I think you need to remove one of the ) and add it after period instead.
=======================================
add.indicator(strategy.st, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n = nSMAfilter),
label = "filterMA"

I think you are missing a ) after "filterMA"
=======================================
osFun = osDollarATR,

Maybe you need to type osFUN ?
=======================================

Reply With Quote
 
  #138 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received


IlyaKipnis View Post
Really strange. I'm not sure if it's an issue with the mac. Maybe Mike might have answers.

I am running R 3.1.2 on Windows 7.
Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


I get no errors, but when I run the last part
> #apply strategy
> t1 <- Sys.time()
> out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st)
> t2 <- Sys.time()
> print(t2 - t1)
Time difference of 2.697127 secs

It does not print out the trades as it does in your video... Any ideas?

When I run the head(mktdata) it shows the values correct, same as @CaptainNegatory

I added debug=TRUE in the applyStrategy
 
Code
#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st, debug=TRUE)
t2 <- Sys.time()
print(t2 - t1)
but dont get any errors...

FYI
My computer is set to show European time/date format, not on UTC time zone, but UTC+1. Thinking of RStudio give some sort of error is time format is not following american format..
Any ideas?


Last edited by donedge; November 6th, 2014 at 06:26 AM.
Reply With Quote
 
  #139 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received


IlyaKipnis View Post
BTW, I found out what was wrong with the people who were getting 0 trades.

Make sure your blotter, TTR, and FinancialInstrument libraries are at their current versions. Install all of them from R-forge, as the default installation settings will install old versions that don't play well with the current functionality.

Hi @IlyaKipnis

Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


Do I have the correct packages loaded and up to date?

Reply With Quote
 
  #140 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received



donedge View Post
I am running R 3.1.2 on Windows 7.
Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


I get no errors, but when I run the last part
> #apply strategy
> t1 <- Sys.time()
> out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st)
> t2 <- Sys.time()
> print(t2 - t1)
Time difference of 2.697127 secs

It does not print out the trades as it does in your video... Any ideas?

When I run the head(mktdata) it shows the values correct, same as @CaptainNegatory

I added debug=TRUE in the applyStrategy
 
Code
#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st, debug=TRUE)
t2 <- Sys.time()
print(t2 - t1)
but dont get any errors...

FYI
My computer is set to show European time/date format, not on UTC time zone, but UTC+1. Thinking of RStudio give some sort of error is time format is not following american format..
Any ideas?

I wrote another strategy with quantstrat and the function applyStrategy is working. So I guess either the IKTrading is not compatible with R3.1.2 or some other function in another package. Please let me know if someone else can run this strategy with R3.1.2 installed.

Here is the code for the strategy I wrote that is working:

 
Code
require(quantstrat)

##### Initialize a currency and a stock instrument #####
currency("USD")
stock("SPY", currency="USD",multiplier = 1)
#ls(envir = FinancialInstrument:::.instrument)
#ls(all=T)

##### Fetch historic data ##### 
initDate <- '1997-12-31'
startDate <- '1998-01-01'
endDate <- '2014-11-05'
initEq <- 1e6
Sys.setenv(TZ="UTC")
getSymbols('SPY', from=startDate, to=endDate, index.class="POSIXct", adjust=T)
SPY=to.monthly(SPY, indexAt = 'endof', drop.time = FALSE)
SPY$SMA10m <- SMA(x = Cl(SPY), n = 10)

##### Initialize portfolio and account ##### 
qs.strategy <- "qsFaber"
rm.strat(qs.strategy) #remove strategy etc. if this is a re-run.
initPortf(qs.strategy, 'SPY', initDate = initDate)
initAcct(qs.strategy, portfolios=qs.strategy, initDate = initDate, initEq = initEq)

##### Initialize orders container ##### args(initOrders)
initOrders(portfolio = qs.strategy, initDate = initDate)

##### Instantiate a new strategy object ##### args(strategy)
strategy(qs.strategy, store=TRUE)

##### Portfolio, account, orderbook and strategy objects ##### 
#ls(all=T)
#ls(.blotter) #.blotter holds the portfolio and account object
#ls(.strategy) #.strategy holds the orderbook and strategy object

##### The quantstrat strategy object ##### args(getStrategy)
strat <- getStrategy(qs.strategy)
#class(strat)
#summary(strat)

##### The add.indicator function ##### args(add.indicator)
add.indicator(strategy=qs.strategy, name="SMA",
              arguments=list(x=quote(Cl(mktdata)), n=10),
              label="SMA10")
#summary(getStrategy(qs.strategy))

##### The add.signals function ##### args(add.signal)

#signal for Close crossing above SMA
add.signal(strategy=qs.strategy, name="sigCrossover",
           arguments=list(columns=c("Close", "SMA10"), relationship="gt"),
           label="Cl.gt.SMA")
#signal for Close crossing below SMA
add.signal(strategy=qs.strategy, name="sigCrossover",
           arguments=list(columns=c("Close", "SMA10"), relationship="lt"),
           label="Cl.lt.SMA")

#summary(getStrategy(qs.strategy))

##### The add.rules function ##### args(add.rule) args(ruleSignal)

#rule go long when close > MA
add.rule(strategy = qs.strategy, name="ruleSignal",
         arguments=list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=900, ordertype="market", orderside="long"),
         type="enter")

#rule exit when close < MA
add.rule(strategy = qs.strategy, name="ruleSignal",
         arguments=list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty="all", ordertype="market", orderside="long"),
         type="exit")

#summary(getStrategy(qs.strategy))

##### The applyStrategy function ##### args(applyStrategy)

applyStrategy(strategy = qs.strategy, portfolios = qs.strategy)

Reply With Quote

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 02:42 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-14 in 0.15 seconds with 20 queries on phoenix via your IP 54.221.76.68