Я просматриваю следующие PDF-слайды (в настоящее время 24/42):
http://www.r-programming.org/files/WFA.pdf
Первоначально я видел ошибки, связанные с параллельной обработкой ( Я использую Ubuntu), но когда я закомментирую параллельный код, я сталкиваюсь со следующей ошибкой:
Ошибка в walk.forward (стратегии.st = strat.st, paramset.label = "BBOPT" ,: obj.fun c () вернул пустой результат Кроме того: Предупреждение: в max (x): нет не пропущенных аргументов для max; возвращается -Inf
Я проверил код и, похоже, не может найти ошибку. Я знаю, что код с 2014 года, и с тех пор были сделаны некоторые обновления для пакета quantstrat
. Я не хочу запускать код с использованием параллельной обработки, моя цель - просто получить код работает.
Код, который я скопировал со слайдов:
library(quantstrat)
#library(xtsExtra)
stock.st = c("USO")
currency("USD")
stock(stock.st, currency = "USD", multiplier = 1)
Sys.setenc(TZ = "UTC")
initDate = "2006-12-31"
startDate = "2007-01-01"
endDate = "2013-12-31"
initEq = 1000000
tradeSize = initEq / 10
getSymbols(
stock.st,
from = startDate,
to = endDate
)
myTheme <- chart_theme()
myTheme$col$dn.col <- "ligthblue"
myTheme$col$dn.border <- "lightgray"
myTheme$col$up.border <- "lightgray"
chart_Series(
Ad(get(stock.st)),
name = stock.st,
theme = myTheme
)
# order sizing function
osFixedDollar <- function(timestamp, orderqty, portfolio, symbol, ruletype){
pos = getPosQty(portfolio, symbol, timestamp)
if(isTRUE(all.equal(pos, 0))){
ClosePrice = as.numeric(Cl(mktdata[timestamp, ]))
orderqty = sign(orderqty) * round(tradeSize / ClosePrice, -2)
} else {
orderqty = 0
}
return(orderqty)
}
lineChart(USO["2010"])
addBBands(n = 20, sd = 2)
# define indicators and signals
strat.st <- "bbands"
rm.strat(strat.st)
strategy(strat.st, store = TRUE)
add.indicator(
strategy = strat.st,
name = "BBands",
arguments = list(HLC = quote(HLC(mktdata)), maType = "SMA"),
label = "BBands"
)
# create a signal when the close > upper BBand (only at the first cross over)
add.signal(
strategy = strat.st,
name = "sigCrossover",
arguments = list(columns = c("Close", "up"), relationship = "gt"),
label = "Cl.gt.UpperBand"
)
# create a signal when the close is < the lower BBand (only at the first cross over)
add.signal(
strategy = strat.st,
name = "sigCrossover",
arguments = list(columns = c("Close", "dn"), relationship = "lt"),
label = "Cl.lt.LowerBand"
)
add.signal(
strategy = strat.st,
name = "sigCrossover",
arguments = list(columns = c("High", "Low", "mavg"), relationship = "op"), # opposite side
label = "Cross.Mid"
)
# Define the rules
add.rule(
strategy = strat.st,
name = "ruleSignal",
arguments = list(
sigcol = "Cl.gt.UpperBand", # enter a short when we are above the upper BBand
sigval = TRUE,
ORDERTQY = -100,
ORDERTYPE = "market",
orderside = NULL,
threshold = NULL,
osFUN = osFixedDollar,
orderset = "ocoshort" # short side
),
type = "enter",
label = "SE"
)
add.rule(
strategy = strat.st,
name = "ruleSignal",
arguments = list(
sigcol = "Cl.lt.LowerBand", # enter a long when we are below the lower BBand
sigval = TRUE,
orderqty = 100,
ordertype = "market",
orderside = NULL,
threshold = NULL,
osFUN = osFixedDollar,
orderset = "ocolong"# long side
),
type = "enter",
label = "LE"
)
add.rule(
strategy = strat.st,
name = "ruleSignal",
arguments = list(
sigcol = "Cross.Mid",
sigval = TRUE,
orderqty = "all",
ordertype = "market",
orderside = NULL,
threshold = NULL
),
type = "exit"
)
# Define distributions
add.distribution(
strategy = strat.st,
paramset.label = "BBOPT",
component.type = "indicator",
component.label = "BBands",
variable = list(n = seq(10, 30, by = 5)),
label = "n" # n number of periods
)
add.distribution(
strategy = strat.st,
paramset.label = "BBOPT",
component.type = "indicator",
component.label = "BBands",
variable = list(sd = seq(1, 3, by = 0.5)),
label = "sd" # sd to test in each n periods
)
# Walk forward analysis
# This is a wrapper for apply.paramset() and applyStrategy()
# args(walk.forward)
# parallel processing
# if(Sys.info()["sysname"] == "Windows"){
# library(doParallel)
# } else {
# library(doMC)
# registerDoMC(cores = detectCores())
# }
rm.strat("opt")
initPortf(
name = "opt",
stock.st,
initDate = initDate
)
initAcct(
name = "opt",
portfolios = "opt",
initDate = initDate,
initEq = initEq
)
initOrders(
portfolio = "opt",
initDate = initDate
)
?walk.forward
results <- walk.forward(
strategy.st = strat.st,
paramset.label = "BBOPT",
portfolio.st = "opt",
account.st = "opt",
period = "years", # unit of days, months or years etc.
k.training = 4, # number of training periods
k.testing = 1, # number of test periods
nsamples = 0, # number of sample param.combos to draw - 0 means all samples
obj.func = function(x) { which(x == max(x)) },
#obj.fun = NULL, # user provided function retuning the best para.combo
#obj.args = NULL, # user provided argument to obj.func
audit.prefix = "wfa", # prefix to generate filenames for storage of audit data
anchored = FALSE, # whether to a fixed start or not for the trainijng window
#include.insamples = NULL, # will run a full backtest for each param.combo in the paramset
verbose = TRUE
)