Tips for coding to find the top x% of stocks in an exploration

As above - I have a simple exploration to find the top 7% of stocks in terms of price increase vs the $SPX. However I have been struggling for weeks to try and figure out how to only show the top 7% of stocks.

I've had a look through the forums but can't figure out how to make it work. Any input would be greatly appreciated.

//Calculate % gain in price since a specific date vs SPX

//Get current stock performance
startprice = Ref(C,-60);
endprice = Ref(C,0);
ratiostock = ((endprice-startprice)/startprice)*100;

//Get SPY performance
SetForeign("$SPX");
spy3m = Ref(C,-60);
spycu = Ref(C,0);
ratiospy = ((spycu-spy3m)/spy3m)*100;
RestorePriceArrays();

//Compare the two
score = ratiostock/ratiospy*100;



// Calculate the percentile rank of each stock
PercentRankValue = PercentRank(score,1);

// Select only stocks in the top 7%
Selected = PercentRankValue >= 93;  // Top 7% corresponds to PercentRank >= 93

// Apply the filter
Filter = Selected;

AddColumn(C, "Current Price", 1.2);
AddColumn(startprice, "Stock % Gain", 1.2 );
AddColumn(ratiospy, "S&P 500 % Gain Reference", 1.2 );
AddColumn(score, "Stock %gain vs S&P500", 1.2 );
AddColumn(PercentRankValue, "PercentRank", 1.2);


AddTextColumn( SectorID(Mode=1), "Sector Name", 1.2,colorDefault, colorDefault,90);
AddTextColumn( IndustryID(Mode=1), "Industry Name", 1.2,colorDefault, colorDefault,90);

SetSortColumns( -6 );


//AddColumn(startprice, "startprice", 1.2);
//AddColumn(endprice, "endprice", 1.2);
//AddColumn(ratiostock, "ratiostock", 1.2);

//AddColumn(spy3m, "spy3m", 1.2);
//AddColumn(spycu, "spycu", 1.2);
//AddColumn(ratiospy, "ratiospy", 1.2);

Your question is not very clear. Can you post with a specific example and in which time frame you are calculating the price and in which time frame you expect the AFL to run in.

Apologies. Hopefully you can see my code in my original post but I will explain it below.

My exploration compares a given stocks performance over the last 60 days to the $SPY performance over the last 60 days.

The calculation for the stock and $SPY is = (Closing price today-closing price 60 days ago)/closing price 60 days ago *100

Then, the result for the stock above is divided by the $SPY result and multiplied by 100.

This would normally display the results for all the stocks in my watchlist. However, I want Amibroker to only show the top 7% of stocks in the exploration (ie filter for the strongest moving stocks). I'm not sure how to achieve this last part. The exploration will be run "From-to dates" with the date being one day, ie from 28/1/2025 to 28/1/2205

Thanks a lot for your input

Use StaticvarGenerateRanks.
Endless number of examples in forum already.
First Scan then explore.
No looping code required.

2 Likes