root/applications/robust/main.cpp @ 1390

Revision 1390, 15.6 kB (checked in by sindj, 13 years ago)

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