# How do I loop through all the stocks and find the 10 stocks with the highest Sharpe ratio using R program?

I am recently doing a project, which I need to apply Sharpe ratio to all the stocks. How do I loop through all the stocks and find the 10 stocks with the highest Sharpe ratio using R program? Thanks a lot!!

• Use function rank on the vector of the Sharpe ratios; then use which(ranks<=10) where ranks is the output of rank. – Richard Hardy Sep 16 '16 at 8:52
• Do you have the data already? If you assign Sharpe ratios to each stock, just sort by the Sharpe ratio and take the top 10? – user59 Sep 16 '16 at 16:49

I would recommend you should avoid using loops in R unless absolutely necessary since iteration is very slow in R. Some newer data classes improve performance, but in general its always best to use a "vectorised" method if available.

You could use either order or rank to get the 10 stocks with the highest Sharpe Ratio.

Lets assume you have the following data in R:

mydata <- as.data.frame( cbind( scrip=letters, sharpe_ratio=seq(from=-0.25,to=1.00,by=0.05) ) )
mydata$sharpe_ratio <- as.numeric( as.character(mydata$sharpe_ratio ) )


Method 1: Sort and then pick up top 10:

mydata[ order(mydata$sharpe_ratio, decreasing =TRUE) ,][1:10,] scrip sharpe_ratio 26 z 1.00 25 y 0.95 24 x 0.90 23 w 0.85 22 v 0.80 21 u 0.75 20 t 0.70 19 s 0.65 18 r 0.60 17 q 0.55  Method 2: Find the rank and pick top 10: sharpe_ranks <- rank( mydata$sharpe_ratio )
mydata[ sharpe_ranks[ sharpe_ranks>(length(sharpe_ranks)-10) ] ,]
scrip sharpe_ratio
17     q         0.55
18     r         0.60
19     s         0.65
20     t         0.70
21     u         0.75
22     v         0.80
23     w         0.85
24     x         0.90
25     y         0.95
26     z         1.00