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

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

Hm, okay, I think I found the issue...

Seems to be a windows issue, or an issue with TTR's column naming.

When you add an SMA, where you type x=quote(Cl(mktdata))

Instead, type x=quote(Cl(mktdata))[,1]

Reply With Quote
The following user says Thank You to IlyaKipnis for this post:
 
  #142 (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
Hm, okay, I think I found the issue...

Seems to be a windows issue, or an issue with TTR's column naming.

When you add an SMA, where you type x=quote(Cl(mktdata))

Instead, type x=quote(Cl(mktdata))[,1]

Hi @IlyaKipnis,
I installed Windows 8.1. I got the same error first after added your code above. I restarted my Rstudio and after it worked.. :-)

Thank you for your support and excellent webinar!

 
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 = strategy.st, name="lagATR", arguments = list(HLC = quote(HLC(mktdata)), n = period),
              label = "atrX")

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

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

add.indicator(strategy = 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
              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

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


@donedge glad you're in good shape ^_^

Reply With Quote
 
  #144 (permalink)
Market Wizard
Houston, TX
 
Futures Experience: Advanced
Platform: XTrader
Broker/Data: Advantage Futures
Favorite Futures: Energy
 
Posts: 2,123 since Dec 2013
Thanks: 1,749 given, 3,358 received
Forum Reputation: Legendary

All credit to @NJAMC
https://futures.io/elite-circle/23861-machine-learning-ai-discussion-generic-4.html#post452866

How to Trade the RSI: An analysis using a Support Vector Machine

and linked in that article
How to Backtest a Strategy in R

Reply With Quote
The following user says Thank You to SMCJB for this post:
 
  #145 (permalink)
Trading Apprentice
Newtown, PA/USA
 
Futures Experience: Beginner
Platform: Etrade
Favorite Futures: Violin :-)
 
Posts: 2 since Nov 2014
Thanks: 2 given, 0 received

Unable to install.packages("Defaults")


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

I am also getting the issue with the Defaults:
> install.packages("Defaults")
Warning in install.packages :
package ‘Defaults’ is not available (for R version 3.0.3)

I downloaded the latest version from the archives, but how do I install it locally? (Yes, I'm new to R too). Thanks!

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


AmyKann View Post
I am also getting the issue with the Defaults:
> install.packages("Defaults")
Warning in install.packages :
package ‘Defaults’ is not available (for R version 3.0.3)

I downloaded the latest version from the archives, but how do I install it locally? (Yes, I'm new to R too). Thanks!

Download and go to packages tab in Rstudio and click on install and select the file and it should be installed.
Index of /src/contrib/Archive/Defaults

Reply With Quote
The following user says Thank You to donedge for this post:
 
  #147 (permalink)
Trading Apprentice
Newtown, PA/USA
 
Futures Experience: Beginner
Platform: Etrade
Favorite Futures: Violin :-)
 
Posts: 2 since Nov 2014
Thanks: 2 given, 0 received

THE CODE


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:

Captain,
I was in the "same boat" as you... everything was completing without throwing errors, but I did not see the orders printing. I also could see the data in View(mktdata), but something else must have been off... I thoroughly compared your code and Ilya's (and to mine), and here are some differences:

The bigger errors I found in your code are as follows:
1. First Indicator: atrX
Should be: add.indicator(strategy.st, name="lagATR", arguments = list(HLC=quote(HLC(mktdata)), n=period), label="atrX")
You had: add.indicator(strategy.st, name="lagATR", arguments = list(HLC = quote(HLC(mktdata))), n = period, label = "atrX")
There is an error in the placement of parenthesis.

2. Rules: I find that R is very case sensitive. You have osFun, but I think it should be osFUN. (How FUN!).
I am not sure the next two differences are as important, but I’ll post them anyway:

3. I do not know how sensitive R is to quotes -- your require commands are in quotes, and I don't think they need to be [i.e. require("quantstrat")]

3.1 Similarly, in the initPortf line, does it matter if currency is in single or double quotes?
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')

4. I found instead of using suppressMessages, I used suppressWarnings. Not really important, but it did the intended trick where suppressMessages didn't.

I almost thought I had it all together and my code was matching Ilya’s, but I then received this error:
> out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st)
Error in osFUN(strategy = strategy, data = mktdata, timestamp = timestamp, :
Term atrX not found in mktdata column names.


That’s when I changed atrx to atrX. And it WORKED!

Okay, so here is the code I used:

The Code:

 
Code
require(quantstrat)
require(devtools)
require(DSTrading) 
require(IKTrading)

sessionInfo()

## Setup for new portfolio strategy:  

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

symbols <- "SPY"

suppressWarnings(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)


## Initialize portfolio strategy
strategy.st <- portfolio.st <- account.st <- "RSI_10_6"
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

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

In R, something like:

string <- "myString"

vs.

string <- 'myString'

is identical in functionality.

EG:

 
Code
str1 <- "Hello, world!"
str2 <- 'Hello, world!'

str1==str2
Will give

 
Code
TRUE

Reply With Quote
The following user says Thank You to IlyaKipnis for this post:
 
  #149 (permalink)
Elite Member
Australia
 
Futures Experience: Intermediate
Platform: Python, R
Broker/Data: IB
Favorite Futures: forex
 
Posts: 26 since Sep 2014
Thanks: 0 given, 2 received


CaptainNegatory View Post
If someone could tell me what these errors mean, or suggest a solution, I would appreciate it.

 
Code
> #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
>


HI did anyone find a solution to this issue?
> tStats[,4:ncol(tStats)] <- round(tStats[,4:ncol(tStats)], 2)
Error in 4:ncol(tStats) : argument of length 0

Reply With Quote
 
  #150 (permalink)
Elite Member
Australia
 
Futures Experience: Intermediate
Platform: Python, R
Broker/Data: IB
Favorite Futures: forex
 
Posts: 26 since Sep 2014
Thanks: 0 given, 2 received


solved my own issue.. i was using a simple MA crossover for the rules.. here is a copy of my code for ref


 
Code
require(quantstrat)
require(IKTrading)
require(devtools)
require(DSTrading)
require(PerformanceAnalytics)
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="2015-05-15"))
stock(symbols, currency="USD", multiplier=1)
initDate="1990-01-01"

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

account.st  <- 0
strategy.st  <- portfolio.st <- account.st  <- "RSI_10_6"
#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, store=TRUE)
#strategy(strategy.st, store = TRUE)
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
thres2 = 6

#nSMAexit = 5
nSMAquick = 15
nSMAslow = 30


nSMAfilter = 200

period =10
pctATR = .02
maxPct = .04

#quickMA  <- SMA(x = Cl(SPY), n = 15)
#slowMA  <- SMA(x = Cl(SPY), n = 30)

#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=nSMAquick), label="quickMA")
add.indicator(strategy.st, name = "SMA", arguments=list(x=quote(Cl(mktdata)), n=nSMAslow), label="slowMA")





#add.signal(strategy.st, 
 #            name="sigFormula", 
  #           arguments = list(columns=c("quickMA","slowMA","RSI"), 
   #                           formula = "(SPY.Close > SMA200) & (RSI < 25)", 
    #                          label="trigger", 
     #                         cross=TRUE), 
      #       label="Cl.gt.SMA") 



add.signal(strategy.st, name = "sigCrossover", arguments = list(columns=c("quickMA", "slowMA"),
                                                                relationship="gt"), label="crossUp")
add.signal(strategy.st, name = "sigCrossover", arguments = list(columns=c("slowMA","quickMA"), 
                                                                relationship="lt"), label="crossDown")

#enter rule
add.rule(strategy.st, name = "ruleSignal", arguments = list(sigcol="crossUp",
                                                            sigval=TRUE, 
                                                            ordertype="market",
                                                            orderside=NULL,
                                                            replace=FALSE,
                                                            prefer="close",
                                                            orderqty=1,
                                                            osFun=osDollarATR,
                                                            tradeSize=tradeSize,
                                                            pctATR=pctATR,
                                                            maxPctATR=pctATR,
                                                            atrMod="X"),
         type="enter",path.dep=TRUE,label="crossup")

#exit rule
add.rule(strategy.st, name = "ruleSignal", arguments = list(sigcol="crossDown",
                                                            sigval=TRUE, 
                                                            orderqty="all",
                                                            orderqty=-1,
                                                            ordertype="market",
                                                            orderside=NULL,
                                                            replace=FALSE,
                                                            prefer="open"),
         type="enter",path.dep=TRUE,label="crossdown")

#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st,debug=TRUE )
t2 <- Sys.time()
print(t2-t1)
head(mktdata)
#set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)

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 03:43 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-16 in 0.14 seconds with 20 queries on phoenix via your IP 54.196.201.241