我用穷举法计算的时候没有报错,但是带进rbga函数中总这个报错
代码就是一个求解最优交易策略的,是均线的交易策略,通过找金叉死叉来实现交易
是对长短均线进行的遗传算法优化,其实穷举也可以,就是想试试rbga函数怎么用
代码附在下面,我找了好久也不知道为什么报这个错
#交易策略代码
trading<-function(MAlong,MAshort,m){
output=NA
for(i in 35:m){
if((MAshort
>MAlong)&&(MAshort[i-1]<MAlong[i-1])&&(MAshort>MAshort[i-1]))
{output="金叉"}
else if((MAshort<MAlong)&&(MAshort[i-1]>MAlong[i-1]))
{output="死叉"}
else{output="非"}
}
return(output)
}
#遗传算法代码
getAdjust <- function(x)
{
#求均值
MAshort <-ma(close,m,n=x[1])
MAlong <-ma(close,m,n=x[2])
#交易策略
output=trading(MAlong,MAshort,m)
buy=point(output)$buy
sell=point(output)$sell
head(cbind(buy,sell))
#收益率
cost=0.0001
return=profit(buy,sell,cost)
sum(return)
return(-sum(return))
}
monitor <- function(rbga0)
{
#打印种群中的第一个个体的值population[1,]
print(rbga0$population[1,])
}
rbgaObj <- rbga(stringMin = c(5,5),
stringMax = c(30,30),
popSize = 50,
iters = 1000,
mutationChance = 0.01,
monitorFunc = monitor,
evalFunc = getAdjust,
verbose = TRUE)