Discusión sobre el artículo "Distribuciones Estadísticas en MQL5: tomando lo mejor de R" - página 7

 
ivanivan_11:

Estoy hablando de R, pero mi habilidad es veri pequeña)) ¿alguien puede comprobar si el código es correcto?

Si el código es correcto, ¿puede comprobar el punto de referencia?

El código es incorrecto.

Has medido el tiempo de compilación de la función, no su ejecución:

La función cmpfun compila el cuerpo de un cierre y devuelve un nuevo cierre con los mismos formales y el cuerpo sustituido por la expresión del cuerpo compilada.


Prueba del error:

> library(microbenchmark)
> library(compiler)
> n <- 2000
> k <- seq(0,n,by=20)
> qqq<- function(xx) { a <- dbinom(k, n, pi/10, log = TRUE) }
> res <- microbenchmark(cmpfun(qqq))
> a
Ошибка: объект 'a' не найден

Si la función qqq se hubiera ejecutado durante el benchmark, el objeto a habría recibido los datos calculados. Pero resultó que el objeto ni siquiera se creó.

Como resultado, el benchmark contó el tiempo de compilación en lugar del tiempo de ejecución. En mi código, todo es correcto - el benchmark cuenta el tiempo de ejecución real y el objeto a se crea con los datos correctos.


Y sí, la compilación es un proceso bastante costoso: se muestra en milisegundos en lugar de microsegundos.

> print(res)
Unit: milliseconds
        expr      min       lq     mean   median       uq      max neval
 cmpfun(qqq) 1.741577 1.783867 1.856366 1.812613 1.853096 2.697548   100
 

Y una broma aparte, cómo anulaste la función del sistema q() - salir - en tu ejemplo.

No había manera de salir de R :)

 
Dr.Trader:

Me refiero a que el compilador mql ya conoce todos los parámetros de entrada en tiempo de compilación. Basta con que lo calcule todo durante la compilación, y al llamar al script, simplemente devuelve el resultado precalculado. Vi algunos artículos en el hub donde comparaban compiladores de c++, y a juzgar por el análisis del código ensamblador, esto es exactamente lo que ocurre allí.

Sí, puede que lo esté utilizando activamente. Aquí hay algunos ejemplos: https://www.mql5.com/ru/forum/58241.

Pero en este caso no va a funcionar - es necesario contar en su totalidad debido a la complejidad, el llenado de bucles y matrices.

 
ivanivan_11:

si el código es correcto, ¿puedes comprobar el benchmark?

Tienes que sustituirres <- microbenchmark (cmpfun ( q) ) por res <- microbenchmark(q())). Pero las librerías previamente compiladas no se recompilarán en bytecode, obtuve los mismos resultados.

Renat Fatkhullin:
qqq<- function(xx) { a <- dbinom(k, n, pi/10, log = TRUE) }

"a" en este caso será una variable local, inaccesible fuera de la propia función de todos modos. Pero se puede hacer de esta manera
a <<- dbinom(k, n, pi/10, log = TRUE)
entonces será una variable global.

Renat Fatkhullin:

Pero en este caso no va a funcionar - que necesita para contar en su totalidad debido a la complejidad, el bucle y la matriz de llenado.

Ya veo, la velocidad de ejecución es excelente entonces

 

Por cierto, no cuesta prácticamente nada interpretar la llamada primitiva a <- dbinom(k, n, pi/10, log = TRUE) con una caída directa en el núcleo de R con ejecución nativa(dbinom está en r.dll).

Así que tratar de compilar esta llamada es obviamente inútil.

 

Ya que he escrito muchas veces sobre la rapidez de R, permítanme poner mis cinco centavos.

¡Querido Renat!

¡Tu ejemplo no es nada!

Has tomado dos funciones similares y has sacado una conclusión sobre el rendimiento de R en absoluto.

Las funciones que has dado no representan la potencia y diversidad de R en absoluto.

Deberías comparar operaciones de gran capacidad computacional.

Por ejemplo, multiplicación de matrices...

Midamos la expresión en R

c <- a*b

donde a y b son matrices de al menos 100*100 de tamaño. En tu código, asegúrate de que R utiliza MKL de Intel. Y esto se consigue simplemente instalando la versión correspondiente de R.

Si nos fijamos en R, hay montañas de código que contienen operaciones computacionalmente intensivas. Para ejecutarlas, se utilizan librerías, que son las más eficientes del momento.

Y la utilidad de R en el trading no está en las funciones que reescribiste (aunque también son necesarias), sino en los modelos. En una de las respuestas que te hice mencioné el paquete caret. Mira lo que es.... La implementación de cualquier modelo de trading prácticamente útil en el marco de este paquete y sobre µl te dará la respuesta

Además, no debes olvidar que cargar todos los núcleos de una comp es una rutina de R. Además puedes cargar comps vecinas en la red local.

PD.

Para mí la idea de comparar el rendimiento de MKL y R es cuestionable: estos dos sistemas tienen áreas temáticas completamente diferentes.

 

SanSanych, lo probaremos todo y publicaremos un benchmark. Pero primero vamos a completar la funcionalidad.

La prueba estaba justificada y reveló inmediatamente el problema. He presentado la justificación teórica y estoy seguro de que la sobrecarga del sistema de R se conservará para la abrumadora cantidad de funcionalidad.

Podemos multiplicar las matrices de tal manera que Intel perderá. No es ciencia de cohetes durante mucho tiempo, e Intel (o más bien, tales programadores de terceros dentro de la afiliación de la empresa) no es un campeón en el conocimiento mítico de sus procesadores.

[Eliminado]  
СанСаныч Фоменко:

Ya que he escrito muchas veces sobre la rapidez de R, déjame poner mis cinco centavos.

.................

Para San-Sanych y los demás.

San-Sanych, ya sabes lo mucho que te respeto ... ((S) Kataev y Feinzilberg, conocidos como "Ilf y Petrov"), a pesar de algunas de tus bromas post-soviéticas aquí.

Permítame aclararle algo importante:

1). El principal trabajo de un programador no es escribir programas, sino LEER programas, en particular los suyos propios. Cualquier programador del 95...99% de su tiempo se sienta y se queda mirando el monitor. ¿Escribe un programa? No, casi siempre lo lee. Por lo tanto, cuanto más cercano al lenguaje natural sea lo que lee en la pantalla, es decir, a lo que le enseñaron su madre, su padre, su abuela, su profesor de escuela, más eficazmente descifrará estas krakozebras lingüísticamente obedientes en la pantalla y encontrará la correspondencia entre el algoritmo y su programa.

2). Para los fines del punto (1) no hay nada mejor en promedio que el lenguaje C. Por eso, por ejemplo, yo personalmente (así como 2-3 personas responsables y no muy responsables) logré escribir un proyecto con 700+ subrutinas en C, MQL4, CUDA..... Y todo funciona.

3). Desde el punto de vista del punto (1), la variante orientada a objetos de C, es decir, C++, es mucho peor. (Pero de eso hablaremos en otra ocasión).

4). La compatibilidad total de C clásico y MQL4 es simplemente inestimable. Transferir un procedimiento de un lado a otro lleva medio minuto.

5). La principal ventaja de C+MQL4 es la CLARIDAD. Es decir, la comprensibilidad y transparencia de todo lo que está en la pantalla del programador.

Si comparamos C-MQL4 con su R, no debemos fijarnos en la velocidad y volumen del código escrito, sino en la CLARIDAD del texto. Es decir, su comprensibilidad. De lo contrario, el programador se quedará 24 horas mirando la pantalla en vanos intentos de entender qué hace el programa, qué parámetros tiene, por qué el autor los nombró así y, en general, por qué el programador lo hizo así y no de otra manera. Lo importante aquí no es la velocidad del programa, sino la corrección de su trabajo y la rapidez de su APLICABILIDAD para el programador final.

Desde este punto de vista, lo que ha hecho Metaquotes es desde luego un gran apoyo para aquellos que quieran insertar estadísticas en sus EAs. No hay nada comparable en cuanto a sencillez y comprensibilidad de las funciones. Y esto es importante. Especialmente si tienes cálculos delicados (y Forex y el trading en general requieren cálculos delicados).

Comparemos.

Así es como se ve la función de integración en C - MQL4:

//__________________________________________________________________
//|
// Integral_Simpson_3_Points_Lite ()|
//_______________________________________________________|
#define  FACTOR_1_3      (1.0 / 3.0)

double Integral_Simpson_3_Points_Lite
(
   double       & Price_Array[],
   int          Period_Param,
   int          Last_Bar
)
{
        double  Sum, Sum_Full_Cycles, Sum_Tail, Sum_Total;
        int             i, j;
        int             Quant;
        int             Full_Cycles;
        int             Tail_Limit;
        int             Tail_Start;

        //..................................................................
        if (Last_Bar < 0)
        {
                Last_Bar = 0;
        }
        //.........................................
        if (Period_Param <= 1)
        {
                return (0.0);
        }
        //.................................................................
        if (Period_Param == 2)
        {
                return (0.5 * (Price_Array[Last_Bar] + Price_Array[Last_Bar + 1]));
        }
        //=============================================================================================
        //=============================================================================================
        Quant = 3;
        Full_Cycles = (Period_Param - 1) / (Quant - 1);
        Tail_Start = Full_Cycles * (Quant - 1);
        Tail_Limit = Period_Param - Tail_Start;
        //...........................................................
        j = Last_Bar;

        Sum = 0.0;
        for (i = 0; i < Full_Cycles; i ++)
        {
                //.........................................................................
                Sum += Price_Array[j];
                Sum += 4.0 * Price_Array[j + 1];
                Sum += Price_Array[j + 2];
                j = j + (Quant - 1);
        }
        //...........................................................
        Sum_Full_Cycles = Sum * FACTOR_1_3;
        Sum_Tail = Integral_Trapezoid_Lite (Price_Array,
                                            Tail_Limit,
                                            Last_Bar + Tail_Start);
        //.........................................................................
        Sum_Total = Sum_Full_Cycles + Sum_Tail;
        //...............................................................
        return (Sum_Total) ;

}
[Eliminado]  

Escribiré por partes, es más fácil escribir así.

Hay una función de integración trapezoidal dentro:

//__________________________________________________________________
//|
// Integral_Trapezoid_Lite ()|
//_______________________________________________________|
double Integral_Trapezoid_Lite
(
   double       & Price_Array[],
   int          Period_Param,
   int          Last_Bar
)
{
        double  Sum;
        int             i;
        int             Price_Index ;
        //.........................................
        if (Last_Bar < 0)
        {
                Last_Bar = 0;
        }
        //.........................................
        if (Period_Param <= 1)
        {
                return (0.0);
        }
        //.................................................................
        if (Period_Param == 2)
        {
                return (0.5 * (Price_Array[Last_Bar] + Price_Array[Last_Bar + 1]));
        }
        //..................................................................
        //..................................................................
        Sum = 0.0;
        for (i = 0; i < Period_Param; i++)
        {
                Price_Index = Last_Bar + i;
                if (Price_Index < 0)
                {
                        break;
                }
                //........................................
                if ((i == 0) || (i == (Period_Param - 1)))
                {
                        Sum = Sum + Price_Array[i] * 0.5;
                }
                else
                {
                        Sum = Sum + Price_Array[i];
                }
        }
        //...............................................................
        return (Sum) ;
}
[Eliminado]  

Todo es absolutamente claro y comprensible. Y lo que es importante, siempre funciona y funciona bien, es decir, con pocos errores incluso en MT4-MQL4, lo que ahorra mucho tiempo.

Pero si quieres averiguar por qué tienes errores incomprensibles cuando trabajas en R, o si simplemente quieres entender qué parámetros hay en el procedimiento de integración o qué método de integración han programado ahí, verás lo siguiente (que Dios me perdone por publicar esto para niños inmaduros programadores):

http://www.netlib.org/quadpack/

Esto es sólo el título de la función escrita originalmente en Fortran. El texto principal vendrá después. Este es el programa original utilizado en el paquete R para la integración.

¿Qué hay que entender aquí, dime?

      subroutine qagse(f,a,b,epsabs,epsrel,limit,result,abserr,neval,
     *   ier,alist,blist,rlist,elist,iord,last)
c***begin prologue  qagse
c***date written   800101   (yymmdd)
c***revision date  830518   (yymmdd)
c***category no.  h2a1a1
c***keywords  automatic integrator, general-purpose,
c             (end point) singularities, extrapolation,
c             globally adaptive
c***author  piessens,robert,appl. math. & progr. div. - k.u.leuven
c           de doncker,elise,appl. math. & progr. div. - k.u.leuven
c***purpose  the routine calculates an approximation result to a given
c            definite integral i = integral of f over (a,b),
c            hopefully satisfying following claim for accuracy
c            abs(i-result).le.max(epsabs,epsrel*abs(i)).
c***description
c
c        computation of a definite integral
c        standard fortran subroutine
c        real version
c
c        parameters
c         on entry
c            f      - real
c                     function subprogram defining the integrand
c                     function f(x). the actual name for f needs to be
c                     declared e x t e r n a l in the driver program.
c
c            a      - real
c                     lower limit of integration
c
c            b      - real
c                     upper limit of integration
c
c            epsabs - real
c                     absolute accuracy requested
c            epsrel - real
c                     relative accuracy requested
c                     if  epsabs.le.0
c                     and epsrel.lt.max(50*rel.mach.acc.,0.5 d-28),
c                     the routine will end with ier = 6.
c
c            limit  - integer
c                     gives an upperbound on the number of subintervals
c                     in the partition of (a,b)
c
c         on return
c            result - real
c                     approximation to the integral
c
c            abserr - real
c                     estimate of the modulus of the absolute error,
c                     which should equal or exceed abs(i-result)
c
c            neval  - integer
c                     number of integrand evaluations
c
c            ier    - integer
c                     ier = 0 normal and reliable termination of the
c                             routine. it is assumed that the requested
c                             accuracy has been achieved.
c                     ier.gt.0 abnormal termination of the routine
c                             the estimates for integral and error are
c                             less reliable. it is assumed that the
c                             requested accuracy has not been achieved.
c            error messages
c                         = 1 maximum number of subdivisions allowed
c                             has been achieved. one can allow more sub-
c                             divisions by increasing the value of limit
c                             (and taking the according dimension
c                             adjustments into account). however, if
c                             this yields no improvement it is advised
c                             to analyze the integrand in order to
c                             determine the integration difficulties. if
c                             the position of a local difficulty can be
c                             determined (e.g. singularity,
c                             discontinuity within the interval) one
c                             will probably gain from splitting up the
c                             interval at this point and calling the
c                             integrator on the subranges. if possible,
c                             an appropriate special-purpose integrator
c                             should be used, which is designed for
c                             handling the type of difficulty involved.
c                         = 2 the occurrence of roundoff error is detec-
c                             ted, which prevents the requested
c                             tolerance from being achieved.
c                             the error may be under-estimated.
c                         = 3 extremely bad integrand behaviour
c                             occurs at some points of the integration
c                             interval.
c                         = 4 the algorithm does not converge.
c                             roundoff error is detected in the
c                             extrapolation table.
c                             it is presumed that the requested
c                             tolerance cannot be achieved, and that the
c                             returned result is the best which can be
c                             obtained.
c                         = 5 the integral is probably divergent, or
c                             slowly convergent. it must be noted that
c                             divergence can occur with any other value
c                             of ier.
c                         = 6 the input is invalid, because
c                             epsabs.le.0 and
c                             epsrel.lt.max(50*rel.mach.acc.,0.5 d-28).
c                             result, abserr, neval, last, rlist(1),
c                             iord(1) and elist(1) are set to zero.
c                             alist(1) and blist(1) are set to a and b
c                             respectively.
c
c            alist  - real
c                     vector of dimension at least limit, the first
c                      last  elements of which are the left end points
c                     of the subintervals in the partition of the
c                     given integration range (a,b)
c
c            blist  - real
c                     vector of dimension at least limit, the first
c                      last  elements of which are the right end points
c                     of the subintervals in the partition of the given
c                     integration range (a,b)
c
c            rlist  - real
c                     vector of dimension at least limit, the first
c                      last  elements of which are the integral
c                     approximations on the subintervals
c
c            elist  - real
c                     vector of dimension at least limit, the first
c                      last  elements of which are the moduli of the
c                     absolute error estimates on the subintervals
c
c            iord   - integer
c                     vector of dimension at least limit, the first k
c                     elements of which are pointers to the
c                     error estimates over the subintervals,
c                     such that elist(iord(1)), ..., elist(iord(k))
c                     form a decreasing sequence, with k = last
c                     if last.le.(limit/2+2), and k = limit+1-last
c                     otherwise
c
c            last   - integer
c                     number of subintervals actually produced in the
c                     subdivision process
c
c***references  (none)
c***routines called  qelg,qk21,qpsrt,r1mach
c***end prologue  qagse
c
      real a,abseps,abserr,alist,area,area1,area12,area2,a1,
     *  a2,b,blist,b1,b2,correc,defabs,defab1,defab2,r1mach,
     *  dres,elist,epmach,epsabs,epsrel,erlarg,erlast,errbnd,
     *  errmax,error1,error2,erro12,errsum,ertest,f,oflow,resabs,
     *  reseps,result,res3la,rlist,rlist2,small,uflow
      integer id,ier,ierro,iord,iroff1,iroff2,iroff3,jupbnd,k,ksgn,
     *  ktmin,last,limit,maxerr,neval,nres,nrmax,numrl2
      logical extrap,noext
c
      dimension alist(limit),blist(limit),elist(limit),iord(limit),
     * res3la(3),rlist(limit),rlist2(52)
c
      external f
c
c            the dimension of rlist2 is determined by the value of
c            limexp in subroutine qelg (rlist2 should be of dimension
c            (limexp+2) at least).
c
c            list of major variables
c            -----------------------
c
c           alist     - list of left end points of all subintervals
c                       considered up to now
c           blist     - list of right end points of all subintervals
c                       considered up to now
c           rlist(i)  - approximation to the integral over
c                       (alist(i),blist(i))
c           rlist2    - array of dimension at least limexp+2
c                       containing the part of the epsilon table
c                       which is still needed for further computations
c           elist(i)  - error estimate applying to rlist(i)
c           maxerr    - pointer to the interval with largest error
c                       estimate
c           errmax    - elist(maxerr)
c           erlast    - error on the interval currently subdivided
c                       (before that subdivision has taken place)
c           area      - sum of the integrals over the subintervals
c           errsum    - sum of the errors over the subintervals
c           errbnd    - requested accuracy max(epsabs,epsrel*
c                       abs(result))
c           *****1    - variable for the left interval
c           *****2    - variable for the right interval
c           last      - index for subdivision
c           nres      - number of calls to the extrapolation routine
c           numrl2    - number of elements currently in rlist2. if an
c                       appropriate approximation to the compounded
c                       integral has been obtained it is put in
c                       rlist2(numrl2) after numrl2 has been increased
c                       by one.
c           small     - length of the smallest interval considered
c                       up to now, multiplied by 1.5
c           erlarg    - sum of the errors over the intervals larger
c                       than the smallest interval considered up to now
c           extrap    - logical variable denoting that the routine
c                       is attempting to perform extrapolation
c                       i.e. before subdividing the smallest interval
c                       we try to decrease the value of erlarg.
c           noext     - logical variable denoting that extrapolation
c                       is no longer allowed (true value)
c
c            machine dependent constants
c            ---------------------------
c
c           epmach is the largest relative spacing.
c           uflow is the smallest positive magnitude.
c           oflow is the largest positive magnitude.
c
c***first executable statement  qagse
      epmach = r1mach(4)
c
c            test on validity of parameters
c            ------------------------------