Skip to content
Prev 13884 / 15274 Next

Custom Txnfee function in apply.paramset vs applyStrategy

Oh sorry about that. Thanks for pointing it out Mr.Ulrich. If it did not work, I will use an gmail account  to send the code for the next try. 

Here is the code:

library(lattice);library(foreach);library(doSNOW);library(ggplot2)
library(gridExtra);library(reshape);library(beepr);library(quantstrat) 
library(doSNOW)
Sys.setenv(TZ="UTC")                                                                                 
.strategy<- new.env();.blotter<- new.env()                                                                                                                             

currency('USD')                                                                                                                                                                      
stock("AAPL", currency="USD", multiplier=1,tick_size= 0.01)

getSymbols('AAPL',src = 'yahoo', from="2014-01-01", to="2015-05-31")
AAPL <- adjustOHLC(AAPL)

strategy.st <- paste("AAPL","MACD_D1",sep = "_")
rm.strat(strategy.st) 

initialEquity = 100000                                                                               
initDate = "2013-12-30" 
initPortf(strategy.st, "AAPL", initDate=initDate, currency = "USD")
initAcct(strategy.st, portfolios=strategy.st, initDate=initDate, initEq=initialEquity, currency = "USD")
initOrders(portfolio=strategy.st,initDate=initDate) 
strategy(strategy.st,store=TRUE)

customFees <- function (TxnQty, ...) 
{
  return(abs(TxnQty) * -0.01)
}
txn.model <- "customFees"    

positionSizeLong  =  1000     
positionSizeShort =  -1000     


paramset.label.name <- "SMA_OPT"
FastSMARange <- seq(5,21,by=8)
SlowSMARange <- seq(10,50,by=20)
StopLossDistanceRange <- seq(0.0025,0.005,by=0.0025)                               


add.indicator(strategy.st,                                               
              name = "SMA",                                               
              arguments = list(x=Cl(eval(parse(text = "AAPL")))
                               ,n=5   #fastsma of best combination by NetPnL
              ),                                                            
              label='fastsma')                                           

add.indicator(strategy.st,                                                 
              name = "SMA",                                                
              arguments = list(x=Cl(eval(parse(text = "AAPL")))
                               ,n=50    #slowsma of best combination by NetPnL
              ),                                                           
              label='slowsma')                                             

add.signal(strategy.st,
           name="sigCrossover",
           arguments = list(columns=c("fastsma","slowsma"),relationship="gt"),
           label="fastsma.gt.slowsma")                                                        

add.signal(strategy.st,
           name="sigCrossover",
           arguments = list(columns=c("fastsma","slowsma"),relationship="lt"),
           label="fastsma.lt.slowsma")

add.rule(strategy.st,
         name='ruleSignal',
         arguments = list(sigcol="fastsma.gt.slowsma",
                          sigval=TRUE,
                          prefer="Open", 
                          orderqty= positionSizeLong, 
                          #osFUN="osAllInLong",  
                          ordertype='market',
                          orderside='long',
                          orderset='ocolong',
                          TxnFees = txn.model),
         type='enter',
         label='longenter',
         enabled=TRUE
)

# Long Exit Rule-------------------------------------------------------------------
add.rule(strategy.st,
         name='ruleSignal',
         arguments = list(sigcol="fastsma.lt.slowsma",
                          sigval=TRUE,
                          prefer="Open", 
                          orderqty='all',
                          ordertype='market',
                          orderside='long',
                          orderset='ocolong',
                          TxnFees = txn.model),
         type='exit',
         label='longexit',
         enabled=TRUE
)

# Long StopLoss Rule---------------------------------------------------------------------------
add.rule(strategy.st,name='ruleSignal',
         arguments = list( sigcol="fastsma.lt.slowsma", sigval=TRUE,
                           replace=FALSE,
                           orderside='long',
                           ordertype='stoplimit',
                           tmult=TRUE,
                           threshold=quote( longStopLossDistance ),
                           orderqty='all',
                           orderset='ocolong',
                           TxnFees = txn.model),
         type='chain', parent="longenter",
         label='StopLossLong',
         enabled=TRUE)

# Short Entry Rule--------------------------------------------------------------------
add.rule(strategy.st,
         name='ruleSignal',
         arguments = list(sigcol="fastsma.lt.slowsma",
                          sigval=TRUE,
                          prefer="Open", 
                          orderqty=positionSizeShort, 
                          #osFUN="osAllInShort",  
                          ordertype='market',
                          orderside='short',
                          orderset='ocoshort',
                          TxnFees = txn.model),
         type='enter',
         label='shortenter',
         enabled=TRUE
)

# Short Exit Rule---------------------------------------------------------------------
add.rule(strategy.st,
         name='ruleSignal',
         arguments = list(sigcol="fastsma.gt.slowsma",
                          sigval=TRUE,
                          prefer="Open", 
                          orderqty='all',
                          ordertype='market',
                          orderside='short',
                          orderset='ocoshort',
                          TxnFees = txn.model),
         type='exit',
         label='shortexit',
         enabled=TRUE
)

# Short Stop Loss Rule-----------------------------------------------------------------
add.rule(strategy.st,name='ruleSignal',
         arguments = list( sigcol="fastsma.gt.slowsma", sigval=TRUE,
                           replace=FALSE,
                           orderside='short',
                           ordertype='stoplimit',
                           tmult=TRUE,
                           threshold=quote( shortStopLossDistance ),
                           orderqty='all',
                           orderset='ocoshort',
                           TxnFees = txn.model),
         type='chain', parent="shortenter",
         label='StopLossShort',
         enabled=TRUE)


#Indicator Optimization-------------------------------------------------------------
add.distribution(strategy.st,
                 paramset.label = paramset.label.name,
                 component.type = 'indicator',
                 component.label = "fastsma",
                 variable = list( n = FastSMARange ),               
                 label = "FastSMARANGE")


add.distribution(strategy.st,
                 paramset.label = paramset.label.name,
                 component.type = 'indicator',
                 component.label = "slowsma",
                 variable = list( n = SlowSMARange ),
                 label = "SlowSMARANGE")

add.distribution.constraint(strategy.st,
                            paramset.label = 'SMA_OPT',
                            distribution.label.1 = 'FastSMARANGE',
                            distribution.label.2 = 'SlowSMARANGE',
                            operator = '<',
                            label = 'FastSMA<- snow::makeCluster(4, type = "SOCK")
registerDoSNOW(cl)
results <- apply.paramset(strategy.st,paramset.label=paramset.label.name,
                          portfolio=strategy.st, account=strategy.st,nsamples=0,verbose = TRUE,
                          audit=paramsetenv)
snow::stopCluster(cl)
results.df <- data.frame(results$tradeStats)


#Second run applyStrategy()
longStopLossDistance <- 0.005   #SL of best combination by NetPnL
shortStopLossDistance <- 0.005  #SL of best combination by NetPnL

applyStrategy( strategy=strategy.st , portfolios=strategy.st
               #,parameters=list(n = 5)
               ,verbose=TRUE)
updatePortf(strategy.st)
updateAcct(strategy.st)
updateEndEq(strategy.st)

results.df.2 <- data.frame(tradeStats(strategy.st))

#Check NetPnL apply.paramset vs applyStrategy
results.df$Net.Trading.PL[12]  == results.df.2$Net.Trading.PL