You say, if you don't use the date parameter query takes longer time. It means query takes the data set correctly to get the rows. So, the reason for taking about 5 minutes to process 8000 rows could be the function you are using. Is that function in turn, access much data? If so, you will make 8000 calls to determine the outcome. You may have to rewrite the function or if those values are static per stock, move to a table and join with that table.