0

I am trying to get quantstrat to work by investing a proportion of the portfolio (100% or 20%) in the position rather than a fixed order quantity (i.e. 10 shares).

I have tried to adapt the ordersize function from (Quantstrat: Ordersize function) but my code errors out when partway through trading:

[1] "2016-06-01 00:00:00 BP 3972.33383061 @ 25.1741178521841"
[1] "2016-06-30 00:00:00 BP -3972.33383061 @ 28.5237037199368"
[1] "2016-09-14 00:00:00 BP 4157.48457062 @ 27.2534200275105"
[1] "2016-11-02 00:00:00 BP 4157.48457062 @ 27.8177899348377"
[1] "2017-03-30 00:00:00 BP -8314.96914124 @ 29.2450509184207"
Error in if (!is.null(orderqty) && orderqty != 0 && length(orderprice)) { : 
  missing value where TRUE/FALSE needed

My code is as follows:

###########################################################################################
#
#  part 1 - initialize things
#
###########################################################################################

initdate <- "2016-01-01"
from <- "2016-01-01" #start of backtest
to <- Sys.Date() #end of backtest

stock(symbols, currency = "GBP", multiplier = 1)


tradesize <-100000 #default trade size
initeq <- 100000 #default initial equity in our portfolio

strategy.st <- portfolio.st <- account.st <- "firststrat" #naming strategy, portfolio and account

#removes old portfolio and strategy from environment
rm.strat(portfolio.st)
rm.strat(strategy.st) 

#initialize portfolio, account, orders and strategy objects
initPortf(portfolio.st, symbols = symbols, initDate = initdate, currency = "GBP")
initAcct(account.st, portfolios = portfolio.st, initDate = initdate, currency = "GBP", initEq = initeq)
initOrders(portfolio.st, initDate = initdate)

# set position limits
strategy(strategy.st, store=TRUE)

#################
#               #
#  add signals  #
#               #
#################

# custom entry signal
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "abv_bb",
                            threshold = 1,
                            relationship = "gte",
                            cross = TRUE),
           label = "thresholdentry")

# custom exit signal
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "blw_bb",
                            threshold = 1,
                            relationship = "gte",
                            cross = TRUE),
           label = "thresholdexit")


###############
#             #
#  add rules  #
#             #
###############


osInvestAll <- function (data, timestamp, orderqty, ordertype, 
                         orderside, equity, portfolio, symbol, ruletype, ..., initEq) {
  datePos <- format(timestamp,"%Y-%m-%d %H:%M:%OS")

  datePos <- strptime(c(datePos), format = "%Y-%m-%d %H:%M:%OS", tz = 
                        "UTC") + 86400 #for daily data

  updatePortf(Portfolio=portfolio,Symbol=symbol,Dates=paste0(start(data), 
                                                             "/", datePos))
  # After updating portfolio profit, we can extract the Net.Trading.PL earned up to datePos.
  trading_pl <- sum(.getPortfolio(portfolio)$summary$Net.Trading.PL)
  # The total equity in the strategy for this symbol (and this symbol only in isolation always,
  # as this is how quantstrat by default works with applyStrategy)
  equity <- initEq + trading_pl
  ClosePrice <- getPrice(data, prefer = "Close")[datePos]
  UnitSize <- as.numeric((equity / ClosePrice))
  UnitSize1 <- round(UnitSize, digits = 8)
  UnitSize1
}


# add custom entry rule
add.rule(strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "thresholdentry",
                          sigval = TRUE,
                          ordertype = "market",
                          orderside = "long",
                          prefer = "Close",
                          osFUN = osInvestAll),
         type = "enter")

# add custom exit rule
add.rule(strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "thresholdexit",
                          sigval = TRUE,
                          orderqty = "all",
                          ordertype = "market",
                          orderside = "long",
                          prefer = "Close"),
         type = "exit",label="ExitRule",enabled=T)


##################
#                #
#  run strategy  #
#                #
##################

out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st, initEq=initeq)
Laurence_jj
  • 646
  • 1
  • 10
  • 23

1 Answers1

0

I think it is possible to use osFUN=IKTrading::osMaxDollar

Laurence_jj
  • 646
  • 1
  • 10
  • 23