root/applications/robust/main.cpp @ 1395

Revision 1395, 16.9 kB (checked in by sindj, 13 years ago)

Dodelavani toho zatracenyho samplingu. JS

Line 
1
2/*!
3\file
4\brief Robust
5\author Vasek Smidl
6
7 */
8
9#include "estim/arx.h"
10#include "robustlib.h"
11#include <vector>
12#include <iostream>
13#include <fstream>
14//#include <itpp/itsignal.h>
15#include "windows.h"
16#include "ddeml.h"
17#include "stdio.h"
18
19//#include "DDEClient.h"
20//#include <conio.h>
21
22
23using namespace itpp;
24using namespace bdm;
25
26//const int emlig_size = 2;
27//const int utility_constant = 5;
28
29const int max_model_order = 1;
30const double apriorno     = 0.01;
31
32/*
33HDDEDATA CALLBACK DdeCallback(
34        UINT uType,     // Transaction type.
35        UINT uFmt,      // Clipboard data format.
36        HCONV hconv,    // Handle to the conversation.
37        HSZ hsz1,       // Handle to a string.
38        HSZ hsz2,       // Handle to a string.
39        HDDEDATA hdata, // Handle to a global memory object.
40        DWORD dwData1,  // Transaction-specific data.
41        DWORD dwData2)  // Transaction-specific data.
42{
43        return 0;
44}
45
46void DDERequest(DWORD idInst, HCONV hConv, char* szItem)
47{
48        HSZ hszItem = DdeCreateStringHandle(idInst, szItem, 0);
49        HDDEDATA hData = DdeClientTransaction(NULL,0,hConv,hszItem,CF_TEXT,
50                                                                        XTYP_ADVSTART,TIMEOUT_ASYNC , NULL); //TIMEOUT_ASYNC
51        if (hData==NULL)
52        {
53                printf("Request failed: %s\n", szItem);
54        }
55
56        if (hData==0)
57        {
58                printf("Request failed: %s\n", szItem);
59        }
60}
61
62DWORD WINAPI ThrdFunc( LPVOID n )
63{   
64    return 0;
65}
66*/
67
68class model
69{
70public:
71        set<pair<int,int>> ar_components;
72
73        // Best thing would be to inherit the two models from a single souce, this is planned, but now structurally
74        // problematic.
75        RARX* my_rarx; //vzmenovane parametre pre triedu model
76        ARXwin* my_arx;
77
78        bool has_constant;
79        int  window_size;  //musi byt vacsia ako pocet krokov ak to nema ovplyvnit
80        int  predicted_channel;
81        mat* data_matrix;
82        vec  predictions;
83        char name[80];
84       
85        model(set<pair<int,int>> ar_components, //funkcie treidz model-konstruktor
86                  bool robust, 
87                  bool has_constant, 
88                  int window_size, 
89                  int predicted_channel,
90                  mat* data_matrix)
91        {
92                this->ar_components.insert(ar_components.begin(),ar_components.end());
93
94                strcpy(name,"M");
95
96                for(set<pair<int,int>>::iterator ar_ref = ar_components.begin();ar_ref!=ar_components.end();ar_ref++)
97                {
98                        char buffer1[2];
99                        char buffer2[2];
100                        itoa((*ar_ref).first,buffer1,10);
101                        itoa((*ar_ref).second,buffer2,10);
102
103                        strcat(name,buffer1);
104                        strcat(name,buffer2);
105                        strcat(name,"_");
106                }
107
108                this->has_constant      = has_constant;
109
110                if(has_constant)
111                {
112                        strcat(name,"C");
113                }
114
115                this->window_size       = window_size;
116                this->predicted_channel = predicted_channel;
117                this->data_matrix       = data_matrix;
118
119                if(robust)
120                {
121                        strcat(name,"R");
122
123                        if(has_constant)
124                        {
125                                my_rarx = new RARX(ar_components.size()+1,window_size,true,sqrt(2*apriorno),sqrt(2*apriorno),ar_components.size()+4);
126                                my_arx  = NULL;
127                        }
128                else
129                        {
130                                my_rarx = new RARX(ar_components.size(),window_size,false,sqrt(2*apriorno),sqrt(2*apriorno),ar_components.size()+3);
131                                my_arx  = NULL;
132                        }
133                }
134                else
135                {
136                        my_rarx = NULL;
137                        my_arx  = new ARXwin();
138                        mat V0;
139
140                        if(has_constant)
141                        {                               
142                                V0  = apriorno * eye(ar_components.size()+2); //aj tu konst
143                                //V0(0,0) = 0;
144                                my_arx->set_constant(true);                             
145                        }
146                        else
147                        {
148                               
149                                V0  = apriorno * eye(ar_components.size()+1);//menit konstantu
150                                //V0(0,0) = 0;
151                                my_arx->set_constant(false);                           
152                               
153                        }
154
155                        my_arx->set_statistics(1, V0, V0.rows()+2);                     
156                        my_arx->set_parameters(window_size);
157                        my_arx->validate();
158                }
159        }
160
161        void data_update(int time) //vlozime cas a ono vlozi do data_vector podmineky(conditions) a predikce, ktore pouzije do bayes
162        {
163                vec data_vector;
164                for(set<pair<int,int>>::iterator ar_iterator = ar_components.begin();ar_iterator!=ar_components.end();ar_iterator++)
165                {  //ar?iterator ide len od 1 pod 2, alebo niekedy len 1
166                        data_vector.ins(data_vector.size(),(*data_matrix).get(ar_iterator->first,time-ar_iterator->second));
167// do data vector vlozi pre dany typ regresoru prislusne cisla z data_matrix. Ale ako? preco time-ar_iterator->second?
168                }
169                if(my_rarx!=NULL)
170                {       //pre robust priradi az tu do data_vector aj predikciu
171                        data_vector.ins(0,(*data_matrix).get(predicted_channel,time));
172                        my_rarx->bayes(data_vector);
173                }
174                else
175                {
176                        vec pred_vec;//tu sa predikcia zadava zvlast
177                        pred_vec.ins(0,(*data_matrix).get(predicted_channel,time));
178                        my_arx->bayes(pred_vec,data_vector);
179                }
180        }
181
182        pair<vec,vec> predict(int sample_size, int time, itpp::Laplace_RNG* LapRNG)  //nerozumiem, ale vraj to netreba, nepouziva to
183        {
184                vec condition_vector;
185                for(set<pair<int,int>>::iterator ar_iterator = ar_components.begin();ar_iterator!=ar_components.end();ar_iterator++)
186                {
187                        condition_vector.ins(condition_vector.size(),(*data_matrix).get(ar_iterator->first,time-ar_iterator->second+1));
188                }
189
190                if(my_rarx!=NULL)
191                {
192                        pair<vec,mat> imp_samples = my_rarx->posterior->importance_sample(sample_size);
193
194                        //cout << imp_samples.first << endl;                   
195                       
196                        vec sample_prediction;                 
197                        for(int t = 0;t<sample_size;t++)
198                        {
199                                vec lap_sample = condition_vector;
200                               
201                                if(has_constant)
202                                {
203                                        lap_sample.ins(lap_sample.size(),1.0);
204                                }
205                               
206                                lap_sample.ins(lap_sample.size(),(*LapRNG)());
207
208                                sample_prediction.ins(0,lap_sample*imp_samples.second.get_col(t));                             
209                        }
210
211                        return pair<vec,vec>(imp_samples.first,sample_prediction);
212                }       
213                else
214                {
215                        mat samples = my_arx->posterior().sample_mat(sample_size);                     
216                       
217                        vec sample_prediction;
218                        for(int t = 0;t<sample_size;t++)
219                        {
220                                vec gau_sample = condition_vector;
221                               
222                                if(has_constant)
223                                {
224                                        gau_sample.ins(gau_sample.size(),1.0);
225                                }
226                               
227                                gau_sample.ins(gau_sample.size(),randn());
228
229                                sample_prediction.ins(0,gau_sample*samples.get_col(t));                         
230                        }
231
232                        return pair<vec,vec>(ones(sample_prediction.size()),sample_prediction);
233                }
234       
235        }
236
237
238        static set<set<pair<int,int>>> possible_models_recurse(int max_order,int number_of_channels)
239        {
240                set<set<pair<int,int>>> created_model_types;           
241
242                if(max_order == 1)//ukoncovacia vetva
243                {                       
244                        for(int channel = 0;channel<number_of_channels;channel++)//pre AR 1 model vytvori kombinace kanalov v prvom kroku poyadu
245                        {
246                                set<pair<int,int>> returned_type;
247                                returned_type.insert(pair<int,int>(channel,1));  //??
248                                created_model_types.insert(returned_type);
249                        }
250
251                        return created_model_types;
252                }
253                else
254                {
255                        created_model_types = possible_models_recurse(max_order-1,number_of_channels);//tu uz mame ulozene kombinace o jeden krok dozadu  //rekuryivne volanie
256                        set<set<pair<int,int>>> returned_types;
257                       
258                        for(set<set<pair<int,int>>>::iterator model_ref = created_model_types.begin();model_ref!=created_model_types.end();model_ref++)
259                        {                               
260                               
261                                for(int order = 1; order<=max_order; order++)
262                                {
263                                        for(int channel = 0;channel<number_of_channels;channel++)
264                                        {
265                                                set<pair<int,int>> returned_type;
266                                                pair<int,int> new_pair = pair<int,int>(channel,order);//??
267                                                if(find((*model_ref).begin(),(*model_ref).end(),new_pair)==(*model_ref).end()) //??
268                                                {
269                                                        returned_type.insert((*model_ref).begin(),(*model_ref).end()); //co vlozi na zaciatok retuned_type?
270                                                        returned_type.insert(new_pair);
271                                                       
272
273                                                        returned_types.insert(returned_type);                                                   
274                                                }
275                                        }
276                                }
277                        }
278
279                        created_model_types.insert(returned_types.begin(),returned_types.end());
280
281                        return created_model_types;
282                }               
283        }
284};
285
286
287
288
289int main ( int argc, char* argv[] ) 
290{
291       
292        // EXPERIMENT: A moving window estimation and prediction of RARX is tested on data generated from
293    // y_t=0.95*y_(t-1)+0.05*y_(t-2)+0.2*e_t, where e_t is normally, student(4) and cauchy distributed. It
294    // can be compared to the classical setup.
295       
296        itpp::Laplace_RNG LapRNG = Laplace_RNG();       
297
298        vector<vector<string>> strings;
299
300        char* file_string =  "C:\\ar_student_single"; // "C:\\dataADClosePercDiff"; // 
301
302        char dfstring[80];
303        strcpy(dfstring,file_string);
304        strcat(dfstring,".txt");
305       
306       
307        mat data_matrix;
308        ifstream myfile(dfstring);
309        if (myfile.is_open())
310        {               
311                string line;
312                while(getline(myfile,line))
313                {                       
314                        vec data_vector;
315                        while(line.find(',') != string::npos) //zmenil som ciarku za medzeru
316                        {
317                                //line.erase(0,1); // toto som sem pridal
318                                int loc2 = line.find('\n');
319                                int loc  = line.find(',');
320                                data_vector.ins(data_vector.size(),atof(line.substr(0,loc).c_str()));                           
321                                line.erase(0,loc+1);                                   
322                        }
323
324                        data_matrix.ins_row(data_matrix.rows(),data_vector);
325                }               
326
327                myfile.close(); 
328        }
329        else
330        {
331                cout << "Can't open data file!" << endl;
332        }
333       
334        //konec nacitavania dat
335        set<set<pair<int,int>>> model_types = model::possible_models_recurse(max_model_order,data_matrix.rows()); //volanie funkce kde robi kombinace modelov
336                                                                                                //to priradime do model_types, data_matrix.row urcuje pocet kanalov dat
337        vector<model*> models;
338        for(set<set<pair<int,int>>>::iterator model_type = model_types.begin();model_type!=model_types.end();model_type++)
339        {// prechadza rozne typy kanalov, a poctu regresorov
340                for(int window_size = 50;window_size < 51;window_size++)
341                {
342                        models.push_back(new model((*model_type),true,true,window_size,0,&data_matrix));   // to su len konstruktory, len inicializujeme rozne typy
343                        models.push_back(new model((*model_type),false,true,window_size,0,&data_matrix));
344                        models.push_back(new model((*model_type),true,false,window_size,0,&data_matrix));
345                        models.push_back(new model((*model_type),false,false,window_size,0,&data_matrix));             
346                }
347
348                //set<pair<int,int>> empty_list;
349                //models.push_back(new model(empty_list,false,true,100,0,&data_matrix));
350        }
351       
352        mat result_lognc;
353        // mat result_preds;
354
355        ofstream myfilew;
356        //char fstring[80];                                     
357        //strcpy(fstring,file_string);
358        //strcat(fstring,"lognc.txt");
359        //strcat(fstring,"preds.txt"); 
360
361        for(int time = max_model_order;time<data_matrix.cols();time++) //time<data_matrix.cols()
362        {       //pocet stlpcov data_matrix je pocet casovych krokov
363                vec cur_res_lognc;
364                // vec preds;
365                vector<string> nazvy;
366                for(vector<model*>::iterator model_ref = models.begin();model_ref!=models.end();model_ref++)
367                {//posuvam s apo models, co je pole modelov urobene o cyklus vyssie. Teda som v case time a robim to tam pre vsetky typy modelov, kombinace regresorov
368                        (*model_ref)->data_update(time); //pozret sa preco je toto tu nutne
369
370                        cout << "Updated." << endl;
371                        //if (time = max_model_order) nazvy.push_back(models.model_ref]);// ako by som mohol dostat nazov modelu?
372
373                        if((*model_ref)->my_rarx!=NULL) //vklada normalizacni faktor do cur_res_lognc
374                        {
375                                cur_res_lognc.ins(cur_res_lognc.size(),(*model_ref)->my_rarx->posterior->_ll());                               
376                        }
377                        else
378                        {
379                                cur_res_lognc.ins(cur_res_lognc.size(),(*model_ref)->my_arx->_ll());
380                        }
381
382                        int sample_size = 10;
383                        pair<vec,mat> samples;
384                        if((*model_ref)->my_arx!=NULL)
385                        {
386                                mat samp_mat = (*model_ref)->my_arx->posterior().sample_mat(sample_size);
387                                samples = pair<vec,mat>(ones(samp_mat.rows()),samp_mat);
388                        }
389                        else
390                        {
391                                samples = (*model_ref)->my_rarx->posterior->importance_sample(sample_size);
392                        }
393                       
394                        for(int i=0;i<(*model_ref)->ar_components.size()+1;i++)
395                        {
396                                char fstring[80];                                       
397                                strcpy(fstring,file_string);
398                                strcat(fstring,(*model_ref)->name);
399                                strcat(fstring,".txt");
400                               
401                                cout << samples.first << endl;
402                               
403                                myfilew.open(fstring,ios::app);
404                                myfilew << samples.first << endl << samples.second << endl << zeros(samples.first.size()) << endl; 
405                                myfilew.close();
406                        }                       
407                       
408                        /* // PREDICTIONS
409                        pair<vec,vec> predictions = (*model_ref)->predict(500,time,&LapRNG);
410
411                        cout << predictions.first << endl << predictions.second << endl;
412
413                        double avg_prediction = (predictions.first*predictions.second)/(predictions.first*ones(predictions.first.size()));
414
415                        (*model_ref)->predictions.ins((*model_ref)->predictions.size(),avg_prediction);
416                                       
417                        myfilew.open(fstring,ios::app);
418                        myfilew << avg_prediction << ",";
419                        myfilew.close();
420                        */
421
422                        //preds.ins(0,data_matrix.get(0,time+1));
423                }
424
425               
426                /* // REAL PRICE
427                myfilew.open(fstring,ios::app);
428                myfilew << data_matrix.get(0,time+1) << endl;
429                myfilew.close();
430                */
431
432                result_lognc.ins_col(result_lognc.cols(),cur_res_lognc);
433                // result_preds.ins_col(result_preds.cols(),preds);
434
435                // cout << "Updated." << endl; 
436                                                       
437                /*
438                myfilew.open(fstring,ios::app);
439               
440                // myfile << my_rarx->posterior->minimal_vertex->get_coordinates()[0];
441               
442                if(time == max_model_order)
443                {
444                        for(int i = 0;i<cur_res_lognc.size();i++)
445                        {
446                                for(set<pair<int,int>>::iterator ar_ref = models[i]->ar_components.begin();ar_ref != models[i]->ar_components.end();ar_ref++)
447                                {
448                                        myfilew << (*ar_ref).second << (*ar_ref).first;                                                 
449                                }
450
451                                myfilew << ".";
452
453                                if(models[i]->my_arx == NULL)
454                                {
455                                        myfilew << "1";
456                                }
457                                else
458                                {
459                                        myfilew << "0";
460                                }
461                                       
462                                if(models[i]->has_constant)
463                                {
464                                        myfilew << "1";
465                                }
466                                else
467                                {
468                                        myfilew << "0";
469                                }
470
471                                myfilew << ",";
472                        }
473
474                        myfilew << endl;
475                }
476               
477               
478                // for(int i = 0;i<cur_res_lognc.size();i++)
479                // {
480                //         myfilew << cur_res_lognc[i] << ' ';//zmenil som ciarku ze medzeru
481                // }
482               
483
484                myfilew << endl;                               
485               
486                myfilew.close();
487                */
488               
489}
490       
491
492
493        // EXPERIMENT: One step ahead price prediction. Comparison of classical and robust model using optimal trading
494    //             with maximization of logarithm of one-step ahead wealth.
495
496       
497               
498                /*
499                cout << "One experiment finished." << endl;
500
501                ofstream myfile;
502                myfile.open("c:\\robust_ar1.txt",ios::app);
503                myfile << endl;
504                myfile.close();
505
506                myfile.open("c:\\robust_ar2.txt",ios::app);
507                myfile << endl;
508                myfile.close();*/
509       
510
511        //emlig* emlig1 = new emlig(emlig_size);
512
513        //emlig1->step_me(0);
514        //emlig* emlig2 = new emlig(emlig_size);
515       
516        /*
517        emlig1->set_correction_factors(4);
518
519        for(int j = 0;j<emlig1->correction_factors.size();j++)
520        {
521                for(set<my_ivec>::iterator vec_ref = emlig1->correction_factors[j].begin();vec_ref!=emlig1->correction_factors[j].end();vec_ref++)
522                {
523                        cout << j << "    ";
524                       
525                        for(int i=0;i<(*vec_ref).size();i++)
526                        {
527                                cout << (*vec_ref)[i];
528                        }
529
530                        cout << endl;
531                }
532        }*/
533       
534        /*
535    vec condition5 = "1.0 1.0 1.01";//"-0.3 1.7 1.5";
536
537        emlig1->add_condition(condition5);
538        //emlig1->step_me(0);
539
540
541        vec condition1a = "-1.0 1.02 0.5";
542        //vec condition1b = "1.0 1.0 1.01";
543        emlig1->add_condition(condition1a);
544        //emlig2->add_condition(condition1b);
545
546        vec condition2a = "-0.3 1.7 1.5";
547        //vec condition2b = "-1.0 1.0 1.0";
548        emlig1->add_condition(condition2a);
549        //emlig2->add_condition(condition2b);
550
551        vec condition3a = "0.5 -1.01 1.0";
552        //vec condition3b = "0.5 -1.01 1.0";
553
554        emlig1->add_condition(condition3a);
555        //emlig2->add_condition(condition3b);   
556
557        vec condition4a = "-0.5 -1.0 1.0";
558        //vec condition4b = "-0.5 -1.0 1.0";   
559
560        emlig1->add_condition(condition4a);
561        //cout << "************************************************" << endl;
562        //emlig2->add_condition(condition4b);
563        //cout << "************************************************" << endl;
564       
565        //cout << emlig1->minimal_vertex->get_coordinates();
566       
567        //emlig1->remove_condition(condition3a);
568        //emlig1->step_me(0);
569        //emlig1->remove_condition(condition2a);
570        //emlig1->remove_condition(condition1a);
571        //emlig1->remove_condition(condition5);
572       
573
574        //emlig1->step_me(0);
575        //emlig2->step_me(0);
576       
577
578        // DA SE POUZIT PRO VYPIS DO SOUBORU
579        // emlig1->step_me(0);
580
581        //emlig1->remove_condition(condition1);
582       
583       
584
585       
586       
587        /*
588        for(int i = 0;i<100;i++)
589        {
590                cout << endl << "Step:" << i << endl;           
591
592                double condition[emlig_size+1];         
593
594                for(int k = 0;k<=emlig_size;k++)
595                {
596                        condition[k] = (rand()-RAND_MAX/2)/1000.0;             
597                }
598                       
599
600                vec* condition_vec = new vec(condition,emlig_size+1);
601                emlig1->add_condition(*condition_vec);
602
603                /*
604                for(polyhedron* toprow_ref = emlig1->statistic.rows[emlig_size]; toprow_ref != emlig1->statistic.end_poly; toprow_ref = toprow_ref->next_poly)
605                {
606                        cout << ((toprow*)toprow_ref)->probability << endl;
607                }
608                */
609                /*
610                cout << emlig1->statistic_rowsize(emlig_size) << endl << endl;
611       
612                /*
613                if(i-emlig1->number_of_parameters >= 0)
614                {
615                        pause(30);
616                }
617                */
618
619                // emlig1->step_me(i);
620               
621                /*
622                vector<int> sizevector;
623                for(int s = 0;s<=emlig1->number_of_parameters;s++)
624                {
625                        sizevector.push_back(emlig1->statistic_rowsize(s));
626                }
627                */
628        //}
629   
630
631
632       
633        /*
634        emlig1->step_me(1);
635
636        vec condition = "2.0 0.0 1.0"; 
637
638        emlig1->add_condition(condition);
639
640        vector<int> sizevector;
641        for(int s = 0;s<=emlig1->number_of_parameters;s++)
642        {
643                sizevector.push_back(emlig1->statistic_rowsize(s));
644        }
645
646        emlig1->step_me(2);
647
648        condition = "2.0 1.0 0.0";
649
650        emlig1->add_condition(condition);
651
652        sizevector.clear();
653        for(int s = 0;s<=emlig1->number_of_parameters;s++)
654        {
655                sizevector.push_back(emlig1->statistic_rowsize(s));
656        }
657        */
658
659        return 0;
660}
661
662
Note: See TracBrowser for help on using the browser.