3

#读取数据

library(data.table)
setwd("C:/Users/lenovo/Documents/WeChat Files/wxid_qv9c0kbnp35a22/FileStorage/MsgAttach/69a496a03226e02c9aa496e04ad523e8/File/2022-06")
v <- "BABA"
DATA <- list() 
for(i in v){ 
    suppressWarnings( 
    DATA[[i]] <- fread( paste0(i, ".csv"), sep = ",")) 
    DATA[[i]] <- (DATA[[i]])[ order(DATA[[i]][["Date"]], decreasing = FALSE)] 
}

因先前是code出错,evaluate函数出现了错误,其中有缺少大括号,现已将错误进行修改,改正过来。

# install.packages("lattice")
library(lattice)
# install.packages("zoo")
library(zoo)
evaluate <- function(PARAM, minVal = NA, maxVal = NA, y = 2021,
                     transform = FALSE, verbose = FALSE,
                     negative = FALSE, transformOnly = FALSE,
                     returnData = FALSE, accountParams = NULL){
  
  # Step 1
  # Convert and declare parameters if they exist on unbounded (-inf,inf) domain
  if( transform | transformOnly ){
    PARAM <- minVal +
      (maxVal - minVal) * unlist(lapply( PARAM, function(v) (1 + exp(-v))^(-1) ))
    if( transformOnly ){

    }
  }
 return(PARAM)  
}  ## 修改
  
 
# Declare bounds and step size for optimization
lowerBound <- c(n1 = 5, nFact = 3, nSharpe = 22, shThresh = 0.05)
upperBound <- c(n1 = 80, nFact = 3, nSharpe = 22, shThresh = 0.95)
stepSize <- c(n1 = 5, nFact = 1, nSharpe = 1, shThresh = 0.05)

pnames <- names(stepSize)
np <- length(pnames)

# Declare list of all test points
POINTS <- list()
for( p in pnames ){
  POINTS[[p]] <- seq(lowerBound[[p]], upperBound[[p]], stepSize[[p]])
}

OPTIM <- data.frame(matrix(NA, nrow = prod(unlist(lapply(POINTS, length))),
                           ncol = np + 1))
names(OPTIM)[1:np] <- names(POINTS)
names(OPTIM)[np+1] <- "obj"

# Store all possible combinations of parameters
for( i in 1:np ){
  each <- prod(unlist(lapply(POINTS, length))[-(1:i)])
  times <- prod(unlist(lapply(POINTS, length))[-(i:length(pnames))])
  OPTIM[,i] <- rep(POINTS[[pnames[i]]], each = each, times = times)
}

# Test each row of OPTIM
timeLapse <- proc.time()[3]
for( i in 1:nrow(OPTIM) ){
  OPTIM[i,np+1] <- evaluate(OPTIM[i,1:np], transform = FALSE, y = 2021)
  cat(paste0("##  ", floor( 100 * i / nrow(OPTIM)), "% complete/n"))
  cat(paste0("##  ",
             round( ((proc.time()[3] - timeLapse) * 
                       ((nrow(OPTIM) - i)/ i))/60, 2),
             " minutes remaining/n/n"))
}
library(lattice)
wireframe(obj ~ n1*shThresh, data = OPTIM,
          xlab = "n1", ylab = "shThresh",
          main = "Long-Only MACD Exhaustive Optimization",
          drape = TRUE,
          colorkey = TRUE,
          screen = list(z = 15, x = -60)
)

levelplot(obj ~ n1*shThresh, data = OPTIM,
          xlab = "n1", ylab = "shThresh",
          main = "Long-Only MACD Exhaustive Optimization"
)