[R-SIG-Finance] Custom Txnfee function in apply.paramset vs applyStrategy

Atakan Okan atakanokan at outlook.com
Mon Apr 25 17:43:33 CEST 2016


So the code seems a bit odd, the indentation must have somehow caused some problems when emailing.
This a better and a little bit more compact one:
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<SlowSMA')

#SL/Trail-SL/TP Optimization-----------------------------------------------------------------
#Long Stoploss Optimizationadd.distribution(strategy.st,                 paramset.label = paramset.label.name,                 component.type = "chain",                 component.label = "StopLossLong",                 variable = list( threshold = StopLossDistanceRange ),                 label = "StopLossLONG")
#Short Stoploss Optimizationadd.distribution(strategy.st,                 paramset.label = paramset.label.name,                 component.type = "chain",                 component.label = "StopLossShort",                 variable = list( threshold = StopLossDistanceRange ),                 label = "StopLossSHORT")
#Long&Short Stoploss Distance Constraintadd.distribution.constraint(strategy.st,                            paramset.label = paramset.label.name,                            distribution.label.1 = "StopLossLONG",                            distribution.label.2 = "StopLossSHORT",                            operator = "==",                            label = "StoplossEquality")
summary(getStrategy(strategy.st))                                              

#First run apply.paramset()paramsetenv<-new.env()cl <- 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 NetPnLshortStopLossDistance <- 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 applyStrategyresults.df$Net.Trading.PL[12]  == results.df.2$Net.Trading.PL
From: atakanokan at outlook.com
To: r-sig-finance at r-project.org
Subject: Custom Txnfee function in apply.paramset vs applyStrategy
Date: Sun, 24 Apr 2016 21:36:33 +0300




Hi,
I have been experimenting with different custom transaction fee models for different assets and I realized that apply.paramset and applyStrategy yields different results when a custom transaction fee function is used. 
The reproducible example is below, and even though apply.paramset yields a NetPnL result of 21779 with the custom transaction fee model, applyStrategy yields 21509, which makes me believe that apply.paramset somehow is not incorporating the fees. The comparison of NetPnL results were made with the parameter combination of FastSMA=5, SlowSMA=50 and Stoploss=0.005.
Any help is appreciated, thanks.
Atakan Okan
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=FALSE         #timespan = xxxx,         #store=TRUE         #storefun=FALSE )
# 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=FALSE         #timespan = xxxx,         #store=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=FALSE)
# 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=FALSE         #timespan = xxxx,         #store=TRUE         #storefun=FALSE )
# 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=FALSE         #timespan = xxxx,         #store=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=FALSE)

#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<SlowSMA')

#SL/Trail-SL/TP Optimization-----------------------------------------------------------------
#Long Stoploss Optimizationadd.distribution(strategy.st,                 paramset.label = paramset.label.name,                 component.type = "chain",                 component.label = "StopLossLong",                 variable = list( threshold = StopLossDistanceRange ),                 label = "StopLossLONG")
#Short Stoploss Optimizationadd.distribution(strategy.st,                 paramset.label = paramset.label.name,                 component.type = "chain",                 component.label = "StopLossShort",                 variable = list( threshold = StopLossDistanceRange ),                 label = "StopLossSHORT")
#Long&Short Stoploss Distance Constraintadd.distribution.constraint(strategy.st,                            paramset.label = paramset.label.name,                            distribution.label.1 = "StopLossLONG",                            distribution.label.2 = "StopLossSHORT",                            operator = "==",                            label = "StoplossEquality")

enable.rule(strategy.st,type="enter",label="longenter", enable = TRUE) enable.rule(strategy.st,type="exit",label="longexit", enable = TRUE)enable.rule(strategy.st,type="enter",label="shortenter", enable = TRUE) enable.rule(strategy.st,type="exit",label="shortexit", enable = TRUE)enable.rule(strategy.st,type="chain",label="StopLossLong", enable = TRUE)enable.rule(strategy.st,type="chain",label="StopLossShort", enable = TRUE) summary(getStrategy(strategy.st))                                              

#First run apply.paramset()paramsetenv<-new.env()cl <- 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 NetPnLshortStopLossDistance <- 0.005                  #SL of best combination by NetPnL
applyStrategy( strategy=strategy.st , portfolios=strategy.st  ,verbose=TRUE)updatePortf(strategy.st)updateAcct(strategy.st)updateEndEq(strategy.st)
results.df.2 <- data.frame(tradeStats(strategy.st))
#Check NetPnL resulting from apply.paramset vs applyStrategyresults.df$Net.Trading.PL[12]  == results.df.2$Net.Trading.PL 		 	   		   		 	   		  
	[[alternative HTML version deleted]]



More information about the R-SIG-Finance mailing list