2016-08-16 76 views
-1

我試圖優化價值,我不斷收到寫着優化取代了NA與最大值

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

什麼NA價值在於它更換一個錯誤? 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

這可能有助於迫使qqdata$changeUP是與同級別0,1因素:

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)