R code runs slowly

I try use R to find out which two stocks run very similarly in last 30 days. My database is MySQL. but it runs slowly. I read the records for each stock in a for loop and append it to a data frame. After that i use a double for loop to find out the maximum value of cor() to those data.

library(RMySQL)
library(quantmod)

killDbConnections <- function () {
  all_cons <- dbListConnections(MySQL())
  #print(all_cons)
  for(con in all_cons)
    +  dbDisconnect(con)
  #print(paste(length(all_cons), " connections killed."))
}

killDbConnections()

mydb = dbConnect(MySQL(), user='stockmonitor', password='stockmonitor', dbname='stockmonitor', host='127.0.0.1')

getStocks <- function(stockNo){
  rs=dbSendQuery(mydb, "select distinct date(date) from recordDaily order by date(date) limit 0,30")
  data=fetch(rs, n=-1)
  str=""
  for (i in 1:(nrow(data)-1)){
    if (str==""){
      str=paste0(str, "select '", data[i,], "' as date union")
    }else{
      str=paste0(str, " select '", data[i,], "' union")
    }
  }
  str=paste0(str, " select '", data[nrow(data),], "'")
  str=paste0("select a.date, IFNULL(b.price, -1) from (\n", str, ") as a
             left join 
             (select * from recordDaily where stockNo='",stockNo,"') as b 
             on a.date=date(b.date)")
  
  rs=dbSendQuery(mydb, str)
  data=fetch(rs, n=-1)
  return(data)
}

appendStock <- function(df, stockNo){
  stockData=getStocks(stockNo)
  df=data.frame(rbind(as.matrix(df), as.matrix(t(c(stockNo,stockData[,2])))))
  return(df)
}

#colClasses = c("character", rep("numeric", length(data[,1])))

rs=dbSendQuery(mydb, "select distinct date(date) from recordDaily order by date(date) limit 0,30")
data=fetch(rs, n=-1)
col.names = c("Stock", data[,1])
df <- read.table(text = "", col.names = col.names)

rs=dbSendQuery(mydb, "select distinct stockNo from recordDaily order by stockNo")
data=fetch(rs, n=-1)
for (i in 1:nrow(data)){
  print(paste0('appending ', data[i,]))
  df=appendStock(df, data[i,])
}

maxCor=-999999
name1=""
name2=""
for (x in 1:length(df[,1])){
  for (y in 1:length(df[,1])){
    if (x!=y){
      c=cor(as.numeric(as.matrix(df[x,-1])), as.numeric(as.matrix(df[y,-1])))
      print(paste0("cor=",c, "=", df[x,1],",",df[y,1]))
      if (abs(c)>maxCor){
        maxCor=abs(c)
        name1=df[x,1]
        name2=df[y,1]
        print(paste0(name1,", ", name2))
      }
    }
  }
}

print(paste0(cor,"=",name1,",",name2))

read count : 5