root/applications/robust/main.cpp @ 1405

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