getKDJ<-function(rt,n){ l=length(rt[["Chg"]]) K=array(0,c(l-n+1)) D=array(0,c(l-n+1)) J=array(0,c(l-n+1)) daycount=0 for(i in n:l){ daycount=daycount+1 nlow=rt[["Low"]][i] nhigh=rt[["High"]][i] for(j in 0:(n-1)){ if(rt[["Low"]][i-j]nhigh) nhigh=rt[["High"]][i-j] } nRSV=100*(rt[["Call"]][i]-nlow)/(nhigh-nlow) if(daycount==1){ K[daycount]=(2/3)*50+(1/3)*nRSV D[daycount]=(2/3)*50+(1/3)*K[daycount] }else{ K[daycount]=(2/3)*K[daycount-1]+(1/3)*nRSV D[daycount]=(2/3)*D[daycount-1]+(1/3)*K[daycount] } J[daycount]=3*D[daycount]-2*K[daycount] } dates=as.Date(rt[["Date"]][n:l]) minvalue=min(min(K),min(D),min(J)) maxvalue=max(max(K),max(D),max(J)) minlab=floor((minvalue-10)/10)*10 maxlab=floor((maxvalue+20)/10)*10 plot(dates,K,type="l",col = "blue",ylab="KDJ",ylim=c(minlab,maxlab),yaxt="n",lwd=2) axis(side=2,at=seq(minlab,maxlab,10),cex.axis=0.8,tck=1) lines(dates,D,type="l",col = "red",lwd=2) lines(dates,J,type="l",col = "orangered4",lwd=2) legend("bottomright",c("K","D","J"), col =c("blue","red","orangered4"),lty=c(1,1,1)) return(list(K,D,J)) } rt=read.table("SM1209.txt", header=TRUE) n=9 KDJ=getKDJ(rt,n) K=KDJ[[1]] D=KDJ[[2]] J=KDJ[[3]]