Integral() function in AFL?


I am in the process of moving my trading system analysis from MATLAB to Amibroker AFL. I've searched this forum for integral() or quad() and read the list of functions published here: as well as general google searches.

I would like to replace the MATLAB function: integral( fun, xmin, xmax ) which numerically integrates function "fun" from "xmin" to "xmax" using global adaptive quadrature and default error tolerances.

My specific application is to implement Espen Haug's benchmark option pricing for american options with discrete dividends:

function callprice = DiscreteDividend( s, k, r, t, vol, d, dt )

%code by written by a. biao at
%based upon E. Haug, "Back to Basics:  A New Approach to the Discrete Dividend Problem", 2003;

%s: current stock price;
%k: strike price;
%r: risk-free interest rate;
%t: time to maturity of option;
%vol: volatility;
%d: discrete dividend amount
%dt: dividend time

Haug2003 = exp( -r * dt ) * ( integral( @( x ) blsprice( x - d, k, r, t - dt, vol, 0 ) .* lognpdf( x, lns + ( r - 0.5 *vol^2 ) * dt, vol * sqrt( dt ) ), d, k + d ) ...
	+ integral( @( x ) blsprice( x - d, k, r, t - dt, vol, 0 ) .* lognpdf( x, lns + ( r - 0.5 * vol^2 ) * dt, vol * sqrt( dt ) ), k + d, 20 * s ) );
callprice = Haug2003;

Thank you for any help in pointing me in the right direction for accomplishing this in Amibroker AFL.

Kind regards,

There is no direct 1-1 replacement for MATLAB's Integral() yet (however it may be good idea for future addition - thanks)

In the meantime there are two possibilities, one is to use AmiPy plug-in - Python integration to call numpy/scipy modules for integration, or write integration directly in AFL, the simplest is obviously

integral_sum = 0;
steps = 100000;
xmin = 1;
xmax = 2;
dx = (xmax - xmin)/steps;
for( i = 0; i < num_steps; i++ )
  x = xmin + i * dx;
  integral_sum += your_function_here(  x );

integral = dx * integral_sum;

Obviously it just an illustration of absolutely simplest approach that may not provide required accuracy without bumping up number of steps to very high value making too slow to be practical.


Thank you Tomasz. I will delve into the AmiPy plugin :smiley:

On a side note: I am continually surprised by your personal involvement in answering so many questions on the forum. Thank you for your patience and perseverance in developing Amibroker into the powerhouse platform it is.