GeniusTrader/Analyzers/Process.pm untested

filter: Statementstmt 0.0% 0 / 587 Branchbran 0.0% 0 / 226 Conditioncond 0.0% 0 / 122 MC/DCmcdc 0.0% 0 / 79 Subroutinesub 0.0% 0 / 45 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 1084 CC 114 SCAR 46.4
CC
114
Cov
0%
set_code
272.0
set
210.0
btest
182.0
CRAP 103.4
1 package Finance::GeniusTrader::Analyzers::Process;
2  
3 # Copyright 2004 Oliver Bossert
4 # This file is distributed under the terms of the General Public License
5 # version 2 or (at your option) any later version.
6  
7 use strict;
8  
9 use Finance::GeniusTrader::ArgsTree;
10 use Finance::GeniusTrader::Prices;
11 use Finance::GeniusTrader::Calculator;
12 use Finance::GeniusTrader::Conf;
13 use Finance::GeniusTrader::Eval;
14 use Finance::GeniusTrader::BackTest::Spool;
15 use Finance::GeniusTrader::BackTest;
16 use Finance::GeniusTrader::Portfolio;
17 use Finance::GeniusTrader::PortfolioManager;
18 use Finance::GeniusTrader::DateTime;
19 use Finance::GeniusTrader::Tools qw(:conf);
20 use Finance::GeniusTrader::Analyzers::Report;
21  
22 use Compress::Zlib ;
23 use Data::Dumper;
24 use IO::Handle;
25  
26 use Finance::GeniusTrader::Brokers::InteractiveBrokers;
27 use Finance::GeniusTrader::Brokers::NoCosts;
28  
29 # Uncomment this to use PGPLOT instead of R:
30 # use PGPLOT;
31 # use Chart::Math::Axis;
32  
33 require Exporter;
34 our @ISA = qw(Exporter);
35 our @EXPORT = qw($term);
36 our $term;
37 our $myself;
38  
39 =head1 NAME
40  
41 Finance::GeniusTrader::Analyzers::Process
42  
43 =head1 DESCRIPTION
44  
45 This module offes all those functions that are needed by the analyzers
46 shell to interactively analyze and test portfolios.
47  
48 =head2 FUNCTIONS
49  
50 =over
51  
52 =item C<< Finance::GeniusTrader::Analyzers::Process->new() >>
53  
54 =cut
55  
56 ############################################################
57 sub new { # Generate a new Object
58 ############################################################
59 my $type = shift;
60 my $args = \@_;
61 my $class = ref($type) || $type;
62 my $self = {};
63 bless $self, $class;
64  
65 $self->{'db'} = create_standard_object("DB::" . Finance::GeniusTrader::Conf::get("DB::module"));
66  
67 $self->{'VERSION'} = "0.5";
68 %{$self->{'config'}} = ( 'code' => '',
69 'first' => 'auto',
70 'timeframe' => 'day',
71 'expert' => '1',
72 'last' => 'auto',
73 'full' => 0,
74 'broker' => Finance::GeniusTrader::Conf::get("Brokers::module"),
75 'system' => "Systems::Generic {S:Generic:CrossOverUp {I:SMA 20} {I:SMA 60}} " .
76 "{S:Generic:CrossOverDown {I:SMA 20} {I:SMA 60}}",
77 'cs' => "OppositeSignal",
78 'tf' => "OneTrade",
79 'mm' => [ 'Basic' ]
80 );
81 $self->set_code( $self->{'config'}{'code'} ) if (defined($term));
82  
83 %{$self->{'CMDS'}} = map { $_ => \&$_ }
84 qw(bye set load save calc calc_array licence license help p info btest report list source);
85  
86 if ( defined($term) && -r ".AnaShHistory" ) {
87 open IN, ".AnaShHistory";
88 while (<IN>) {
89 chomp;
90 $term->addhistory( $_ );
91 }
92 close IN;
93 }
94  
95 # In a later version the hole workspace should be restored:
96 # This code is not working due to the code references...
97 #
98 # if ( -r ".AnaShData" ) {
99 # my $gz = gzopen(".AnaShData", "rb");
100 # my $text = "";
101 # while ($gz->gzreadline($_) > 0) {
102 # $text .= $_;
103 # }
104 # my $VAR1;
105 # eval $text;
106 # if (! $@) {
107 # map { $self->{$_} => $VAR1->{$_} }
108 # qw(calc q first config pf );
109 # }
110 # }
111  
112 $myself = $self if ( $self->{'config'}{'expert'} == 1);
113  
114 return $self;
115 }
116  
117  
118 =item C<< Finance::GeniusTrader::Analyzers::Process->parse( $cmd ) >>
119  
120 This function parses the command $cmd. If the shell is set in expert
121 mod it tries first to map $cmd to an internat command and otherwise
122 evaluates it using eval.
123  
124 =cut
125  
126 ############################################################
127 sub parse {
128 ############################################################
129 no strict "vars";
130 my $self = shift;
131 my $cmd = shift;
132 $cmd =~ s/^\s*//;
133 $cmd =~ s/\s*$//;
134 return if ($cmd =~ /^\s*$/);
135 return if ($cmd =~ /^#/);
136 my ($func, $params) = split ' ', $cmd, 2;
137
138 my $erg = "";
139 if ( defined( $self->{'CMDS'}{$func} ) ) {
140 my @param = split /\s+/, $params;
141 $erg = $self->{'CMDS'}{$func}->($self, @param);
142 } else {
143 if ( $self->{'config'}{'expert'} == 1 ) {
144 eval ( $func . " " . $params );
145 print "Error: $@\n" if ($@);
146  
147 } else {
148 print "Command not found: '$func' ($params) \n";
149 }
150 }
151  
152 return $erg;
153 }
154  
155 =item C<< Finance::GeniusTrader::Analyzers::Process->bye() >>
156  
157 Exits the program after asking if the history should be stored.
158  
159 =cut
160  
161 ############################################################
162 sub bye {
163 ############################################################
164 my $self;
165 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
166 $self = shift;
167 } else {
168 $self = $myself;
169 }
170 print "Exiting Olf's Analyzer...\n";
171 if ( defined( $term ) ) {
172 my $leave = 0;
173 while ($leave != 1) {
174 print "Save settings? [Y/n]: ";
175 my $answer = <>;
176 chomp( $answer );
177 if ( lc($answer) eq "y" || lc($answer) eq "" ) {
178 open OUT, ">.AnaShHistory";
179 my @history = $term->GetHistory();
180 @history = splice @history, ($#history-100), 100 if ($#history > 100);
181 print OUT join("\n", @history ) . "\n";
182 close OUT;
183  
184 # Later some code like this one should store the hole workspace:
185 #
186 # open OUT, ">.AnaShData";
187 # my $buffer = Compress::Zlib::memGzip( Dumper( $self ) );
188 # print OUT $buffer;
189 # close OUT;
190  
191 $leave = 1;
192 } elsif ( lc($answer) eq "n" ) {
193 $leave = 1;
194 } else {
195 print "Please answer yes or no!\n";
196 }
197 }
198 }
199 $self->disconnect();
200 exit;
201 }
202  
203 =item C<< Finance::GeniusTrader::Analyzers::Process->set( [ $key ] ) >>
204  
205 Set a configuration-parameter. If key is not given, the list of
206 parameters is given. The variable key consits of the real key and the
207 value separated by a space. If you want to set an array, you can
208 either use key[x] to teh xth element or +key to add the value to the
209 array.
210  
211 =cut
212  
213 ############################################################
214 sub set {
215 ############################################################
216 my $self;
217 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
218 $self = shift;
219 } else {
220 $self = $myself;
221 }
222  
223 my $nb;
224 my $skey = shift;
225 my $val = join(" ", @_);
226 if ($skey =~ /(\w+)\[(\d+)\]/) {
227 $skey = $1;
228 $nb = $2;
229 }
230  
231 if ( !defined($skey) ) {
232 print "Settings:\n";
233 foreach my $key ( keys %{$self->{'config'}} ) {
234 if ( ref($self->{'config'}{$key}) =~ /ARRAY/ ) {
235 for my $i (0..$#{$self->{'config'}{$key}} ) {
236 print " $key " . "[" . $i . "] => " . $self->{'config'}{$key}->[$i] . "\n";
237 }
238 } else {
239 print " $key => " . $self->{'config'}{$key} . "\n";
240 }
241 }
242 } else {
243 # Add value
244 if ( $skey =~ /^\+(.*)/ ) {
245 $skey = $1;
246 if ( ref($self->{'config'}{$skey}) =~ /ARRAY/ ) {
247 push @{$self->{'config'}{$skey}}, $val;
248 } else {
249 if ( defined($self->{'config'}{$skey}) &&
250 $self->{'config'}{$skey} ne "" ) {
251 my $erg = $self->{'config'}{$skey};
252 undef( $self->{'config'}{$skey} );
253 push @{$self->{'config'}{$skey}}, $erg;
254 }
255 push @{$self->{'config'}{$skey}}, $val;
256 }
257 } else {
258 if ( defined($nb) ) {
259 if ($val =~ /^\s*$/ ) {
260 splice @{$self->{'config'}{$skey}}, $nb, 1;
261 } else {
262 $self->{'config'}{$skey}->[$nb] = $val;
263 }
264 } else {
265 $self->{'config'}{lc($skey)} = $val;
266 undef ($self->{'config'}{lc($skey)}) if ( $val eq "" );
267 if ( lc($skey) eq "code" ) {
268 unless ( defined( $self->{'config'}{'noloadcode'} ) &&
269 $self->{'config'}{'noloadcode'} == 1 ) {
270 $self->set_code( $val, 1 );
271 }
272 }
273 $myself = $self if (lc($skey) eq "expert" && !defined($myself) && $val == 1 );
274 }
275 }
276 }
277 return "";
278 }
279  
280 =item C<< Finance::GeniusTrader::Analyzers::Process->set_code( $code ) >>
281  
282 Set the code and do the necessary initialization-stuff.
283  
284 =cut
285  
286 ############################################################
287 sub set_code {
288 ############################################################
289 my $self;
290 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
291 $self = shift;
292 } else {
293 $self = $myself;
294 }
295 my $param = shift;
296 my $chngtime = shift;
297 $chngtime = 0 if (!defined($chngtime));
298  
299 $self->{'config'}{'code'} = $param;
300 $self->{'q'} = $self->{'db'}->get_prices($self->{'config'}{'code'});
301 $self->{'calc'} = Finance::GeniusTrader::Calculator->new( $self->{'q'} );
302 $self->{'calc'}->set_code($self->{'config'}{'code'});
303  
304 if ($self->{'config'}{'timeframe'} ne "day") {
305 if (! $self->{'calc'}->set_current_timeframe(
306 Finance::GeniusTrader::DateTime::name_to_timeframe($self->{'config'}{'timeframe'})) ) {
307 warn "Can't create « ".$self->{'config'}{'timeframe'}." » timeframe ...\n";
308 }
309 }
310  
311 $self->{'c'} = $self->{'calc'}->prices->count;
312  
313 return if ($chngtime == 0);
314  
315 $self->{'last'} = $self->{'c'} - 1;
316 $self->{'first'} = $self->{'c'} - 2 * Finance::GeniusTrader::DateTime::timeframe_ratio($YEAR,
317 $self->{'calc'}->current_timeframe);
318  
319 $self->{'first'} = 0 if ($self->{'config'}{'full'});
320 $self->{'first'} = 0 if ($self->{'first'} < 0);
321  
322 if ( $self->{'config'}{'first'} ne "auto" ) {
323 my $date = $self->{'calc'}->prices->find_nearest_following_date( $self->{'config'}{'first'} );
324 $self->{'first'} = $self->{'calc'}->prices->date($date);
325 } elsif ( $self->{'config'}{'first'} =~ /^\d+$/ ) {
326 $self->{'first'} = $self->{'config'}{'first'};
327 $self->{'first'} = 0 if ($self->{'first'} < 0);
328 $self->{'first'} = $self->{'c'} - 1 if ($self->{'first'} >= $self->{'c'});
329 }
330  
331 if ( $self->{'config'}{'last'} ne "auto" ) {
332 my $date = $self->{'calc'}->prices->find_nearest_preceding_date($self->{'config'}{'last'});
333 $self->{'last'} = $self->{'calc'}->prices->date($date);
334 } elsif ( $self->{'config'}{'last'} =~ /^\d+$/ ) {
335 $self->{'last'} = $self->{'config'}{'last'};
336 $self->{'last'} = 0 if ($self->{'last'} < 0);
337 $self->{'last'} = $self->{'c'} - 1 if ($self->{'last'} >= $self->{'c'});
338 }
339  
340 $self->{'calc'}->{'first'} = $self->{'first'};
341 $self->{'calc'}->{'last'} = $self->{'last'};
342 }
343  
344 =item C<< Finance::GeniusTrader::Analyzers::Process->load( $sys, $dir, $code ) >>
345  
346 Loads $sys from $dir and $code (optional).
347  
348 =cut
349  
350 ############################################################
351 sub load {
352 ############################################################
353 my $self;
354 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
355 $self = shift;
356 } else {
357 $self = $myself;
358 }
359  
360 my ($sys, $dir, $code) = @_;
361 if ( defined($code) ) {
362 $self->set_code ( $code );
363 } else {
364 $self->set_code( $self->{'config'}{'code'} );
365 }
366  
367 # Load a single portfolio
368 if ( -e $sys ) {#=~ /^\./ || $sys =~ /^\// ) {
369 $self->{'pf'} = Finance::GeniusTrader::Portfolio->create_from_file($sys);
370 my $name = Finance::GeniusTrader::Conf::get("Brokers::module");
371 $self->{'pf'}->{'broker'} = create_standard_object(split (/\s+/, "Brokers::$name"));
372 $self->{'calc'}->{'pf'} = $self->{'pf'};
373  
374 my @dates = sort {$a cmp $b} keys %{$self->{'pf'}->{'evaluation_history'}};
375 @dates = grep { ref($_) !~ /ARRAY/ } @dates;
376 my $dat = $self->{'calc'}->prices->find_nearest_date( $dates[0] );
377 $self->{'first'} = $self->{'calc'}->prices->date($dat);
378 $dat = $self->{'calc'}->prices->find_nearest_date( $dates[$#dates] );
379 $self->{'last'} = $self->{'calc'}->prices->date($dat);
380  
381 return;
382 }
383  
384 # Load a portfolio from a backtest-dir
385 my $directory;
386 if (defined($dir) && $dir) {
387 $directory = $dir;
388 } elsif (Finance::GeniusTrader::Conf::get("BackTest::Directory")) {
389 $directory = Finance::GeniusTrader::Conf::get("BackTest::Directory");
390 }
391  
392 if (! (defined($directory) && $sys)) {
393 die "Bad syntax for BackTestPortfolio(sysname, directory) !\n";
394 }
395
396 my $spool = Finance::GeniusTrader::BackTest::Spool->new($directory);
397  
398 my $index = $spool->{'index'};
399 $self->{'pf'}->{'name'} = $sys;
400 foreach my $a ( keys %{$index->{'alias'}} ) {
401 $self->{'pf'}->{'name'} = $index->{'alias'}{$a} if ($a eq $sys);
402 }
403 $self->{'pf'} = $spool->get_portfolio($self->{'pf'}->{'name'},
404 $self->{'config'}{'code'});
405 $self->{'pf'}->{'name'} = $sys if ( $self->{'pfname'} eq "" );
406  
407 foreach my $a ( keys %{$index->{'alias'}} ) {
408 $self->{'pf'}->{'name'} = $a if ($index->{'alias'}{$a} eq $sys);
409 }
410  
411 my $name = $self->{'pf'}->{'broker'}->{'names'}[0];
412 $name =~ s/[\[\],]/ /g;
413 $name = Finance::GeniusTrader::Conf::get("Brokers::module") if ($name =~ /^\s*$/);
414 $self->{'pf'}->{'broker'} = create_standard_object(split (/\s+/, "Brokers::$name"));
415  
416 $self->{'calc'}->{'pf'} = $self->{'pf'};
417  
418 my @dates = sort {$a cmp $b} keys %{$self->{'pf'}->{'evaluation_history'}};
419 @dates = grep { ref($_) !~ /ARRAY/ } @dates;
420 my $dat = $self->{'calc'}->prices->find_nearest_date( $dates[0] );
421 $self->{'first'} = $self->{'calc'}->prices->date($dat);
422 $dat = $self->{'calc'}->prices->find_nearest_date( $dates[$#dates] );
423 $self->{'last'} = $self->{'calc'}->prices->date($dat);
424  
425 my $stats = $spool->get_stats($sys, $self->{'config'}{'code'});
426 $self->{'analysis'}->{'portfolio'} = $self->{'pf'};
427 $self->{'analysis'}->{'real'}{'std_performance'} = $stats->[0];
428 $self->{'analysis'}->{'real'}{'performance'} = $stats->[1];
429 $self->{'analysis'}->{'real'}{'max_draw_down'} = $stats->[2];
430 $self->{'analysis'}->{'real'}{'std_buyandhold'} = $stats->[3];
431 $self->{'analysis'}->{'real'}{'buyandhold'} = $stats->[4];
432  
433 $self->{'calc'}->{'first'} = $self->{'first'};
434 $self->{'calc'}->{'last'} = $self->{'last'};
435  
436 return "" unless(defined($term));
437 return "Loaded Portfolio $sys...\n";
438 }
439  
440 =item C<< Finance::GeniusTrader::Analyzers::Process->save( $sys, $dir ) >>
441  
442 Saves the portfolio with name $sys to directory $dir.
443  
444 =cut
445  
446 ############################################################
447 sub save {
448 ############################################################
449 my $self;
450 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
451 $self = shift;
452 } else {
453 $self = $myself;
454 }
455 # my $self = shift;
456 my ($alias, $dir) = @_;
457 $dir = "./" if ( !defined($dir) );
458 delete( $self->{'analysis'}->{'portfolio'}->{objects} )
459 if defined( $self->{'analysis'}->{'portfolio'}->{objects} );
460  
461 my $bkt_spool = Finance::GeniusTrader::BackTest::Spool->new($dir);
462 my $stats = [ $self->{'analysis'}->{'real'}{'std_performance'},
463 $self->{'analysis'}->{'real'}{'performance'},
464 $self->{'analysis'}->{'real'}{'max_draw_down'},
465 $self->{'analysis'}->{'real'}{'std_buyandhold'},
466 $self->{'analysis'}->{'real'}{'buyandhold'}
467 ];
468  
469 $alias = $self->{'config'}{'alias'} if ( !defined($alias) );
470 $alias = $self->{'sys_manager'}->alias_name if ( !defined($alias) );
471 my $name = $alias;
472  
473 $name = $self->{'pf'}->{'name'} if ( defined($self->{'pf'}->{'name'}) &&
474 $self->{'pf'}->{'name'} ne "" );
475 $name = $self->{'sys_manager'}->{'name'} if (defined($self->{'sys_manager'}) &&
476 $self->{'sys_manager'}->{'name'} ne "");
477  
478 $bkt_spool->add_alias_name($name, $alias); #self->{'sys_manager'}->get_name(), $alias);
479 $bkt_spool->add_results($name, $self->{'config'}{'code'}, $stats,
480 $self->{'analysis'}->{'portfolio'}, $self->{'config'}{'code'} );
481 $bkt_spool->sync();
482  
483 return "" unless(defined($term));
484 return "Saved $alias in $dir...\n";
485 }
486  
487 =item C<< Finance::GeniusTrader::Analyzers::Process->list( $dir ) >>
488  
489 Lists the systems in directory $dir.
490  
491 =cut
492  
493 ############################################################
494 sub list {
495 ############################################################
496 my $self;
497 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
498 $self = shift;
499 } else {
500 $self = $myself;
501 }
502 my $dir = shift;
503 my $bkt_spool = Finance::GeniusTrader::BackTest::Spool->new($dir);
504 my $list = $bkt_spool->list_available_data();
505 if ( wantarray() ) {
506 return %{$list};
507 } else {
508 my $erg = "";
509 foreach my $key ( %{$list} ) {
510 next if ( ref($key) =~ /ARRAY/ );
511 $erg .= " ==> " . $key . "\n";
512 if ( $bkt_spool->get_alias_name( $key ) ) {
513 $erg .= " Alias: " . $bkt_spool->get_alias_name( $key ) . "\n";
514 }
515 foreach my $code ( @{$list->{$key}} ) {
516 $erg .= " " x 5 . " --> " . $code . "\n";
517 }
518 }
519 return $erg;
520 }
521 }
522  
523 =item C<< Finance::GeniusTrader::Analyzers::Process->btest() >>
524  
525 start the backtest.
526  
527 =cut
528  
529 ############################################################
530 sub btest {
531 ############################################################
532 my $self;
533 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
534 $self = shift;
535 } else {
536 $self = $myself;
537 }
538 # If prepare is set, only prepare Backtest - don't test!
539 my $prepare = shift;
540 $prepare = 0 if (!defined($prepare));
541  
542 my $start = time();
543  
544 $self->{'pf_manager'} = Finance::GeniusTrader::PortfolioManager->new;
545 $self->{'sys_manager'} = Finance::GeniusTrader::SystemManager->new;
546  
547 # Clear calc-object
548 $self->set_code( $self->{'config'}{'code'}, 1 ); #{'calc'} = Finance::GeniusTrader::Calculator->new( $self->{'q'} );
549  
550 # Set up the System or alias
551 if ( defined($self->{'config'}{'system'}) && $self->{'config'}{'system'} ne "" ) {
552 $self->{'sys_manager'}->set_system( create_standard_object( split (/\s+/, $self->{'config'}{'system'})) );
553 } elsif ( defined($self->{'config'}{'alias'}) && $self->{'config'}{'alias'} ne "" ) {
554 my $alias = $self->{'config'}{'alias'};
555 my $sysname = resolve_alias($alias);
556 if (defined($sysname) && $sysname) {
557 $self->{'sys_manager'}->setup_from_name($sysname);
558 $self->{'pf_manager'}->setup_from_name($sysname);
559 } else {
560 return "ERROR: Could not resolve alias.\n";
561 }
562 } else {
563 return "ERROR: No alias or system given!\n";
564 }
565  
566 # Add Money Management
567 if ( ref($self->{'config'}{'mm'}) =~ /ARRAY/ ) {
568 foreach my $mm ( @{$self->{'config'}{'mm'}} ) {
569 $self->{'pf_manager'}->add_money_management_rule( create_standard_object(split (/\s+/, "MoneyManagement::$mm")));
570 }
571 } else {
572 $self->{'pf_manager'}->add_money_management_rule( create_standard_object(split (/\s+/, "MoneyManagement::" . $self->{'config'}{'mm'})));
573 }
574 $self->{'pf_manager'}->default_money_management_rule( create_standard_object("MoneyManagement::Basic") );
575 $self->{'pf_manager'}->finalize;
576  
577 # Add Order-Factories
578 if ( defined($self->{'config'}{'of'}) && $self->{'config'}{'of'} ne "" ) {
579 $self->{'sys_manager'}->set_order_factory( create_standard_object(split (/\s+/, "OrderFactory::" . $self->{'config'}{'of'})));
580 }
581  
582 # Add Tradefilters
583 if ( ref($self->{'config'}{'tf'}) =~ /ARRAY/ ) {
584 foreach my $tf ( @{$self->{'config'}{'tf'}} ) {
585 $self->{'sys_manager'}->add_trade_filter( create_standard_object(split (/\s+/, "TradeFilters::$tf")));
586 }
587 } elsif ( defined($self->{'config'}{'tf'}) && $self->{'config'}{'tf'} ne "" ) {
588 $self->{'sys_manager'}->add_trade_filter( create_standard_object(split (/\s+/, "TradeFilters::" . $self->{'config'}{'tf'})));
589 }
590  
591 # Add Closingstrategies
592 if ( ref($self->{'config'}{'cs'}) =~ /ARRAY/ ) {
593 foreach my $cs ( @{$self->{'config'}{'cs'}} ) {
594 $self->{'sys_manager'}->add_position_manager( create_standard_object(split (/\s+/, "CloseStrategy::$cs")));
595 }
596 } else {
597 $self->{'sys_manager'}->add_position_manager( create_standard_object(split (/\s+/, "CloseStrategy::" . $self->{'config'}{'cs'})));
598 }
599  
600 $self->{'sys_manager'}->finalize;
601  
602 $self->{'analysis'} = backtest_single($self->{'pf_manager'},
603 $self->{'sys_manager'},
604 $self->{'config'}{'broker'},
605 $self->{'calc'},
606 $self->{'first'},
607 $self->{'last'}) unless ($prepare == 1);
608  
609 $self->{'pf'} = $self->{'analysis'}->{'portfolio'};
610 $self->{'calc'}->{'pf'} = $self->{'pf'};
611  
612 $self->{'pf'}->{'name'} = $self->{'sys_manager'}->get_name();
613  
614 return "" unless (defined($term));
615 return "Tested ... ok in " . (time()-$start) . " seconds\n";
616 }
617  
618  
619 =item C<< Finance::GeniusTrader::Analyzers::Process->calc($args) >>
620  
621 Calculates the expression given as argument(s).
622  
623 =cut
624  
625 ############################################################
626 sub calc {
627 ############################################################
628 my $self;
629 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
630 $self = shift;
631 } else {
632 $self = $myself;
633 }
634 my $args = Finance::GeniusTrader::ArgsTree->new( @_ );
635  
636 my $nb = $args->get_nb_args();
637 my $expr = "";
638 for (my $n = 1; $n <= $nb; $n++) {
639 if ($args->is_constant($n)) {
640 $expr .= " " . $args->get_arg_constant($n);
641 } else {
642 my $ob = $args->get_arg_object($n);
643  
644 $ob->calculate($self->{'calc'}, $self->{'last'})
645 if ( $ob->isa("Finance::GeniusTrader::Indicators") );
646  
647 my $val = $args->get_arg_values($self->{'calc'}, $self->{'last'}, $n);
648 return if (! defined($val));
649 $expr .= " $val";
650 }
651 }
652 my $res = undef;
653 eval "\$res = $expr";
654 if ($@) {
655 warn "$@ : $expr";
656 return;
657 }
658  
659 return $res unless (defined($term));
660 return $res . "\n";
661 }
662  
663 =item C<< Finance::GeniusTrader::Analyzers::Process->calc_array($arg1, $arg2, ...) >>
664  
665 Calculates each array and prints out/returns a list.
666  
667 The arry should have the same length.
668  
669 =cut
670  
671 ############################################################
672 sub calc_array {
673 ############################################################
674 my $self;
675 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
676 $self = shift;
677 } else {
678 $self = $myself;
679 }
680 # my $self = shift;
681 my $param = join(" ", @_ );
682  
683 my $args = Finance::GeniusTrader::ArgsTree->new( $param );
684 my $nb = $args->get_nb_args();
685 my $expr = "";
686 my $val;
687 if ( $nb == 1 ) {
688 $val = $args->get_arg_values($self->{'calc'}, $self->{'last'}, 1);
689 } else {
690 $val = ();
691 push @{$val}, $args->get_arg_values($self->{'calc'}, $self->{'last'}, 1);
692 for (my $n = 2; $n <= $nb; $n++) {
693 push @{$val}, $args->get_arg_values($self->{'calc'}, $self->{'last'}, $n);
694 }
695 }
696 return if (! defined($val));
697 if ( ref($val) =~ /ARRAY/ ) {
698 if (wantarray()) {
699 return @{$val};
700 } else {
701 my $erg = "";
702 if ( $nb == 1 ) {
703 foreach my $i (0..$#{$val}) {
704 if (defined($term)) {
705 $erg .= " [" . sprintf("%4d", $i) . "] " unless (defined($self->{'config'}->{'nonb'}) &&
706 $self->{'config'}->{'nonb'} == 1);
707 } else {
708 $erg .= sprintf("%04d", $i) . "\t" unless (defined($self->{'config'}->{'nonb'}) &&
709 $self->{'config'}->{'nonb'} == 1);
710 }
711 $erg .= $val->[$i] . "\n";
712 }
713 } else {
714 $erg .= "Number\t";
715 for (my $n = 1; $n <= $nb; $n++) {
716 #$erg .= $args->get_arg_names($n) . "\t";
717 $erg .= $args->get_arg_object($n)->get_name(0) . "\t";
718 }
719 $erg .= "\n";
720 foreach my $i (0..$#{$val->[0]}) {
721 if (defined($term)) {
722 $erg .= " [" . sprintf("%4d", $i) . "] " unless (defined($self->{'config'}->{'nonb'}) &&
723 $self->{'config'}->{'nonb'} == 1);
724  
725 } else {
726 $erg .= sprintf("%04d", $i) . "\t" unless (defined($self->{'config'}->{'nonb'}) &&
727 $self->{'config'}->{'nonb'} == 1);
728 }
729  
730 foreach my $j (0..$#{$val}) {
731 $erg .= $val->[$j]->[$i] . "\t";
732 }
733 $erg .= "\n";
734 }
735 }
736 return $erg;
737 }
738 }
739 return $val;
740 }
741  
742 =item C<< Finance::GeniusTrader::Analyzers::Process->p($arg) >>
743  
744 Prints out the string $arg and replaces the variable elements
745  
746 =cut
747  
748 ############################################################
749 sub p {
750 ############################################################
751 my $self;
752 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
753 $self = shift;
754 } else {
755 $self = $myself;
756 }
757 # my $self = shift;
758 # my $param = shift;
759 my $args = Finance::GeniusTrader::ArgsTree->new( @_ ); #split /\s+/, $param );
760  
761 my $nb = $args->get_nb_args();
762 my $expr = "";
763 for (my $n = 1; $n <= $nb; $n++) {
764 if ($args->is_constant($n)) {
765 $expr .= " " . $args->get_arg_constant($n);
766 } else {
767 my $val = $args->get_arg_values($self->{'calc'}, $self->{'last'}, $n);
768 return if (! defined($val));
769 $expr .= " $val";
770 }
771 }
772 return $expr . "\n";
773 }
774  
775 =item C<< Finance::GeniusTrader::Analyzers::Process->help() >>
776  
777 Print the help screen
778  
779 =cut
780  
781 ############################################################
782 sub help {
783 ############################################################
784 return <<HELP
785  
786 Anashell support the follwing commands:
787 set [name] [value] - Without parameters: Displays settings.
788 With parameters: Set name to value.
789 set +name <value> - Adds value to the array name
790 set name[3] <value> - Sets 3rd element of name to value
791 Element is deleted if value == ''
792  
793 btest - Run backtest with given parameters.
794 save <sys> [dir] - Save Portfolio with alias sys to dir.
795 load <sys> [dir] - Load Portfolio for alias sys from dir.
796 list <dir> - Lists the Portfolios in directory dir.
797  
798 calc <args> - Calculate the value of args
799 calc_array <args> - Calculate an array (or multiple arrays
800 of the same size)
801 p <args> - Print args by replacing variables
802  
803 report <file> - Prints a report for the current
804 portfolio by using file as template.
805  
806 help - This help
807 licence - Show licence
808 bye - Leave program
809  
810  
811 Only available in expert-mode (set expert 1):
812 r_hist( <array-ref> ) - Displays a histogram of an array by using
813 the program R (www.r-project.org)
814 r_bar( <array-ref> ) - Displays an barplot an array.
815 r_corr( <ar1>,<ar2> ) - Display a correlation on array-ref ar1
816 and array-ref ar2.
817  
818 HELP
819 }
820  
821 =item C<< Finance::GeniusTrader::Analyzers::Process->licence() >>
822  
823 Print the licence
824  
825 =cut
826  
827 ############################################################
828 sub licence {
829 ############################################################
830 license();
831 }
832  
833 =item C<< Finance::GeniusTrader::Analyzers::Process->license() >>
834  
835 Prints the license
836  
837 =cut
838  
839 ############################################################
840 sub license {
841 ############################################################
842 return <<GPL
843  
844 This program is free software; you can redistribute it and/or
845 modify it under the terms of the GNU General Public License
846 as published by the Free Software Foundation; either version 2
847 of the License, or any later version.
848  
849 This program is distributed in the hope that it will be useful,
850 but WITHOUT ANY WARRANTY; without even the implied warranty of
851 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
852 GNU General Public License for more details.
853  
854 You should have received a copy of the GNU General Public License
855 along with this program; if not, write to the
856  
857 Free Software Foundation, Inc., 59 Temple Place - Suite 330
858 Boston, MA 02111-1307, USA.
859  
860 or via Internet: http://www.gnu.org/copyleft/gpl.html
861  
862 GPL
863 }
864  
865 =item C<< Finance::GeniusTrader::Analyzers::Process->disconnect() >>
866  
867 Disconnect from database.
868  
869 =cut
870  
871 ############################################################
872 sub disconnect {
873 ############################################################
874 my $self;
875 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
876 $self = shift;
877 } else {
878 $self = $myself;
879 }
880 # my $self = shift;
881 $self->{'db'}->disconnect();
882 }
883  
884 =item C<< Finance::GeniusTrader::Analyzers::Process->info() >>
885  
886 Prints a small information shown at the start of anashell.
887  
888 =cut
889  
890 ############################################################
891 sub info {
892 ############################################################
893 my $self;
894 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
895 $self = shift;
896 } else {
897 $self = $myself;
898 }
899 # my $self = shift;
900 my $erg = "";
901 $erg .= "\n Anashell : Copyright 2004 Oliver Bossert\n";
902 $erg .= " Version: " . $self->{'VERSION'} . "\n\n";
903 $erg .= " Anashell is free software and comes with ABSOLUTE NO WARRANTY\n";
904 $erg .= " You are welcome to redistribute it under certain conditions.\n";
905 $erg .= " type licence or license for distribution details.\n\n";
906 $erg .= " Type bye to leave the program and help for help.\n\n";
907 return $erg;
908 }
909  
910 =item C<< Finance::GeniusTrader::Analyzers::Process->pg_hist() >>
911  
912 Uncomment this function to plot histograms with pgplot.
913  
914 =cut
915  
916 ############################################################
917 sub pg_hist {
918 ############################################################
919 # my $self;
920 # if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
921 # $self = shift;
922 # } else {
923 # $self = $myself;
924 # }
925 # my $array = shift;
926 # my @sort = sort {$a <=> $b} @{$array};
927  
928 # my $Axis = Chart::Math::Axis->new();
929 # $Axis->add_data( @sort );
930 # my $min = $Axis->bottom;
931 # my $max = $Axis->top;
932  
933 # pgbegin(0,"/xserve",1,1);
934 # pgenv( $min, $max,
935 # 0,$#sort/2, 0, 0);
936 # pglabel('X','Y','Histrogram');
937  
938 # # background
939 # pgscr( 0, 1.0, 1.0, 1.0 );
940 # # foreground
941 # #pgscr( 1, 0.0, 0.0, 1.0 );
942  
943 # pghist($#sort, \@sort,
944 # $min, $max,
945 # $Axis->ticks, 1);
946  
947 # pgend;
948  
949 }
950  
951 =item C<< Finance::GeniusTrader::Analyzers::Process->r_hist( $array ) >>
952  
953 Plots a histogram using R (www.r-project.org) of the values of $array.
954  
955 =cut
956  
957 ############################################################
958 sub r_hist {
959 ############################################################
960 my $self;
961 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
962 $self = shift;
963 } else {
964 $self = $myself;
965 }
966 my $array = shift;
967  
968 my $add = "main=\"Histogram\"";
969 $add = $self->{'config'}{'radd'} if ($self->{'config'}{'radd'} ne "");
970  
971 my $prg = "/usr/bin/R --vanilla --no-readline -q";
972 my $pid = open(RPROC, "|-");
973 RPROC->autoflush();
974 if ( $pid ) {
975 print RPROC "png(\"/tmp/Rtmp.png\")\n";
976 print RPROC "x<-scan(file=\"\")\n";
977 print RPROC join("\n", @{$array}) . "\n\n";
978 print RPROC "hist(c(x), " . $add . ")\n";
979 close RPROC || die "Kiddie gone: $?";
980 } else {
981 exec $prg;
982 }
983  
984 system("xv /tmp/Rtmp.png &");
985  
986 # This works; but very unstable:
987 # use R;
988 # use RReferences;
989 # &R::initR("--silent");
990 # &R::library("RSPerl");
991 # &R::callWithNames("hist", {'', $array, 'main', 'Normals', 'xlab', ""});
992  
993 # This is unstable too:
994 # use R::Wrapper;
995 # hist( { x => $array, main => 'Test Plot' } );
996  
997 }
998  
999 =item C<< Finance::GeniusTrader::Analyzers::Process->r_bar( $array ) >>
1000  
1001 Generates a barplot in R by using the values of $array
1002  
1003 =cut
1004  
1005 ############################################################
1006 sub r_bar {
1007 ############################################################
1008 my $self;
1009 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
1010 $self = shift;
1011 } else {
1012 $self = $myself;
1013 }
1014 my $array = shift;
1015  
1016 my $add = "main=\"Barplot\"";
1017 $add = $self->{'config'}{'radd'} if ($self->{'config'}{'radd'} ne "");
1018  
1019 my $prg = "/usr/bin/R --vanilla --no-readline -q";
1020 my $pid = open(RPROC, "|-");
1021 RPROC->autoflush();
1022 if ( $pid ) {
1023 print RPROC "png(\"/tmp/Rtmp.png\")\n";
1024 print RPROC "x<-scan(file=\"\")\n";
1025 print RPROC join("\n", @{$array}) . "\n\n";
1026 print RPROC "barplot(c(x), " . $add . ")\n";
1027 close RPROC || die "Kiddie gone: $?";
1028 } else {
1029 exec $prg;
1030 }
1031  
1032 system("xv /tmp/Rtmp.png &");
1033 }
1034  
1035 =item C<< Finance::GeniusTrader::Analyzers::Process->r_corr( $arr1, $arr2 ) >>
1036  
1037 Plots the correlation of $arr1 and $arr2 in R.
1038  
1039 =cut
1040  
1041 ############################################################
1042 sub r_corr {
1043 ############################################################
1044 my $self;
1045 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
1046 $self = shift;
1047 } else {
1048 $self = $myself;
1049 }
1050 my $arrayx = shift;
1051 my $arrayy = shift;
1052  
1053 my $add = "main=\"Correlation\"";
1054 $add = $self->{'config'}{'radd'} if ($self->{'config'}{'radd'} ne "");
1055  
1056 my $prg = "/usr/bin/R --vanilla --no-readline -q";
1057 my $pid = open(RPROC, "|-");
1058 RPROC->autoflush();
1059 if ( $pid ) {
1060 print RPROC "png(\"/tmp/Rtmp.png\")\n";
1061 print RPROC "x<-scan(file=\"\")\n";
1062 print RPROC join("\n", @{$arrayx}) . "\n\n";
1063 print RPROC "y<-scan(file=\"\")\n";
1064 print RPROC join("\n", @{$arrayy}) . "\n\n";
1065 print RPROC "plot(y ~ x, " . $add . ")\n";
1066 print RPROC "abline(lm(y ~ x), col=\"red\")\n";
1067 print RPROC "summary(lm(y ~ x))\n";
1068 close RPROC || die "Kiddie gone: $?";
1069 } else {
1070 exec $prg;
1071 }
1072  
1073 system("xv /tmp/Rtmp.png &");
1074 }
1075  
1076 ############################################################
1077 sub r_hist2 {
1078 ############################################################
1079 my $self;
1080 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
1081 $self = shift;
1082 } else {
1083 $self = $myself;
1084 }
1085 my $array1 = shift;
1086 my $array2 = shift;
1087  
1088 my $add = "main=\"Histogramm-Comparison\"";
1089 $add = $self->{'config'}{'radd'} if ($self->{'config'}{'radd'} ne "");
1090  
1091 my $prg = "/usr/bin/R --vanilla --no-readline -q";
1092 my $pid = open(RPROC, "|-");
1093 RPROC->autoflush();
1094 if ( $pid ) {
1095 print RPROC "png(\"/tmp/Rtmp.png\")\n";
1096 print RPROC "t1<-scan(file=\"\")\n";
1097 print RPROC join("\n", @{$array1}) . "\n\n";
1098 print RPROC "t2<-scan(file=\"\")\n";
1099 print RPROC join("\n", @{$array2}) . "\n\n";
1100 print RPROC "par(mfrow=c(2,1))\n";
1101 print RPROC "h<-hist(t1)\n";
1102 print RPROC "hist(t2, breaks=h\$breaks)\n";
1103 close RPROC || die "Kiddie gone: $?";
1104 } else {
1105 exec $prg;
1106 }
1107  
1108 system("xv /tmp/Rtmp.png &");
1109 }
1110  
1111 =item C<< Finance::GeniusTrader::Analyzers::Process->report( $file ) >>
1112  
1113 Prints the report of the portfolio using $file as template.
1114  
1115 =cut
1116  
1117 ############################################################
1118 sub report {
1119 ############################################################
1120 my $self;
1121 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
1122 $self = shift;
1123 } else {
1124 $self = $myself;
1125 }
1126 my $filename = shift;
1127  
1128 my $rep = Finance::GeniusTrader::Analyzers::Report->new( $self );
1129 $rep->interpret( $filename );
1130 }
1131  
1132  
1133  
1134 ############################################################
1135 sub source {
1136 ############################################################
1137 my $self;
1138 if ( defined($_[0]) && ref($_[0]) =~ /Finance::GeniusTrader::Analyzers::Process/ ) {
1139 $self = shift;
1140 } else {
1141 $self = $myself;
1142 }
1143  
1144 my $file = shift;
1145 open F, $file;
1146 while (<F>) {
1147 chomp;
1148 $self->parse( $_ );
1149 }
1150 close F;
1151 }
1152  
1153 sub DESTROY {
1154 my $self = shift;
1155 # Destroy command references
1156 foreach ( keys %{$self->{'CMDS'}} ) {
1157 $self->{'CMDS'}{$_} = undef;
1158 }
1159  
1160 foreach my $key ( keys %{$self->{'config'}} ) {
1161 undef $self->{'config'}->{$key};
1162 }
1163 undef $self->{'analysis'};
1164 undef $self->{'calc'}->{'pf'};
1165 undef $self->{'calc'}->{'first'};
1166 undef $self->{'calc'}->{'last'};
1167 undef $self->{'calc'};
1168 undef $self->{'q'};
1169 undef $self->{'pf'};
1170 undef $self->{'pf_manager'};
1171 undef $self->{'sys_manager'};
1172 undef $myself;
1173 }
1174  
1175 =back
1176  
1177 =cut
1178  
1179 1;