Create Custom Index (from specified tickers)

I am trying to create a custom index (weighted by trading value) from says 10 tickers which are stored in a watchlist. The code below is just the example of calculation total summation of trading value of those tickers in a watchlist.

The range of index I want to create is 5 years, however some tickers has just started trading 1 years ago, hence the code below can generate only 1 year data. I want to ignore the ticker that doesn't have data ( equal to zero) and produce the summation of trading value for 5 years. Can you please advise if there is any other way ?

count = 0;
s=0;

procedure CreateIndexesValue( ) 
{
  global List;
  local Symbol,n;
  wlnum = 0; 
  x=0;
  count =0;
  List = CategoryGetSymbols( categoryWatchlist, wlnum ) ;
     
  for( n = 0; ( Symbol = StrExtract( List, n ) )  != "";  n++ )
    {
		count = count+1;
        // THIS IS BAD CODE DO NOT USE IT!!!
       // NEVER EVER CALL SetForeign inside loop
        SetForeign( Symbol ); 
        x= C*V;
        s=s+x;
        RestorePriceArrays( True );
    }
}

CreateIndexesValue();
resultS = s;

Filter = resultS;
AddColumn(resultS,"Value",1.1);

You should use non loop code

1 Like

Correct code for version 6.40. Press "RUN SEQUENCE" to use it.

// the statement below defines sequence of actions 
#pragma sequence(scan,explore) 

Version( 6.40 ); // requires version 6.40.4


if( Status("action") == actionScan ) 
{ 
   AddToComposite( C * V / 100000 , "~MyIndex", "X" ); 
   AddToComposite( 1, "~MyIndex", "V");
   _exit(); // quick exit in scan mode 
} 

CustomCalculation = Foreign( "~MyIndex", "C" );
SymbolCount = Foreign( "~MyIndex", "V" );
CustomIndex = CustomCalculation / SymbolCount; // take the average to create your custom index

///////////////
// Explore
///////////////
Filter = 1;
AddColumn( SymbolCount, "Number of Stocks", 1.0 );
AddColumn( CustomCalculation, "Total Calculation", 1.2 );
AddColumn( CustomIndex, "Custom Index", 1.2 );

Note that this function uses AddToComposite, not static variables, as visible composites in forms of special symbols that are present in the "Symbols" list (here composite is present in form of ~MyIndex ticker) are easier to understand, display and handle for beginners than somewhat "hidden" static variables, that you don't easily see.

5 Likes

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.