root/applications/robust/mainSamples.cpp

Revision 1397, 17.7 kB (checked in by sindj, 13 years ago)

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