Bullish/Bearish Outlook - Stocks in an Index above EMA 200

I am trying to find out how much Average % Change happened to an index of stocks above EMA 200 on Daily and i have written code (below). The whole Idea is to check the percentage of bullishness and bearishness at a particular point of time. I am currently using the below process (with the AFL code below)

  1. Analysis select Index (like NIFTY 500) as watchlist. This Watchlist must be precreated with the stocks list
  2. In the setting make periodicity as Daily
  3. Select a date and Explore.
  4. Put the result into EXCEL and check the average of "Percentage Change" Column. This is will indicate the bullish/bearish nature of the Index Stocks on that particular day.

But I need to do this for each day which is a little time taking process. I tried AddToComposite but in the below example we are not essentially backtesting and it does not work

Can anyone suggest a better way so that i can get a graph kind of in a date range.

AFL CODE:
emaCrossValue = valuewhen( cross( close, ema(close,200) ) ,C, 1);
deltaAmount = C - emaCrossValue;
percentageChange = (deltaAmount/emaCrossValue)*100;
Buy = 1;
Filter = Buy;
AddColumn(percentageChange, "Percentage Change", 1.2,colorDefault);

@yrk,
If you have searched the forum then you know the forum has rules. C'mon, man, at least make an effort...
Please follow this advice: How to ask a good question

Hi,

I actually searched a lot on amibroker forum and google as well but i could not find the average part and if it can be put to a chart. Maybe my search text was not proper. If possible can you please help or redirect to that thread? Please bear with me since i started using Ami for around half an Year now and i am in the learning mode.

As per the forum rules i did follow the below:
Make your question clear and provide necessary information
Post the code that you wrote
Give us all the background Information and explain the GOAL you want to accomplish
Show your own effort

I actually did a good amount of effort and have an Analysis of the major TOPs and BOTTOMs in the last 20 years for the above requirement of mine (I pasted below). But as i said i found this a time consuming effort wanted to check if any better ways.

image

Two words: code tags.

@YRK: perhaps this thread will get you started on how to count the index members that have met a particular condition: Average ATR values for stocks in an index. I searched on "count index".

However, unless you have a data provider that provides historical index constituency data (as Norgate does for US and Australian stocks), then your results are going to be affected by look-ahead bias. In other words, if you create a watchlist of today's NIFTY 500 members and then do your analysis starting at some date in the past, then you have two problems:

  1. Some stocks that were members of the NIFTY 500 in the past will not be in your watchlist because they are no longer part of the NIFTY 500.

  2. Some stocks that were not members of the NIFTY 500 in the past will be in your watchlist because they have been added to the index more recently.

1 Like

That code by @portfoliobuilder is incorrect as it uses StaticVarAdd within loop.
You do not need loop to create average and StaticVarAdd shouldn't be use within loop.

Here is correction without using looping.

Usage:
Select Filter -> Watchlist in AA window,
Check Pad&align and choose reference symbol
Then 1st run Scan and then run Exploration

// Building a composite ATR reading for a WL using StaticVarAdd 
// Original one (don't use StaticVar that way)
// https://forum.amibroker.com/t/average-atr-values-for-stocks-in-an-index/11006/2
// Corrected code at
// https://forum.amibroker.com/t/bullish-bearish-outlook-stocks-in-an-index-above-ema-200/26709/6
// Usage:
// Select Filter -> Watchlist in AA window, 
// Check Pad&align and choose reference symbol
// Then 1st run Scan and then run Exploration
wlnum = GetOption( "FilterIncludeWatchlist" );
List = CategoryGetSymbols( categoryWatchlist, wlnum );
ATRVal = ATR( 30 );

if ( Status( "action" ) == actionScan ) {
	if ( Status( "stocknum" ) == 0 )	{		
		// cleanup variables created in previous runs
		StaticVarRemove( "~ATRtotal*" );
	}
	// prevent accidentely applying to "All symbols"
	if ( StrFind(","+list+",",","+Name()+",") ) 
		StaticVarAdd( "~ATRtotal", ATRVal );
}

svATRtotal= StaticVarGet( "~ATRtotal" );
svSymbolCount = StrCount(list, ",")+1;
AveATRofIndexConstituents = svATRtotal/svSymbolCount;

///////////////////////////////////////////////////
// Explore, let's display the whole WL and confirm
///////////////////////////////////////////////////
Filter = NOT IsNull(svATRtotal);
AddColumn(ATRVal, "ATR(30)");
AddColumn(svATRtotal , "svATRtotal", 1.2 );
AddColumn(svSymbolCount, "Total Number of Stocks", 1.0 );
AddColumn(AveATRofIndexConstituents , "AveATRofIndexConstituents ", 1.2 );


///////////////
// Chart
///////////////
Plot( AveATRofIndexConstituents, "AveATRofIndexConstituents", colorAqua, styleThick );
2 Likes

That same thread had several responses from you, @fxshrat, and I assume the OP will read the entire thing. The point was to show @YRK that there are indeed posts in the forum that show how to generate metrics/composites from all the members of a watchlist.

1 Like

And your point is what...?
I did not comment on your post but I commented on the code I linked to.
People may be misguided to use improper code (since it is marked as solution on top of that).
You didn't point out the mistakes despite being obvious ones, AFAICS. That's why I did.

Thanks @mradtke
Thanks @fxshrat

This helps a me in guiding me to the correct path. I read the codes and understood the concept. I will do the coding for my requirement and get back.

@fxshrat there is slight but important difference between incorrect and inefficient code. The code you pointed out earlier is inefficient, but it is not incorrect in strictest meaning of this word. Incorrect code would produce incorrect results. Inefficient code produces correct results but in inefficient way.

5 Likes

@mradtke Yes look ahead bias exists for the data i am using. I knew this was there but was not aware there's a BIAS word already coined :). I do check the NIFTY 500 Stocks on quarterly basis and add/modify the list but yes back testing results will not be accurate. FYI.. I use weekly and daily charts (since i also do a Job) and do positional investing/trading and currently using Amiquote PLUS data extraction from Python (to check few more parameters)

Any members in this forum aware if there is a data provider like Norgate for India stocks that handles historical index constituency data?

I have tried and followed the procedure, only the result is still: Notice No symbols matched Apply to / filtering criteria. Thanks

Hi All,

Below is the final code for my requirement. I reused @fxshrat 's code. Thanks @fxshrat

//Reused @fxshrat's code originally developed for composite ATR
// Building a composite % increase from 200 EMA of Stocks in an Index
//e.g. In Amibroker Analysis select NIFTY 500 as watchlist. This Watchlist must be precreated with the stocks list
//In the setting make periodicity as Daily/Weekly as per the EMA value selected
// Select Filter -> Watchlist in AA window, 
// Check Pad&align and choose reference symbol
// Then 1st run Scan and then run Exploration
wlnum = GetOption( "FilterIncludeWatchlist" );
List = CategoryGetSymbols( categoryWatchlist, wlnum );
emaCrossValue = valuewhen( cross( close, ema(close,40) ) ,C, 1); //on Daily this is 200 and on weekly this is 40
deltaAmount = C - emaCrossValue;
percentageChange = (deltaAmount/emaCrossValue)*100;

if ( Status( "action" ) == actionScan ) {
	if ( Status( "stocknum" ) == 0 )	{		
		// cleanup variables created in previous runs
		StaticVarRemove( "~PercentChange*" );
	}
	// prevent accidentely applying to "All symbols"
	if ( StrFind(","+list+",",","+Name()+",") ) 
		StaticVarAdd( "~PercentChange", percentageChange );
}

svPERtotal= StaticVarGet( "~PercentChange" );
svSymbolCount = StrCount(list, ",")+1;
AvePercentageofIndexConstituents = svPERtotal/svSymbolCount;

///////////////////////////////////////////////////
// Explore, let's display the whole WL and confirm
///////////////////////////////////////////////////
Filter = NOT IsNull(svPERtotal);
AddColumn(percentageChange, "percentageChange");
AddColumn(svPERtotal , "svPERtotal", 1.2 );
AddColumn(svSymbolCount, "Total Number of Stocks", 1.0 );
AddColumn(AvePercentageofIndexConstituents , "AvePercentageofIndexConstituents ", 1.2 );


///////////////
// Chart
///////////////
Plot( AvePercentageofIndexConstituents, "AvePercentageofIndexConstituents", colorAqua, styleThick );

Below is the Graphical view of the average i get:
image

Of course the chart is not accurate because of the Look-Ahead bais as indicated by @mradtke . Maybe i need to create NIFTY 500 watchlists for 2-3 years period, plot these charts and merge them to get the final accurate chart.

Thanks very much, I will try

In my post above it is no where written that the code by portfoliobuilder was incorrect because of leading to incorrect results. It wasn't meant to say "results will be incorrect if using it".

It was meant incorrect (or improper) use of StaticVarAdd (together with SetForeign in loop) as it leads to inefficient code execution (as you pointed out).

That was my point.

Btw, in the past there was written "plainly wrong" to similar ones e.g. using non-arrays with StaticVarAdd and SetForeign in loop.

Anyway, I understand your point. "Improper use of ..." would have been better.


@Batupermata,

It got nothing to do with the codes.

It got to do with your settings.

It's not hard to understand when it says:

No symbols matched Apply to / filtering criteria

24

You simply got no list of symbols from your Filter settings.
If you look at your Filter window it surely shows zero at the bottom.

27

That's the reason for that message.
You possibly have chosen multiple categories and "Match all" or you have simply chosen an empty Watchlist.

Click clear button in Filter window and choose single filled watchlist to be included.

So look at your failures first.

2 Likes

I am trying to create a new ticker out of the average percent of Index Constituents. At the end of the AFL i am trying with the below code, but it does not seem to work. Is it possible in this kind of scenario? @fxshrat , @mradtk or any other's can you help me.

//Equity Curve - Starts
if (Status("action") == actionExplore)
{
AddToComposite(AvePercentageofIndexConstituents, "~~AVGAbove200EMA", "C", atcFlagDeleteValues);
}
//Equity Curve - Ends

This is the full AFL:

//Reused @fxshrat's code originally developed for composite ATR
// Building a composite % increase from 200 EMA of Stocks in an Index
//e.g. In Amibroker Analysis select NIFTY 500 as watchlist. This Watchlist must be precreated with the stocks list
//In the setting make periodicity as Daily/Weekly as per the EMA value selected
// Select Filter -> Watchlist in AA window, 
// Check Pad&align and choose reference symbol
// Then 1st run Scan and then run Exploration
wlnum = GetOption( "FilterIncludeWatchlist" );
List = CategoryGetSymbols( categoryWatchlist, wlnum );
emaCrossValue = valuewhen( cross( close, ema(close,40) ) ,C, 1); //on Daily this is 200 and on weekly this is 40
deltaAmount = C - emaCrossValue;
percentageChange = (deltaAmount/emaCrossValue)*100;

if ( Status( "action" ) == actionScan ) {
	if ( Status( "stocknum" ) == 0 )	{		
		// cleanup variables created in previous runs
		StaticVarRemove( "~PercentChange*" );
	}
	// prevent accidentely applying to "All symbols"
	if ( StrFind(","+list+",",","+Name()+",") ) 
		StaticVarAdd( "~PercentChange", percentageChange );
}

svPERtotal= StaticVarGet( "~PercentChange" );
svSymbolCount = StrCount(list, ",")+1;
AvePercentageofIndexConstituents = svPERtotal/svSymbolCount;

///////////////////////////////////////////////////
// Explore, let's display the whole WL and confirm
///////////////////////////////////////////////////
Filter = NOT IsNull(svPERtotal);
AddColumn(percentageChange, "percentageChange");
AddColumn(svPERtotal , "svPERtotal", 1.2 );
AddColumn(svSymbolCount, "Total Number of Stocks", 1.0 );
AddColumn(AvePercentageofIndexConstituents , "AvePercentageofIndexConstituents ", 1.2 );

//AddToComposite(AvePercentageofIndexConstituents, "~~AVGAbove200EMA1", "X", atcFlagDeleteValues | atcFlagEnableInPortfolio );
//Equity Curve - Starts
if (Status("action") == actionExplore)
{
	AddToComposite(AvePercentageofIndexConstituents, "~~AVGAbove200EMA", "C", atcFlagDeleteValues); 
}
//Equity Curve - Ends


///////////////
// Chart
///////////////
Plot( AvePercentageofIndexConstituents, "AvePercentageofIndexConstituents", colorAqua, styleThick );

@YRK please review the AddToComposite() function documentation. In particular reread the following note regarding the usage in explorations:

AddToComposite function also detects the context in which it is run
(it works ONLY in scan mode, unless atcFlagEnableInBacktest or atcFlagEnableInExplore flags are specified) and does NOT affect composite ticker when run in Indicator or Commentary mode, so it is now allowed to join scan and indicator into single formula.

Thanks @beppe i had read the function but missed these lines :woozy_face: :rofl:. Works as expected now

1 Like

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