거래 로봇을 무료로 다운로드 하는 법을 시청해보세요
당사를 Twitter에서 찾아주십시오!
당사 팬 페이지에 가입하십시오
스크립트가 흥미로우신가요?
그렇다면 링크 to it -
하셔서 다른 이들이 평가할 수 있도록 해보세요
스크립트가 마음에 드시나요? MetaTrader 5 터미널에서 시도해보십시오
라이브러리

ALGLIB - 수치 분석 라이브러리 - MetaTrader 5용 라이브러리

게시자:
MetaQuotes
조회수:
442
평가:
(125)
게시됨:
2022.02.11 09:50
업데이트됨:
2023.09.08 17:33
\MQL5\Include\Math\Alglib\
alglib.mqh (2420.29 KB) 조회
alglibmisc.mqh (119.42 KB) 조회
ap.mqh (89.98 KB) 조회
bitconvert.mqh (13.49 KB) 조회
dataanalysis.mqh (1124.84 KB) 조회
integration.mqh (116.61 KB) 조회
interpolation.mqh (1430.87 KB) 조회
linalg.mqh (1455.11 KB) 조회
matrix.mqh (45.38 KB) 조회
optimization.mqh (2246.73 KB) 조회
solvers.mqh (295.08 KB) 조회
statistics.mqh (407.4 KB) 조회
\MQL5\Scripts\UnitTests\Alglib\
TestClasses.mq5 (30.42 KB) 조회
TestClasses.mqh (3032.44 KB) 조회
이 코드를 기반으로 한 로봇이나 지표가 필요하신가요? 프리랜스로 주문하세요 프리랜스로 이동

실제 저자:

Sergey Bochkanov. ALGLIB 프로젝트 웹사이트 - http://www.alglib.net/. 라이브러리는 1999년부터 시작되었습니다.

ALGLIB는 가장 크고 완벽한 수학 라이브러리 중 하나입니다.

푸리에 변환이나 미분 방정식 시스템을 빠르게 만들고 싶은가요? 모든 메서드를 소스 코드로 한곳에 모으기 위해 복잡한 데이터 분석을 수행해야 하나요? 그렇다면 ALGRIB 수학 메서드 라이브러리를 사용해 보세요!

ALGLIB는 현재 다국어 알고리즘의 최고의 라이브러리 중 하나입니다. 다음은 공식 웹사이트에 언급된 ALGLIB에 대한 소개입니다:

ALGLIB는 크로스 플랫폼 수치 분석 및 데이터 처리 라이브러리입니다. 여러 프로그래밍 언어(C++, C#, Pascal, VBA)와 여러 운영 체제(Windows, Linux, Solaris)를 지원합니다. ALGLIB 기능은 다음과 같습니다:

  • Linear algebra (direct algorithms, EVD/SVD)
  • Solvers (linear and nonlinear)
  • Interpolation
  • Optimization
  • Fast Fourier transforms
  • Numerical integration
  • Linear and nonlinear least-squares fitting
  • Ordinary differential equations
  • Special functions
  • Statistics (descriptive statistics, hypothesis testing)
  • Data analysis (classification/regression, including neural networks)
  • Multiple precision versions of linear algebra, interpolation optimization and others algorithms (using MPFR for floating point computations)

왜 ALGLIB를 사용해야 할까요? 왜냐하면:

  • 포터블. 거의 모든 컴파일러를 사용하여 거의 모든 곳에서 컴파일할 수 있습니다(참조 호환성 매트릭스).
  • 사용 용이성. 많은 프로그래밍 언어를 지원합니다. 한가지 언어를 사용하는 경우 외부 라이브러리를 컴파일하고 연결하기 위해 다른 언어(예: FORTRAN)를 공부할 필요가 없습니다.
  • 오픈소스. GPL 2+로 무료로 사용할 수 있습니다.
  • 상업용 사용자에게도 적합. 상용 애플리케이션에서 ALGLIB를 사용하고자 하는 사람은 카피레프트 요구사항 없이 상업용 라이센스를 구입할 수 있습니다..

ALGLIB 라이브러리는 지속적으로 향상되고 있으며 사용자의 의견에 따라 새로운 기능과 개선 사항이 정기적으로 구현됩니다. 최신 버전은 4.0입니다.

또한 라이브러리에는 제안된 메서드의 기능 주요 부분을 다루는 테스트 케이스의 모음이 포함되어 있습니다. 그렇게 하면 테스트를 수행할 수 있고 프로젝트의 저자에게 감지된 오류를 보고 할 수 있습니다.


CAlglib 클래스의 정적 함수는 라이브러리와 함께 사용해야 합니다. 모든 라이브러리 함수는 정적 함수로 CAlglib 시스템 클래스로 이동됩니다.

testclasses.mq5 and testinterfaces.mq5 테스트 케이스 스크립트는 간단한 usealglib.mq4 데모 스크립트와 함께 첨부됩니다. 동일한 이름의 Include 파일(testclasses.mqh 및 testinterfaces.mqh)은 테스트 케이스를 시작하는 데 사용됩니다. 이들은 \MQL5\Scripts\Alglib\Testcases\에 놓아야 합니다.

참고: testclasses.mq5 스크립트를 실행하는데는 꽤 오랜 시간(약 8분)이 걸립니다.

다음은 포트된 ALGLIB MQL5 라이브러리 패키지에 대한 자세한 정보입니다.

패키지
설명
alglib.mqh
기본 라이브러리 패키지에는 사용자 정의 기능이 포함되어 있습니다.라이브러리를 사용하기 위해서는 이러한 함수가 호출되어야 합니다.
alglibinternal.mqh
다른 라이브러리 패키지 작업을 위한 추가 클래스.
alglibmisc.mqh

패키지에는 다음 클래스가 포함되어 있습니다.

  1. CHighQualityRand - 하이 퀄러티 랜덤 넘버 생성기.
  2. CNearestNeighbor - KD-trees 제너레이션과 솔루션.
ap.mqh 패키지에는 다른 패키지에 필요한 추가적인 클래스도 포함되어 있습니다.
bitconvert.mqh MQL5에서 기본으로 제공되지 않는 С++ 기본 클래스 및 기능:
  1. BitConverter - int 및 double 유형 숫자를 비트 배열로 또는 그 반대로 변환하기 위한 클래스입니다.
  2. CINFORNaN - NaN 및 플러스/마이너스 인피니티 검증 및 생성 클래스.
  3. ArrayReverse - 배열 요소 역순 기능.
  4. GetSelectionString - char 유형 배열 요소에서 생성된 문자열을 수신하는 함수입니다.
  5. MathSign - 숫자 기호 계산 기능.
  6. MathSinh - 쌍곡선 사인 계산 기능.
  7. MathCosh - 쌍곡선 사인 계산 기능.
  8. MathTanh - 쌍곡선 탄젠트 계산 기능.
dataanalysis.mqh 데이터 분석 클래스:
  1. CBdSS - 오류 함수 계산.
  2. CDForest - forest solution trees 작업.
  3. CKMeans - k-means++ 알고리즘을 활용한 클러스터링.
  4. CLDA - 선형 판별 분석.
  5. CLinReg - 선형 회귀.
  6. CMLPBase - 다층 퍼셉트론(신경망).
  7. CLogit - 다항 로짓 회귀.
  8. CMarkovCPD - 인구 데이터에 대한 마르코프 체인.
  9. CMLPTrain - 다층 퍼셉트론 훈련.
  10. CMLPE - 신경망 앙상블.
  11. CPCA 분석 - 주 요소 메서드.
delegatefunctions.mqh 패키지에는 대리자를 대체하기 위해 생성된 클래스가 포함되어 있습니다. 이들 클래스의 객체는 여러 라이브러리의 메서드에서 최적화된 함수입니다.
diffequations.mqh 상미분 방정식을 풀기 위한 클래스:
  1. CODESolver - 상미분 방정식 풀기.
fasttransforms.mqh Fast Transformation 클래스:
  1. CFastFourierTransform - 빠른 푸리에 변환.
  2. CConv - 컨볼루션.
  3. CCorr - 상호 상관.
  4. CFastHartleyTransform - 빠른 Hartley 변환.
integration.mqh 적분용 클래스:
  1. CGaussQ - Gaussian quadrature.
  2. CGaussKronrodQ - Gauss–Kronrod quadrature formulas.
  3. CAutoGK - adaptive integrator.
interpolation.mqh 보간, 근사 및 수치 미분 클래스:
  1. CIDWINt - interpolation and approximation by the inverse average weighted distance.
  2. CRatInt - rational interpolation.
  3. CPolInt - polynomial interpolation.
  4. CSpline1D - one-dimensional spline interpolation.
  5. CLSFit - approximation using linear or non-linear least squares method.
  6. CPSpline - parametric spline interpolation.
  7. CSpline2D - two-dimensional spline interpolation.
linalg.mqh 선형 대수 연산 계산을 위한 클래스:
  1. COrtFac - QR/LQ decompositions, decompositions of Hessenberg, as well as of bi- and tridiagonal matrices.
  2. CEigenVDetect - finding the eigenvalues ​​and eigenvectors.
  3. CMatGen - random matrices generation.
  4. CTrFac - LU and Cholesky decompositions.
  5. CRCond - estimation of a matrix dependence value.
  6. CMatInv - matrix inversion.
  7. CBdSingValueDecompose - singular decomposition of a bidiagonal matrix.
  8. CSingValueDecompose - matrix singular decomposition.
  9. CFbls - quick basic linear solutions.
  10. CMatDet - calculation of a matrix determinant.
  11. CSpdGEVD - finding the eigenvalues ​​and eigenvectors in generalized symmetric matrices.
  12. CInverseUpdate - matrices inversion and update.
  13. CSchur - Issai Schur decomposition.
matrix.mqh 행렬 클래스: 정수, 연속 및 복소수.
optimization.mqh 차원 및 다차원 최적화 클래스:
  1. CMinCG - optimization using conjugate gradient method.
  2. CMinBLEIC - optimization with linear constraints in the form of equations and inequations.
  3. CMinLBFGS - optimization using successive generation and classification of the function's quadratic model.
  4. CMinQP - quadratic programming with linear constraints in the form of equations and inequations.
  5. CMinLM - optimization using Levenberg-Marquardt algorithm.
  6. CMinComp - backward compatibility functions.
solvers.mqh 선형 및 비선형 방정식 시스템을 풀기 위한 클래스:
  1. CDenseSolver - solving linear equation systems.
  2. CNlEq - solving non-linear equation systems.
specialfunctions.mqh 분포 함수, 적분 및 다항식의 클래스:
  1. CGammaFunc - Gamma function.
  2. CIncGammaF - incomplete Gamma function.
  3. CBetaF - Beta function.
  4. CIncBetaF - incomplete beta function.
  5. CPsiF - psi-function.
  6. CAiryF - Airy function.
  7. CBessel - Bessel functions of integral order.
  8. CJacobianElliptic - Jacobian elliptic functions.
  9. CDawson - Dawson integral.
  10. CTrigIntegrals - trigonometric integrals.
  11. CElliptic - elliptic integrals of the first and second kind.
  12. CExpIntegrals - exponential integrals.
  13. CFresnel - Fresnel integrals.
  14. CHermite - Hermite polynomials.
  15. CChebyshev - Chebyshev polynomials.
  16. CLaguerre - Laguerre polynomials.
  17. CLegendre - Legendre polynomials.
  18. CChiSquareDistr - chi-square distribution.
  19. CBinomialDistr - binomial distribution.
  20. CNormalDistr - normal distribution.
  21. CPoissonDistr - Poisson distribution.
  22. CStudenttDistr - Student t-distribution.
  23. CFDistr - F-distribution.
statistics.mqh 통계 데이터 분석 클래스:
  1. CBaseStat - basic statistical methods.
  2. CCorrTests - test for correlation ratio significance.
  3. CJarqueBera - JarqueBera croterion.
  4. CMannWhitneyU - Mann-Whitney U-criterion.
  5. CSignTest - sign test.
  6. CStudentTests - Student t-tests.
  7. CVarianceTests - F-test and chi-square test.
  8. CWilcoxonSignedRank - Wilcoxon W-criterion.


Code:

라이브러리 함수에는 사용방법에 대해 자세한 설명이 있습니다.

//+------------------------------------------------------------------+
//| Calculation of the distribution moments: mean, variance,         |
//| skewness, kurtosis.                                              |
//| INPUT PARAMETERS:                                                |
//|     X       -   sample                                           |
//|     N       -   N>=0, sample size:                               |
//|                 * if given, only leading N elements of X are     |
//|                   processed                                      |
//|                 * if not given, automatically determined from    |
//|                   size of X                                      |
//| OUTPUT PARAMETERS                                                |
//|     Mean    -   mean.                                            |
//|     Variance-   variance.                                        |
//|     Skewness-   skewness (if variance<>0; zero otherwise).       |
//|     Kurtosis-   kurtosis (if variance<>0; zero otherwise).       |
//+------------------------------------------------------------------+
static bool CBaseStat::SampleMoments(const double &cx[],const int n,double &mean,
                                     double &variance,double &skewness,double &kurtosis)
  {
//--- check
   if(!CAp::Assert(n>=0,__FUNCTION__+": the error variable"))
      return(false);
//--- check
   if(!CAp::Assert(CAp::Len(cx)>=n,__FUNCTION__+": length(x)<n"))
      return(false);
//--- check
   if(!CAp::Assert(CApServ::IsFiniteVector(cx,n),__FUNCTION__+": x is not finite vector"))
      return(false);
//--- create variables
   double v=0;
   double v1=0;
   double v2=0;
   double stddev=0;
//--- Init, special case 'N=0'
   mean=0;
   variance=0;
   skewness=0;
   kurtosis=0;
//--- check
   if(n<=0)
      return(true);
//--- Mean
   for(int i=0;i<n;i++)
      mean+=cx[i];
   mean/=n;
//--- Variance (using corrected two-pass algorithm)
   if(n!=1)
     {
      //--- calculation
      for(int i=0;i<n;i++)
         v1+=CMath::Sqr(cx[i]-mean);
      for(int i=0;i<n;i++)
         v2+=cx[i]-mean;
      v2=CMath::Sqr(v2)/n;
      variance=(v1-v2)/(n-1);
      //--- calculation
      stddev=MathSqrt(variance);
     }
   else
      variance=EMPTY_VALUE;
//--- Skewness and kurtosis
   if(stddev!=0)
     {
      //--- calculation
      for(int i=0;i<n;i++)
        {
         v=(cx[i]-mean)/stddev;
         v2=CMath::Sqr(v);
         skewness+=v2*v;
         kurtosis+=CMath::Sqr(v2);
        }
      //--- change values
      skewness=skewness/n;
      kurtosis=kurtosis/n-3;
     }
//--- successful execution
   return(true);
  }

라이브러리를 사용하기 위해서는 CAlglib 클래스 정적 함수를 사용해야 합니다. 다음은 통계 트레이딩 매개변수 계산을 위한 usealglib.mq5 함수 스크립트의 소스 코드입니다.

//+------------------------------------------------------------------+
//|                                                    UseAlglib.mq5 |
//|                        Copyright 2012, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Connecting the libraries                                         |
//+------------------------------------------------------------------+
#include <Math\Alglib\alglib.mqh>
#include <Trade\DealInfo.mqh>
#include <Arrays\ArrayDouble.mqh>
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- object to access data on deals
   CDealInfo     deal;
//--- object for storing profit/loss of each deal
   CArrayDouble *profit=new CArrayDouble;
//--- objects for storing the balance
   CArrayDouble *balance_total=new CArrayDouble;
//--- initial balance
   double        balance=0;
//--- receive history
   HistorySelect(0,TimeCurrent());
//--- total amount of deals
   int deals_total=HistoryDealsTotal();
//--- receive data on deals' profit and balance
   for(int i=0;i<deals_total;i++)
     {
      //--- move to the deal having i index
      deal.SelectByIndex(i);
      //--- receive initial balance
      if(deal.DealType()==DEAL_TYPE_BALANCE)
        {
         if(NormalizeDouble(deal.Profit()+deal.Swap(),2)>=0.0)
            if(balance==0.0)
               balance=deal.Profit();
        }
      //--- receive profit and balance
      if(deal.DealType()==DEAL_TYPE_BUY || deal.DealType()==DEAL_TYPE_SELL)
         if(deal.Entry()==DEAL_ENTRY_OUT || deal.Entry()==DEAL_ENTRY_INOUT)
           {
            profit.Add(NormalizeDouble(deal.Profit()+deal.Swap()+deal.Commission(),2));
            balance_total.Add(balance);
            balance=balance+NormalizeDouble(deal.Profit()+deal.Swap()+deal.Commission(),2);
           }
     }
   balance_total.Add(balance_total.At(balance_total.Total()-1)+profit.At(balance_total.Total()-1));
//--- copy data on the balance to double type array
   double arr_balance[];
   ArrayResize(arr_balance,balance_total.Total());
   for(int i=0;i<balance_total.Total();i++)
      arr_balance[i]=balance_total.At(i);
//--- copy data on profit to double type array
   double arr_profit[];
   ArrayResize(arr_profit,profit.Total());
   for(int i=0;i<profit.Total();i++)
      arr_profit[i]=profit.At(i);
//--- linear regression
//--- number of independent variables
   int nvars=1;
//--- sample volume
   int npoints=balance_total.Total();
//--- create the matrix of parameters for the linear regression
   CMatrixDouble xy(npoints,nvars+1);
   for(int i=0;i<npoints;i++)
     {
      xy[i].Set(0,i);
      xy[i].Set(1,arr_balance[i]);
     }
//--- variable for detecting calculations result (successful, unsuccessful)
   int info;
//--- class objects necessary for storing data on calculations
   CLinearModelShell lm;
   CLRReportShell    ar;
//--- arrays for storing regression results
   double lr_coeff[];
   double lr_values[];
   ArrayResize(lr_values,npoints);
//--- calculate linear regression ratios
   CAlglib::LRBuild(xy,npoints,nvars,info,lm,ar);
//--- receive linear regression ratios
   CAlglib::LRUnpack(lm,lr_coeff,nvars);
//--- receive recovered linear regression values
   for(int i=0;i<npoints;i++)
      lr_values[i]=lr_coeff[0]*i+lr_coeff[1];
//--- calculate Expected Payoff
   double exp_payoff,tmp1,tmp2,tmp3;
   CAlglib::SampleMoments(arr_profit,exp_payoff,tmp1,tmp2,tmp3);
//--- calculate HPR array
   double HPR[];
   ArrayResize(HPR,balance_total.Total()-1);
   for(int i=0;i<balance_total.Total()-1;i++)
      HPR[i]=balance_total.At(i+1)/balance_total.At(i);
//--- calculate standard deviation and math expectation from HPR
   double AHPR,SD;
   CAlglib::SampleMoments(HPR,AHPR,SD,tmp2,tmp3);
   SD=MathSqrt(SD);
//--- calculate LR Correlation
   double lr_corr=CAlglib::PearsonCorr2(arr_balance,lr_values);
//--- receive LR Standard Error
   double lr_stand_err=0;
   for(int i=0;i<npoints;i++)
     {
      double delta=MathAbs(arr_balance[i]-lr_values[i]);
      lr_stand_err=lr_stand_err+delta*delta;
     }
   lr_stand_err=MathSqrt(lr_stand_err/(npoints-2));
//--- calculate Sharpe Ratio
   double sharpe_ratio=(AHPR-1)/SD;
//--- print
   PrintFormat("-----------------------------------------------");
   PrintFormat("Correlation function: y = %.2fx + %.2f",lr_coeff[0],lr_coeff[1]);
//--- parameters
   PrintFormat("Expected Payoff = %.2f",exp_payoff);
   PrintFormat("AHPR = %.4f",AHPR);
   PrintFormat("Sharpe Ratio = %.2f",sharpe_ratio);
   PrintFormat("LR Correlation = %.2f",lr_corr);
   PrintFormat("LR Standard Error = %.2f",lr_stand_err);
   PrintFormat("-----------------------------------------------");
//--- delete objects
   delete profit;
   delete balance_total;
  }
//+------------------------------------------------------------------+

다음과 같은 결과를 얻게 됩니다:



MetaQuotes Ltd에서 러시아어로 번역함.
원본 코드: https://www.mql5.com/ru/code/1146

IndicatorParameters() 사용 예 IndicatorParameters() 사용 예

이 Expert Advisor는 IndicatorParameters() 함수를 사용하여 입력 매개변수의 수, 유형 및 값에 대한 정보를 얻는 방법을 보여줍니다.

실시간 최적화 결과의 시각화 실시간 최적화 결과의 시각화

최적화의 결과를 실시간으로 시각화하는 예를 소개합니다(균형 곡선 역학 및 Expert Advisor 통계 매개변수).

SMA(no loop) SMA(no loop)

Fast way to calculate Simple moving average.

Trailing Star Trailing Star

Set Trailing Stop only when profit