我正在基于 blogger 在 R 中进行简单的回测,使用%do%代码运行良好但非常慢。当我尝试使用%dopar%时,总是出现以下错误: { 中的错误:任务 1 失败 -“找不到对象 'COKE'” 我发现它可能来自 .blotter 环境,但我无法解决。请帮助,如何解决这种类型的错误。下面是我的代码。谢谢!
require(blotter)
require(foreach)
require(doSNOW)
require(quantstrat)
.blotter <- new.env()
initdate <- '2012-01-01'
startdate <- '2012-01-02'
enddate <- '2020-12-31'
mystock <- c('COKE')
getSymbols(Symbols = mystock,from=startdate,to=enddate,index.class='POSIXct')
registerDoSNOW(makeCluster(2,'SOCK'))
for (symbol in mystock)
{
sym <- get(symbol)
# sym <- to.weekly(sym,indexAt = 'endof',drop.time = FALSE)
sym$SMA10 <- SMA(Cl(sym),n = 20)
sym$Daily_return <- Delt(Cl(sym))
colnames(sym) <- gsub(pattern = 'sym',replacement = symbol,x = colnames(sym))
assign(symbol,sym)
remove(sym)
}
nr <- nrow(COKE)
currency("USD")
stock("HPG",currency="USD",multiplier=1)
mystrat <- 'test'
initEq <- 10000
sym <- COKE
initPortf(name = mystrat,symbols = mystock,initDate = initdate)
initAcct(name = mystrat,portfolios = mystrat,initDate = initdate,initEq = initEq)
backtest <- function (i)
{
symbol <- 'COKE'
currentdate <- time(sym)[i]
# print(currentdate)
# assign(symbol,sym)
if (is.account(mystrat) == FALSE)
{
initPortf(name = mystrat,symbols = mystock)
initAcct(name = mystrat,portfolios = mystrat,initEq = initEq,initDate = initdate)
}
else
{
updatePortf(Portfolio = mystrat,Dates = currentdate)
updateAcct(name = mystrat,Dates = currentdate)
}
Posn <- getPosQty(Portfolio = mystrat,Symbol = symbol,Date = currentdate)
Daily_return <- as.numeric(sym[i,'Daily_return'])
if (!is.na(Daily_return))
{
if (Posn == 0)
{
if (Daily_return < -0.04)
{
Closeprice <- as.numeric(Cl(sym)[i])
sma10 <- as.numeric(sym[i,'SMA10'])
ordersize <- 50
sell_date <- time(sym)[i+10]
Close_sell <- as.numeric(Cl(sym)[i+10])
addTxn(Portfolio = mystrat,Symbol = symbol,TxnDate = currentdate,TxnQty = ordersize,TxnPrice = Closeprice,TxnFees = 0)
addTxn(Portfolio = mystrat,Symbol = symbol,TxnDate = sell_date,TxnQty = -ordersize,TxnPrice = Close_sell,TxnFees = 0)
} }
} }
foreach(i = 1:(nr-10),.noexport = '.blotter',.packages = c('blotter')) %dopar% {
backtest(i=i)
}