Only different sectors

Hi to all,
Anybody can help me to code in AFL to pick up only name of different sectors?
Thanks very much in advance.
Maury

I am not certain of what you are exactly looking for. There are some possible solutions for you at these links,

https://www.amibroker.com/guide/afl/sectorid.html
https://www.amibroker.com/guide/afl/gicsid.html
https://www.amibroker.com/guide/afl/industryid.html

Example Exploration of their outputs run on a watch list containing the Dow Jones Industrials,

Filter = 1;
AddColumn(SectorID(), "Sector number", 1.0);
AddTextColumn( SectorID( 1 ), "Sector name" );
AddTextColumn( GicsID( 0 ), "Gics Code");
AddTextColumn( GicsID( 1 ), "Gics Name");
AddColumn(IndustryID( 0 ), "Industry ID", 1.0);
AddTextColumn( IndustryID( 1 ), "Industry name" );

4 Likes

Larry,Thanks for helping!

What I need, I figureout just know … . I need to rank my stocks from highest to lowest, then pick up20 stocks with highest rank and different sectors.

Thank you for help!Maury

Hi,
I want to write a code for correlations between sectors… . Can you help me?
Thank you for help, Maury

Hi Larry,
How to write the code to get tickers for these sectors or industry?
Thank you very much for helping!!!
Maury

@maury314 you may find what you need in this Knowledge Base article,

http://www.amibroker.com/kb/2016/01/30/separate-ranks-for-categories-that-can-be-used-in-backtesting/

Also worth reading through the discussion on this thread on the old forum,
https://groups.yahoo.com/neo/groups/amibroker/conversations/messages/197096

2 Likes

I’m also trying to achieve what the title of this thread describes.

In a backtest, I want to limit the number of open positions in any one sector.

This is so I don’t end up with more than 1 open positions in the ‘Materials’ sector, for example.

This is all I have so far but it’s not going to work.

SectorLimit = SectorID() != SectorID();

Sorry if this has already bee answered but I haven’t found it or it maybe located in the old forums which I don’t have access to.

2 Likes

This solution form @marwood looks like it may contain a method that I can adapt to fit my needs. Hope it also helps others like me who stumble upon this thread.

2 Likes

try this

it buys the weakest stocks from the strongest industries

#include_once "Formulas\Norgate Data\Norgate Data Functions.afl"


SetTradeDelays(0,0,0,0); 
SetOption ("allowsamebarexit",False); 
SetOption ("MaxOpenPositions" , 20);
SetOption("initialequity",100000); 
OnSecondLastBarOfDelistedSecurity = BarIndex() == (LastValue(BarIndex()) -1) AND !IsNull(GetFnData("DelistingDate"));
OnLastTwoBarsOfDelistedSecurity = BarIndex() >= (LastValue(BarIndex()) -1) AND !IsNull(GetFnData("DelistingDate"));
inindex = NorgateIndexConstituentTimeSeries("$SPX"); 
liquid = MA(V,20) > 1000000;
index = Foreign("$SPX","C"); 
indexup = index > MA(index,200); 



sectorlist = "$SPXE,$SPXM,$SPXI,$SPXD,$SPXS,$SPXA,$SPXF,$SPXT,$SPXL,$SPXU";
wlnum = GetOption( "FilterIncludeWatchlist" );
List = CategoryGetSymbols( categoryWatchlist, wlnum ) ;




if( Status( "stocknum" ) == 0 )
{

    StaticVarRemove( "sector*" );
      StaticVarRemove( "constituentrank*" );
    StaticVarRemove( "values*" );
 
     categoryList = ",";

// sector ranking
    for( i = 0; ( sec = StrExtract( sectorlist, i ) ) != ""; i++ )
    {
        SetForeign( sec );
        sectormom = ROC( C, 90 );
        RestorePriceArrays();
        StaticVarSet( "sectormom" + sec, sectormom );

    }
    StaticVarGenerateRanks( "sectorrank", "sectormom", 0, 1224 );

// top or bottom members of each sector
	    
     for( m = 0; ( Symbol = StrExtract( List, m ) )  != "";  m++ )
    {
        SetForeign( symbol );

        // use sectors for ranking
        category = StrLeft(GicsID( 0 ), 2);
        

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

       
        Values = ROC(C,90)*-1;

        RestorePriceArrays();

        
        StaticVarSet( "values" + category + "_" + symbol, values );

    }

    // generate separate ranks for each category from the list
    for( m = 1; ( category = StrExtract( categoryList, m ) ) != ""; m++ )
    {
        StaticVarGenerateRanks( "Constituentrank", "values" + category + "_", 0, 1224 );
    }
}



StockSector = StrLeft(GicsID( 0 ), 2);
sec = "";


if( stocksector == "10" )
    sec = "$SPXE";

if( stocksector == "15" )
    sec = "$SPXM";

if( stocksector == "20" )
    sec = "$SPXI";

if( stocksector == "25" )
    sec = "$SPXD";

if( stocksector == "30" )
    sec = "$SPXS";

if( stocksector == "35" )
    sec = "$SPXA";

if( stocksector == "40" )
    sec = "$SPXF";

if( stocksector == "45" )
    sec = "$SPXT";

if( stocksector == "50" )
    sec = "$SPXL";

if( stocksector == "55" )
    sec = "$SPXU";
    
    





sym = Name();
category = StrLeft(GicsID( 0 ), 2);

sectorrank = StaticVarGet( "sectorranksectormom" + sec );
sectormom = StaticVarGet( "sectormom" + sec );
// filtering

AddTextColumn(StockSector, "StockSector");
AddTextColumn(sec, "sec");
AddColumn( sectorrank, "Sector Rank", 1 );
AddColumn( sectormom, "Sector Mom", 1.2 );



// top tickers from individual sectors
values = StaticVarGet( "values" + category + "_" + sym );
rank = StaticVarGet( "Constituentrank" + "values" + category + "_" + sym );

AddColumn( values, "values" );
AddColumn( rank, "Constituentrank" );
AddTextColumn( GicsID( 0 ), "Sector" );
AddTextColumn( GicsID( 1 ), "Sector Name", 1 );
AddTextColumn(IcbID(1), "Industry Sector", 1);
Soldoff = RSI(14) < 20;
Overbought = RSI(14) > 80;

AddColumn(RSI(14),"RSI14",1.0,IIf(soldoff,colorred,IIf(overbought,colorGreen,colorDefault)),colorDefault,45);


tickerrank = 10;//Optimize("ticker rank",10,2,10,1);
sectorrnk = 5;//Optimize("sector rank",5,1,6,1);
MAXsectorrank = sectorrnk;
Sectorpassed = sectorrank <= MAXsectorrank;
worststocks = rank <= tickerrank;

// BACKTESTING

// postion sizes
SL =  6.5;//Optimize("Stop Loss",6.5,3.5,7,0.5);
TP = 6.5;//Optimize("Profit ATR",6.5,3,8,0.5);
StopAmount = SL * ATR(14);
Winamount = TP * ATR(14); 

// risk % of entire equity on single trade
PositionRisk = 1;

// position size calculation


PctSize =  PositionRisk * buyprice / StopAmount;
SetPositionSize( Min(pctsize,20), spspercentofequity );

// risk 2% of entire equity on single trade
//PositionRisk = 2;

// position size calculation
//limitpercent = 0.9925;
//BuyLimitPrice = Ref( l, -1) * limitpercent;

//PctSize =  PositionRisk * buylimitprice / StopAmount;
//SetPositionSize( Min(pctsize,20), spspercentofequity );



buysetup = liquid AND inindex AND NOT OnSecondLastBarOfDelistedSecurity AND sectorpassed AND worststocks AND C>1 
;

Buy = Ref( BuySetup, -1);

// now we check if limit was hit
//Buy = Buy AND L < BuyLimitPrice;

// if Open price is below the limit, then we use Open for entry
//BuyPrice = Min( Open, BuyLimitPrice );




Sell =  OnSecondLastBarOfDelistedSecurity OR bearin;

ApplyStop( 2, 2, StopAmount, 1 );
ApplyStop( 1, 2, winAmount, 1 );
positionscore = 	1000 - RSI(14);

//PS = Optimize("number of tests",1,1,1000,1);
//PositionScore = Random() * PS;


Limitorder = 1;
atrmulti = 6.5;
currentATR = ATR(14);
//RISK PER TRADE//
RiskPT = 963; //Change to your personal amount of risk per trade//
AddColumn(C,"Close Price",1.2);
AddColumn(RiskPT/(atrmulti * currentATR),"NumSharesToBuy"); 
AddColumn(6.5*currentATR,"Trailing Stop",1.2);
AddColumn(6.5*currentATR+C,"Target Price",1.2);


Filter = buysetup; 





6 Likes

Thanks for the post. I miss the init of bearin.

1 Like

bearing is an indicator of what you define as a bear market in the index you are using