Apply Index MA to backtest

I have 3rd party code that identifies certain patterns and suggests trades in the Explorations, and provides back test results when running the back test. However, I want to insert code that tests for the index (e.g., "^GSPC", "^MID", "^SML", or "^RUT") 200-day moving average prior to listing exploration or back test results. So far, I have found code that works but I think it checks each ticker for individual MA instead of the overall index MA. I don't know how to convert it to a check the index MA. Here is my code:

NumPos = 5;
SetOption( "MaxOpenPositions", NumPos );
PositionSize = -100 / NumPos;
Index = Foreign("^GSPC", "C", True);
FastMA = MA(Index, 90);
SlowMA = MA(Index, 200);
Buy = Cross( FastMA, SlowMA);
Sell = Cross( SlowMA, FastMA);

The above code does not work with the Index line inserted. The following code does work but check each stock's MA (not what I want).

NumPos = 5;
SetOption( "MaxOpenPositions", NumPos );
PositionSize = -100 / NumPos;
FastMA = MA(C, 90);
SlowMA = MA(C, 200);
Buy = Cross( FastMA, SlowMA);
Sell = Cross( SlowMA, FastMA);

Can anyone help me fix this? Thanks.

@charlescody I think a good place for you to start is with this article. After experimenting with these codes if you don't have a solution come back and show the forum what's not working for you.

http://www.amibroker.com/kb/2014/09/20/broad-market-timing-in-system-formulas/

Thanks. I had already discovered this procedure and attempted to use it. I copied the code and saved it in my Custom folder. Ran a back test against a large cap universe of stocks (close to the S&P500) and did not get any results. Set time period from 2014 to present. Perhaps the code is not meant to stand alone but be put into a larger procedure?

@charlescody sorry it works for me. I just pasted it in and ran a backtest on the S&P 500 (my only difference is I do not have ^GSPC in my data so I used my database symbol for the index).

I don't know what else to suggest other than make sure you have that symbol in your data.

image

Interesting. I changed ^GSPC to $SPX and added $SPX to the database and it worked. So, that tells me it did not recognize ^GSPC. Perhaps the symbol is incorrect? BTW I want to test the S&P600 (^SML), the S&P400 (^MID), and the Russell2K (^RUT). Do you know the correct symbols to use?

Again, thanks for your help.

1 Like

@charlescody the symbols depend upon your data source. I use Norgate so the major U.S. based index symbols are,

// Norgate symbols
// $RUA is Russell 3000, 	$RUI is Russell 1000,	 	$RUT is Russell 2000
// $SPX is SP500, 			$SP1500 is SP1500, 			$MID is SP400 MidCap,
// $NDX is Nasdaq 100 		$DJI is Dow Jones Industrial Average
// $SML is the SP600 small cap