Quantstrat инвестирует все акции в позиции - PullRequest
0 голосов
/ 29 января 2020

Я пытаюсь заставить работать quantstrat, вкладывая в портфель часть портфеля (100% или 20%), а не фиксированное количество ордера (то есть 10 акций).

Я пытался адаптировать функцию ордера из ( Quantstrat: функция ордера ), но мой код выдает ошибки при работе на полпути:

[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

Мой код выглядит так:

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

1 Ответ

0 голосов
/ 30 января 2020

думаю можно использовать osFUN=IKTrading::osMaxDollar

...