aboutsummaryrefslogtreecommitdiffstats
path: root/src/opti.cpp
blob: 702e8c2c7f75c425b07fb0408a3d61fef8217d0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <vector>
#include <nlopt.hpp>
#include <cmath>
#include <algorithm>
#include <iostream>

double pos (double x){
    return x>0?x:0;
};

double f (const std::vector<double> &X, std::vector<double> &grad, void *params) {
    int d = X.size();
    double *p =(double *)params;
    double r=p[0] ; double T=p[1]; double S0=p[2];
    double V=p[3]; double K=p[4];
    double norm = 0;
    for(int i=0; i<d; i++){
        norm+=X[i]*X[i];
    }
    std::vector<double> S(d);
    S[0]= S0*exp((r-V*V/2)*(T/d)+V*sqrt(T/d)*X[0]);
    for(int i=1;i<d;i++){
        S[i]=S[i-1]*exp((r-V*V/2)*(T/d)+V*sqrt(T/d)*X[i]);
    }
    double temp = std::accumulate(S.begin(), S.end(), 0.)/d;
    double value = exp(-r*T)*pos(temp-K);
    return log(value) - 0.5*norm;
};




int main() {
    
    double params[5] = {0.05, 1, 50, 0.1, 45};
    
    nlopt::opt opt(nlopt::LN_COBYLA, 16);

    opt.set_max_objective(f, &params);

    opt.set_xtol_rel(1e-4);

    std::vector<double> x(16,0);
    std::vector<double> g(0);

    
    std::cout<<"valeur au début : "<<f(x, g, &params)<<std::endl;

    double maxf;
    nlopt::result result = opt.optimize(x, maxf);
    for(int i=0; i<16; i++){
        std::cout<<x[i]<<std::endl;
    }
    std::cout<<"valeur à la fin : "<<maxf<<std::endl;

    return 0;
}