HomeKnowledge Base

Separate ranks for categories that can be used in backtesting

When we want to develop a trading system, which enters only N top-scored symbols from each of the sectors, industries or other sub-groups of symbols ranked separately, we should build appropriate ranks for each of such categories. This can be done with ranking functionalities provided by StaticVarGenerateRanks function.

The formula presented below iterates though the list of symbols included in the test, then calculates the scores used for ranking and writes them into static variables. The static variables names are based on category number (sectors in this example) and that allows to create separate ranks for each sector.

// watchlist should contain all symbols included in the test
wlnum GetOption"FilterIncludeWatchlist" );
List = 
CategoryGetSymbolscategoryWatchlistwlnum ) ;

Status"stocknum" ) == )
// cleanup variables created in previous runs (if any)
StaticVarRemove"rank*" );
StaticVarRemove"values*" );
categoryList ",";

0; ( Symbol StrExtract( List, ) )  != "";  n++ )
SetForeignsymbol );

// use sectors for ranking
category sectorID();

// add sector to the list
if( ! StrFindcategoryList"," category "," ) ) categoryList += NumToStrcategory1) + ",";

// write our ranking criteria to a variable
        // in this example we will use 10-bar rate-of-change
values RocClose10 );

// write ranked values to a static variable
StaticVarSet"values" category "_" symbolvalues );


// generate separate ranks for each category from the list
for( 1; ( category StrExtractcategoryList) ) != ""i++ )
StaticVarGenerateRanks"rank""values" category "_"01224 );

category sectorID();
symbol Name();

values StaticVarGet"values" category "_" symbol );
rank StaticVarGet"rank" "values" category "_" symbol );

// exploration code for verification
AddColumnvalues"values" );
AddColumnrank"rank" );
AddTextColumnSectorID), "Sector" );
AddColumnSectorID(), "Sector No");
Filter rank <= 2;

Status"Action" ) == actionExplore SetSortColumns25);

// sample backtesting rules
SetBacktestModebacktestRotational );
score IIfrank <= 2values);
// switch symbols at the beginning of the month only
PositionScore IIf!= Refm, -), scorescoreNoRotate );
SetPositionSize1spsPercentOfEquity );

Our test should be applied to a watchlist, which contains all symbols we want to include in our ranking code:

Watch list selection

Running the exploration will show two top-ranked symbols for each of the sectors:


We can also change Filter variable definition to

Filter 1;

and show all ranked symbols instead.

Such ranking information can be used in backtest and sample rules included at the end of the code use rank information to allow only two top-scored symbols to be traded.

Comments are closed.