在quantstrat包中,我找到了applyRule函數緩慢的主要元兇之一,並想知道是否有更高效的編寫while循環。任何反饋都會有幫助。對於任何經驗包裝這部分並行R.雖然循環R量子代碼 - 如何使其更快?
作爲一個選項申請將工作,而不是?還是應該將這部分重新寫入新的函數,如ruleProc和nextIndex?我也在研究Rcpp,但這可能是一個streach。任何幫助和建設性的意見非常感謝?
while (curIndex) {
timestamp = Dates[curIndex]
if (isTRUE(hold) & holdtill < timestamp) {
hold = FALSE
holdtill = NULL
}
types <- sort(factor(names(strategy$rules), levels = c("pre",
"risk", "order", "rebalance", "exit", "enter", "entry",
"post")))
for (type in types) {
switch(type, pre = {
if (length(strategy$rules[[type]]) >= 1) {
ruleProc(strategy$rules$pre, timestamp = timestamp,
path.dep = path.dep, mktdata = mktdata, portfolio = portfolio,
symbol = symbol, ruletype = type, mktinstr = mktinstr)
}
}, risk = {
if (length(strategy$rules$risk) >= 1) {
ruleProc(strategy$rules$risk, timestamp = timestamp,
path.dep = path.dep, mktdata = mktdata, portfolio = portfolio,
symbol = symbol, ruletype = type, mktinstr = mktinstr)
}
}, order = {
if (length(strategy$rules[[type]]) >= 1) {
ruleProc(strategy$rules[[type]], timestamp = timestamp,
path.dep = path.dep, mktdata = mktdata, portfolio = portfolio,
symbol = symbol, ruletype = type, mktinstr = mktinstr,)
} else {
if (isTRUE(path.dep)) {
timespan <- paste("::", timestamp, sep = "")
} else timespan = NULL
ruleOrderProc(portfolio = portfolio, symbol = symbol,
mktdata = mktdata, timespan = timespan)
}
}, rebalance = , exit = , enter = , entry = {
if (isTRUE(hold)) next()
if (type == "exit") {
if (getPosQty(Portfolio = portfolio, Symbol = symbol,
Date = timestamp) == 0) next()
}
if (length(strategy$rules[[type]]) >= 1) {
ruleProc(strategy$rules[[type]], timestamp = timestamp,
path.dep = path.dep, mktdata = mktdata, portfolio = portfolio,
symbol = symbol, ruletype = type, mktinstr = mktinstr)
}
if (isTRUE(path.dep) && length(getOrders(portfolio = portfolio,
symbol = symbol, status = "open", timespan = timestamp,
which.i = TRUE))) {
}
}, post = {
if (length(strategy$rules$post) >= 1) {
ruleProc(strategy$rules$post, timestamp = timestamp,
path.dep = path.dep, mktdata = mktdata, portfolio = portfolio,
symbol = symbol, ruletype = type, mktinstr = mktinstr)
}
})
}
if (isTRUE(path.dep))
curIndex <- nextIndex(curIndex)
else curIndex = FALSE
}
我懷疑問題是固有的'while',但'while'內無論發生什麼情況。你的代碼似乎沒有做任何事情 - 沒有賦值或返回值。所以你必須運行這個,因爲'ruleProc'的副作用。如果其中一個副作用是你在其他地方賦值,我會從重構開始。根據我的經驗,在結果列表中使用'lapply'和'do.call'通常比使用'[<-''選擇性分配更快。 – Andrie
如果您發佈了每個提供的每個基礎數據結構的玩具示例,那麼我認爲'for'可以是矢量化的。而且,像nextIndex和ruleProc這樣的函數也需要被顯示。只有在這之後,有人才能對「while」循環做出很好的評估。 – John
好的,只是查找了這個代碼...嘗試先獲得ruleProc矢量化。事實上,如果'ruleProc'是這個代碼非常慢的例子,那麼你可以輕鬆地進行大幅加速,幾乎沒有任何想法。通過'ruleProc'並把所有的東西都從包含整個函數的巨大'for'循環中移出。很多。如果你不能自己做那部分,然後張貼它進行矢量化。但先行動吧。 – John