I need to develop system , using repeated median slope , instead of linear regression slope.
The mathematical formula for the repeated median slope
Slope(t) =median(i) {median(i≠j) [(price(t-j)-price(t-i))/(j-i)] }
i=1 to N j=1 to N
Can I use regular Amibroker array for this calculation ?
I can't find solution, just use price array for this calculation.
I am not sure if this is exactly what you wanted but at least should show you how to start:
Version( 6.10 ); // requires versions 6.10+
N = 10; // lookback period
input = Close; // input data
mx = Matrix( N - 1, BarCount );
for( i = N; i < BarCount; i++ )
{
for( j = 1; j < N; j++ )
{
mx[ j - 1 ][ i ] = ( input[ i ] - input[ i - j ] ) / j ;
// dividing by just the distance makes more sense than dividing by ( i - j )
}
}
mx = MxSort( mx, 1 ); // sort each column
// get middle element - that is our median value
slope = MxGetBlock( mx, (N-1)/2, (N-1)/2, 0, BarCount -1, True );
repeated_median = Median( slope, N ); // median of median slopes
// compare rep median slope and linear reg slope
Plot( repeated_median, "RepMedianSlope", colorRed );
Plot( LinRegSlope( input, N ), "LinRegSlope", colorBlue );
As one of our users (@teyano) noted it may make more sense to have just j
in the denominator. Initially there was ( i - j )
because it was written so in the original question.
As I wrote, this code is a quickie, meant as starting point for person who asked for it.
Anyway I added comparison of repeated median slope and linear reg slope so it really shows that repeated median is less susceptible to outliers.
This code is nice example of powerful matrix functionality available in AmiBroker. Note that the code creates N column * BarCount rows
matrix and each column must be sorted individually to find the median for each bar. That is quite a lot of calculations, yet the code is blazing fast because MxSort()
can do per-column sorting of entire matrix in a single call.
Thanks Tomas!
I never before use “Matrix” In Amibroker, but as you mention, it’s very powerful!
So, this is code now:
N = 10; // lookback period
input = Close; // input data
M = (N-1) * (N-1);
mx = Matrix( M, BarCount );
for( k = N; k < BarCount; k++ )
{
ij = 0;
for( i = 0; i < N; i++ )
{
for( j = 1; j < N; j++ )
{
if( i != j)
{
ij = ij + 1;
mx[ ij - 1 ][ k ] = ( input[ k - i ] - input[ k - j ] ) /(j - i) ;
}
}
}
}
mx = MxSort( mx, 1 );
// get middle element - that is our median value
slope = MxGetBlock( mx, (m-1)/2, (m-1)/2, 0, BarCount -1, True );
repeated_median = Median( slope, N ); // median of median slopes
Regards, Boris kanevsky.