R Markdown

##读取excel:BABA.数据

library(readxl)
df<-read_excel("C:/Users/beibei/Desktop/BABA..xlsx")

##加载数据,第37步需要修改

K <- maxIter <- 200
# Vector theta_0
initDelta <- 6
deltaThresh <- 0.05
PARAM <- PARAMNaught <-
 c(n1 = 0, nFact = 0, nSharpe = 0, shThresh = 0) - initDelta/2
# bounds
minVal <- c(n1 = 1, nFact = 1, nSharpe = 1, shThresh = 0.01)
maxVal <- c(n1 = 250, nFact = 10, nSharpe = 250, shThresh = .99)
# Optimization parameters
alpha <- 1
gamma <- 2
rho <- .5
sigma <- .5
randomInit <- FALSE
np <- 2 ##(此步骤进行修改)

##加载数据,第46步需要修改

OPTIM <- data.frame(matrix(NA, ncol = np + 1, nrow = maxIter * (2 * np + 2)))
o <- 1
SIMPLEX <- data.frame(matrix(NA, ncol = np + 1, nrow = np + 1))
POINTS <- list()
names(SIMPLEX) <- names(OPTIM) <- c(names(POINTS),"obj")  ##(此步骤进行修改)

# Print function for reporting progress in loop
printUpdate <- function(){
 cat("Iteration: ", k, "of", K, "\n")
 cat("\t\t", paste0(strtrim(names(OPTIM), 6), "\t"), "\n")
 cat("Global Best:\t",
 paste0(round(unlist(OPTIM[which.min(OPTIM$obj),]),3), "\t"), "\n")
 cat("Simplex Best:\t",
 paste0(round(unlist(SIMPLEX[which.min(SIMPLEX$obj),]),3), "\t"), "\n")
 cat("Simplex Size:\t",
 paste0(max(round(simplexSize,3)), "\t"), "\n\n\n")
}
 # Initialize SIMPLEX
#定义evaluate函数
evaluate<- function(PARAM, minVal = NA, maxVal = NA, y = 2014,
transform = FALSE, verbose = FALSE,
negative = FALSE, transformOnly = FALSE,
returnData = FALSE, accountParams = NULL)
for( i in 1:(np+1) ) {
 SIMPLEX[i,1:np] <- PARAMNaught + initDelta * as.numeric(1:np == (i-1))
 SIMPLEX[i,np+1] <- evaluate(SIMPLEX[i,1:np], minVal, maxVal, negative = TRUE,
 y = y)
 OPTIM[o,] <- SIMPLEX[i,]
 o <- o + 1
}