Iterate backtesting to random entries

Hi, I have to generate 1000 becktest with random entries in a portfolio during the same period. Do you have any idea how can I do that ?

@Carlos Not sure what you are trying to do, but here are some ideas to get you started.

You can generate 1000 backtests with the optimizer. Depending what you need, it might be enough.

dummy = Optimize("dummy", 1, 1, 1000, 1);

You can generate random entries like this:

Buy = MTRandomA() > 0.7;  // change threshold to control frequency of buy signals

Hi @Steve,

Thanks for your help. Let me explain better. I have the code to random entry. So I need apply this same code 1000 times. Would be something like this:

for i=1 to 1000
// code for random entry, the same period each time, with 100 trades

The results would be 1000 runs of the same code with 100000 trades and I have to save all trades in csv. In each run the trades will be different because they have been generated by random entry.
I could do pressing the backtest button 1000 times and joining everything but is very time consuming. I found this in python and R and I would like to know if is possible in AFL.

That’s exactly what @Steve showed you how to do. An optimization is multiple back test runs. If you need to output every one of your trade lists, you can do that by adding a high-level Custom Back Test module which loops through all the completed trades. There are many examples of how to do this.

Yes @mradtke, this is exactly what I need. I dont know these examples but I will look for them.

Thanks,

Here is a python like quick and dirty solution:
you run the code in AA using scan

if( Status( "action" ) == actionScan )
{
	// parameters
	path =  "C:\\Users\\Aron\\Desktop\\trades.csv"  ;
	holdingPeriod = 1; 
	numruns = 1000;
	trades = 100; 
	
	
    change = 100 * ( Ref( Close, holdingPeriod) / Close - 1 ) ;
    len = BarCount - holdingPeriod ;
    index = Sort( mtRandomA() , 0, len - 1 , true );

    trades = Min( trades, len - 1 ) ;
    dt = DateTime();

   
    fh = fopen(path , "w" );

    if( fh )
    {
        count = 0 ;

        while( count <  numruns )
        {

            for( i = 0; i < trades ; i ++ )
            {
                k = index [i] ;
                dtime  = DateTimeToStr( dt [k] );
                line = StrFormat( "%s,%.2f\n", dtime, change[k] ) ;
                fputs( line , fh );
            }

            count ++ ;
        }

        fclose( fh );
    }

    Buy = 0;
}
2 Likes

Hi @aron !

Thank you for your help. This code works and now I can use wtih some adaptations.

Regards,

Carlos