2016-08-16 9 views
-1

最大値とNAを置き換える私は値を最適化しようとしていると私はそれが何NA値を置き換えている最適化が

In optimize(my_func, 3:20, tol = 1, maximum = T, comparator = data$changeUP, :NA/Inf replaced by maximum positive value

を言うエラーが出続けますか? NAは私の計算でxxx値ですか?どうしたらいいんだろう?

data(ttrc) 
data<-data.frame(Close=Cl(ttrc),changeUP=ifelse(Cl(ttrc)-Lag(Cl(ttrc))>0,1,0)) 
colnames(data)<-c("Close","changeUP") 
################################################################################### 
xxx<-RSI(Cl(data),n=3) #hardcoded one specific value of MA in order to test the optimization of the cutoff 
xxx<-lag(xxx) 

res<-optimize(my_func,3:20,tol=1,maximum=T,comparator=data$changeUP,calculated_statistic=xxx) 
res$maximum 
res$objective 

my_func<-function(i,comparator,calculated_statistic){ 
    qq<-as.factor(calculated_statistic<i) 
    comparison<-table(data$changeUP==qq,useNA = "no") 
    comparison[2]/(comparison[1]+comparison[2])#calculate success rate for the cutoff 
} 

私の完成したコードはループを使用しています(まだ奇妙なバグがあります)が、これは最終的には最適化でやろうとしています。

data(ttrc) 
data<-data.frame(Close=Cl(ttrc),changeUP=ifelse(Cl(ttrc)-Lag(Cl(ttrc))>0,1,0)) 
colnames(data)<-c("Close","changeUP") 
################################################################################### 
master_rsi<-lapply(3:20,function(j){ #test every RSI period 
    xxx<-RSI(Cl(data),n=j) 
    xxx<-lag(xxx) 
    cat("indicator parameter=",j,"\n") 

    tempdf<-lapply(10:90,function(i){ #test every cutoff point for the values 
    qq<-xxx<i 
    qq<-as.factor(qq) 
    comparison<-table(data$changeUP==qq,useNA = "no") 
    pp<-comparison[2]/(comparison[1]+comparison[2])#calculate success rate for the cutoff 
    cat(pp) 
    pp 
    }) 

    tempdf<-unlist(tempdf) 
    rp<-paste0("MA period: ",j," success rate: ",max(tempdf)," cutoff: ",which.max(tempdf)+9,"\n") 
    cat(rp) 
    rp 
}) 
unlist(master_rsi) 

答えて

0

同じレベル0,1との因子であることがqqdata$changeUPを強制的に役に立つかもしれません:

library(quantmod) 
data(ttrc) 
data<-data.frame(Close=Cl(ttrc),changeUP=ifelse(Cl(ttrc)-Lag(Cl(ttrc))>0,1,0)) 
colnames(data)<-c("Close","changeUP") 
data$changeUP <- factor(data$changeUP, levels=0:1) 
################################################################################### 
fun <- function(j){ #test every RSI period 
    xxx <- RSI(Cl(data),n=j) 
    xxx <- lag(xxx) 
    cat("indicator parameter=",j,"\n") 

    tempdf <- lapply(10:90,function(i){ #test every cutoff point for the values 
     qq <- factor(as.numeric(xxx<i), levels=0:1) 
     comparison <- table(data$changeUP==qq,useNA = "no") 
     pp <- comparison[2]/(comparison[1]+comparison[2])#calculate success rate for the cutoff 
     ##cat(i, pp,"\n") 
     pp 
    }) 

    tempdf <- unlist(tempdf) 
    rp <- paste0("MA period: ",j," success rate: ",max(tempdf)," cutoff: ",which.max(tempdf)+9,"\n") 
    cat(rp,"\n") 
    rp 
} 
master_rsi <- lapply(3:20,fun) 
unlist(master_rsi)