GeniusTrader/Report.pm untested

filter: Statementstmt 0.0% 0 / 250 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 18 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 405 CC 50 SCAR 48.4
CC
50
Cov
0%
OpenPositions
272.0
PortfolioHTML
156.0
Portfolio
110.0
CRAP 126.2
1 package Finance::GeniusTrader::Report;
2  
3 # Copyright 2000-2002 Raphaƫl Hertzog, Fabien Fulhaber
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::Portfolio;
10 use Finance::GeniusTrader::CacheValues;
11 use Finance::GeniusTrader::BackTest::Spool;
12 use Finance::GeniusTrader::Eval;
13 use Finance::GeniusTrader::Prices;
14 use Finance::GeniusTrader::DateTime;
15  
16 # This is not very clean ... should probably find another
17 # system to let the user redirect the output
18 *OUT = *STDOUT;
19  
20 =head1 NAME
21  
22 Finance::GeniusTrader::Report - Generate visual report of common objects
23  
24 =head1 DESCRIPTION
25  
26 This modules provides various functions to dump to Finance::GeniusTrader::Report::OUT
27 (by default STDOUT) various objects in a nice formatted text.
28  
29 =over
30  
31 =item C<< Finance::GeniusTrader::Report::Portfolio($portfolio) >>
32  
33 Prints the content of a portfolio in text format.
34  
35 =cut
36 sub Portfolio {
37 my ($p, $detailed) = @_;
38  
39 $detailed = 0 if (! defined($detailed));
40
41 my $db = create_db_object();
42
43 print OUT "History of the portfolio :\n";
44 print OUT "--------------------------\n";
45 foreach my $position (@{$p->{'history'}})
46 {
47 if ($position->is_long)
48 {
49 print OUT "Long position";
50 } else {
51 print OUT "Short position";
52 }
53 my $name = $db->get_name($position->code);
54 if ($name) {
55 print OUT " (" . $position->id .") on $name (" . $position->code . ")";
56 } else {
57 print OUT " (" . $position->id .") on " . $position->code;
58 }
59 if ($detailed and $position->source)
60 {
61 print OUT " coming from " . $position->source;
62 }
63 print OUT "\n";
64 foreach my $order ($position->list_detailed_orders)
65 {
66 my $text = swrite(' @<<<<<<<<< @<<< @>>>>>> at @<<<<<<<<<',
67 $order->submission_date,
68 $order->is_buy_order ? "Buy" : "Sell",
69 $order->quantity,
70 sprintf("%.4f", $order->price));
71 print OUT "$text\n";
72 }
73 if ($detailed)
74 {
75 my $pstats = $position->stats($p);
76 my $diff = $pstats->{'sold'} - $pstats->{'bought'}
77 - $pstats->{'cost'};
78 my $variation = 0;
79 if ($position->is_long) {
80 $variation = ($pstats->{'bought'} !=0) ?
81 ($diff / $pstats->{'bought'}) : 0;
82 } else {
83 $variation = ($pstats->{'sold'} !=0) ?
84 ($diff / $pstats->{'sold'}) : 0;
85 }
86  
87 my $text = swrite('Result: @<<<<<< => @<<<<<<<',
88 sprintf("%.2f%%", $variation * 100),
89 sprintf("%.0f", $diff));
90 print OUT "$text\n\n";
91 }
92 }
93 }
94  
95 =item C<< Finance::GeniusTrader::Report::PortfolioHTML($portfolio) >>
96  
97 Prints the content of a portfolio in HTML format.
98  
99 =cut
100 sub PortfolioHTML {
101 my ($p, $detailed) = @_;
102  
103 $detailed = 0 if (! defined($detailed));
104
105 my $db = create_db_object();
106
107 print OUT "<h2>History of the portfolio</h2>\n";
108 print OUT "<table border='1' cellpadding='5' cellspacing='0'>\n";
109 print OUT "<tr><th>Trade #</th><th>Code</th><th>Type</th>";
110 if ($detailed) {
111 print OUT "<th>Source</th>";
112 }
113 print OUT "<th>Shares</th><th>Entry Date</th><th>Entry Price</th><th>Exit Date</th><th>Exit Price</th><th>Return</th><th>Duration</th></tr>\n";
114 foreach my $position (@{$p->{'history'}})
115 {
116 my $pstats = $position->stats($p);
117 my $diff = $pstats->{'sold'} - $pstats->{'bought'}
118 - $pstats->{'cost'};
119 my $variation = 0;
120 if ($position->is_long) {
121 $variation = ($pstats->{'bought'} !=0) ?
122 ($diff / $pstats->{'bought'}) : 0;
123 } else {
124 $variation = ($pstats->{'sold'} !=0) ?
125 ($diff / $pstats->{'sold'}) : 0;
126 }
127 my $bg = ($variation > 0 ) ? "bgcolor='#55FF55'" : "bgcolor='#FF5555'";
128 print OUT "<tr><td $bg>" . $position->id . "</td>";
129 my $name = $db->get_name($position->code);
130 if ($name) {
131 print OUT "<td $bg>" . $name . " - " . $position->code . "</td>";
132 } else {
133 print OUT "<td $bg>" . $position->code . "</td>";
134 }
135 if ($position->is_long)
136 {
137 print OUT "<td $bg>Long</td>";
138 } else {
139 print OUT "<td $bg>Short</td>";
140 }
141 if ($detailed)
142 {
143 print OUT "<td $bg>" . $position->source . "</td>";
144 }
145 my $n = 0;
146 my ($start_date, $start_price, $end_date, $end_price);
147 foreach my $order ($position->list_detailed_orders)
148 {
149 if ($n == 0)
150 {
151 print OUT "<td $bg>" . $order->quantity . "</td>";
152 $start_date = $order->submission_date;
153 $start_price = $order->price;
154 }
155 else
156 {
157 $end_date = $order->submission_date;
158 $end_price = $order->price;
159 }
160 $n++;
161 }
162 my $timeframe = $DAY;
163 if (defined($position->timeframe)) {
164 $timeframe = $position->timeframe;
165 }
166 my $duration = (Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $end_date) - Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $start_date)) / 86400;
167
168 printf OUT ("<td $bg>%s</td><td $bg>%.4f</td>", $start_date, $start_price);
169 printf OUT ("<td $bg>%s</td><td $bg>%.4f</td>", $end_date, $end_price);
170 printf OUT ("<td $bg>%.2f%%</td>", $variation * 100);
171 printf OUT ("<td $bg>%s</td>", $duration);
172 print OUT "</tr>\n";
173 }
174 print OUT "</table>\n";
175 }
176  
177 =item C<< Finance::GeniusTrader::Report::OpenPositions($portfolio, $detailed) >>
178  
179 Display the list of open positions.
180  
181 =cut
182 sub OpenPositions {
183 my ($p, $detailed) = @_;
184 my $db = create_db_object();
185 foreach my $position ($p->list_open_positions) {
186 if ($position->is_long)
187 {
188 print OUT "Long position";
189 } else {
190 print OUT "Short position";
191 }
192 my $name = $db->get_name($position->code);
193 if ($name) {
194 print OUT " (" . $position->id .") on $name (" . $position->code . ")";
195 } else {
196 print OUT " (" . $position->id .") on " . $position->code;
197 }
198 if ($detailed and $position->source)
199 {
200 print OUT " coming from " . $position->source;
201 }
202 print OUT "\n";
203 foreach my $order ($position->list_detailed_orders)
204 {
205 my $text = swrite(' @<<<<<<<<< @<<< @>>>>>> at @<<<<<<<<<',
206 $order->submission_date,
207 $order->is_buy_order ? "Buy" : "Sell",
208 $order->quantity,
209 sprintf("%.4f", $order->price));
210 print OUT "$text\n";
211 }
212 my $pstats = $position->stats($p);
213 my $sstats = { %{$pstats} };
214 my $prices;
215 if (! $db->has_code($position->code)) {
216 print "Code not available in database. No calculations done.\n\n";
217 next;
218 }
219 eval {
220 $prices = $db->get_last_prices($position->code, 1);
221 };
222 if ($@) {
223 print "Error while retrieving prices. No calculations done.\n\n";
224 next;
225 }
226 my $order = Finance::GeniusTrader::Portfolio::Order->new();
227 $order->set_quantity($position->quantity);
228 $order->set_type_limited();
229 $order->set_price($prices->at($prices->count() - 1)->[$CLOSE]);
230 if ($position->is_long) {
231 $order->set_sell_order;
232 $pstats->{'sold'} += $position->quantity * $order->price;
233 $sstats->{'sold'} += $position->quantity * $position->stop if defined($position->stop);
234 } else {
235 $order->set_buy_order;
236 $pstats->{'bought'} += $position->quantity * $order->price;
237 $sstats->{'bought'} += $position->quantity * $position->stop if defined($position->stop);
238 }
239 $pstats->{'costs'} += $p->get_order_cost($order);
240 $sstats->{'costs'} = $pstats->{'costs'};
241 my $diff = $pstats->{'sold'} - $pstats->{'bought'} - $pstats->{'cost'};
242 my $diff2 = $sstats->{'sold'} - $sstats->{'bought'} - $sstats->{'cost'};
243 my $variation = 0;
244 my $variation2 = 0;
245 if ($position->is_long) {
246 $variation = ($pstats->{'bought'} !=0) ? ($diff / $pstats->{'bought'}) : 0;
247 $variation2 = ($sstats->{'bought'} !=0) ? ($diff2 / $sstats->{'bought'}) : 0;
248 } else {
249 $variation = ($pstats->{'sold'} !=0) ? ($diff / $pstats->{'sold'}) : 0;
250 $variation2 = ($sstats->{'sold'} !=0) ? ($diff2 / $sstats->{'sold'}) : 0;
251 }
252  
253 my $text;
254 $text = swrite('Current: @<<<<<< (@<<<<<< => @<<<<<<<)',
255 sprintf("%.2f", $order->price),
256 sprintf("%.2f%%", $variation * 100),
257 sprintf("%.0f", $diff));
258 if (defined($position->stop)) {
259 $text .= swrite(' Stop: @<<<<<< (@<<<<<< => @<<<<<<<)',
260 sprintf("%.2f", $position->stop),
261 sprintf("%.2f%%", $variation2 * 100),
262 sprintf("%.0f", $diff2));
263 } else {
264 $text .= ' Stop: none';
265 }
266 print OUT "$text\n\n";
267 }
268 }
269 =item C<< Finance::GeniusTrader::Report::safe_sprintf($format, $value) >>
270  
271 Checks value is not a NaN, then calls sprintf.
272  
273 =cut
274  
275 sub safe_sprintf {
276 my ($format, $value) =@_;
277  
278 if ($value =~ /^NaN$/ || $value =~ /^NaNQ$/) {
279 sprintf("%s", $value);
280 } else {
281 sprintf($format, $value);
282 }
283 }
284  
285 =item C<< Finance::GeniusTrader::Report::PortfolioAnalysis($analysis) >>
286  
287 Pretty prints the results of the analysis of the portfolio.
288  
289 =cut
290 sub PortfolioAnalysis {
291 my ($a, $detailed) = @_;
292  
293 $detailed = 0 if (! defined($detailed));
294  
295 print OUT "Analysis of the portfolio (" .
296 $a->{'first_date'} . " / " . $a->{'last_date'} . ") :\n";
297 print OUT "-----------------------------------------------------\n";
298 my $format =
299 'Performance : @>>>>> (@>>>>>) Buy & Hold : @>>>>> (@>>>>>) () => by @<<<<<<<
300 MaxDrawDown : @>>>>> B&H MaxDrawDown : @>>>>>
301 Best performance : @>>>>> Worst performance : @>>>>>
302 Net gain : @>>>>>>>>>>>>> Gross gain :@>>>>>>>>>>>>>
303  
304 Trades statistics :
305 Number of trades : @>>>>> Trades/Year : @>>>>>>>>>>>
306 Number of gains : @>>>>>> Number of losses : @>>>>>> Win. ratio : @>>>>>>
307 Max consec. win : @>>>>>> Max consec. loss : @>>>>>> Expectancy : @>>>>>>
308 Average gain : @>>>>>>>>> Average loss : @>>>>>>>>>> Avg. perf : @>>>>>>
309 Biggest gain : @>>>>>>>>> Biggest loss : @>>>>>>>>>> Profit fac : @>>>>>>
310 Sum of gains : @>>>>>>>>> Sum of losses : @>>>>>>>>> Risk of ruin : @>>>>
311 ';
312 my $text = swrite($format,
313 ($a->{'performance'} > 10) ? safe_sprintf("%.0f%%", $a->{'performance'} * 100) : safe_sprintf("%.1f%%", $a->{'performance'} * 100),
314 safe_sprintf("%.1f%%", $a->{'std_performance'} * 100),
315 safe_sprintf("%.1f%%", $a->{'buyandhold'} * 100),
316 safe_sprintf("%.1f%%", $a->{'std_buyandhold'} * 100),
317 $a->{'std_timeframe'},
318 safe_sprintf("%.1f%%", $a->{'max_draw_down'} * 100),
319 safe_sprintf("%.1f%%", $a->{'buyandhold_max_draw_down'}),
320 ($a->{'max_performance'} > 10) ? safe_sprintf("%.0f%%", $a->{'max_performance'} * 100) : safe_sprintf("%.1f%%", $a->{'max_performance'} * 100),
321 safe_sprintf("%.1f%%", $a->{'min_performance'} * 100),
322 safe_sprintf("%.2f", $a->{'global_gain'}),
323 safe_sprintf("%.2f", $a->{'gross_gain'}),
324 $a->{'nb_gain'} + $a->{'nb_loss'},
325 safe_sprintf("%.2f", ($a->{'nb_gain'} + $a->{'nb_loss'}) / $a->{'duration'}),
326 $a->{'nb_gain'},
327 $a->{'nb_loss'},
328 safe_sprintf("%.1f%%", $a->{'win_loss_ratio'} * 100),
329 $a->{'max_consecutive_winner'},
330 $a->{'max_consecutive_loser'},
331 safe_sprintf("%.2f", $a->{'expectancy'}),
332 safe_sprintf("%.2f%%", $a->{'average_gain'} * 100),
333 safe_sprintf("%.2f%%", $a->{'average_loss'} * 100),
334 safe_sprintf("%.2f%%", $a->{'average_performance'} * 100),
335 safe_sprintf("%.2f%%", $a->{'biggest_gain'} * 100),
336 safe_sprintf("%.2f%%", $a->{'biggest_loss'} * 100),
337 safe_sprintf("%.2f", $a->{'profit_factor'}),
338 safe_sprintf("%.2f", $a->{'sum_of_gain'}),
339 safe_sprintf("%.2f", $a->{'sum_of_loss'}),
340 safe_sprintf("%.1f%%", $a->{'risk_of_ruin'} * 100)
341 );
342  
343 print OUT $text;
344  
345 if ($detailed) {
346 $format =
347 '
348 Corresponding dates :
349 MaxDrawDown : @<<<<<<<<< Best perf : @<<<<<<<<< Worst perf : @<<<<<<<<<
350 Biggest gain : @<<<<<<<<< Biggest loss : @<<<<<<<<<
351 Max consec. win : @<<<<<<<<< Max consec. loss : @<<<<<<<<<
352 ';
353 $text = swrite($format,
354 $a->{'max_draw_down_date'},
355 $a->{'max_performance_date'},
356 $a->{'min_performance_date'},
357 $a->{'biggest_gain_date'},
358 $a->{'biggest_loss_date'},
359 $a->{'max_consecutive_winner_date'},
360 $a->{'max_consecutive_loser_date'}
361 );
362 print OUT $text;
363 }
364 }
365  
366 =item C<< Finance::GeniusTrader::Report::AnalysisList >>
367  
368 Display the results of the backtest. Results per code and per system.
369  
370 =cut
371  
372 #=============================================
373 # previously sub _get_name was defined inside sub AnalysisList
374 sub _get_name {
375 my ($spool, $name) = @_;
376 my $res = $spool->get_alias_name($name);
377 return $res if (defined($res) && $res);
378 return $name;
379 }
380 #=============================================
381  
382 sub AnalysisList {
383 my ($spool, $set) = @_;
384  
385 my $l = $spool->list_available_data($set);
386 my $s = $spool;
387
388 # Find all codes
389 my %codes;
390 foreach (keys %{$l})
391 {
392 foreach my $code (@{$l->{$_}})
393 {
394 $codes{$code} = 1;
395 }
396 }
397
398 # $spool->get_stats($sysname, $code) returns an array
399 # [0] std_perf
400 # [1] perf
401 # [2] max draw down
402 # [3] std_buyandhold
403 # [4] buyandhold
404
405 my $db = create_db_object();
406 my ($nb_gain, $nb_loss, $mean, $buyhold);
407 # Analysis by code
408 foreach my $code (sort keys %codes)
409 {
410 $nb_gain = $nb_loss = 0; $mean = 1; $buyhold = 0;
411 my @systems = sort {
412 ($s->get_stats($b,$code)->[0] <=>
413 $s->get_stats($a,$code)->[0]) ||
414 ($s->get_stats($b,$code)->[1] <=>
415 $s->get_stats($a,$code)->[1])
416 }
417 grep {
418 defined($s->get_stats($_,$code))
419 } keys %{$l};
420 next if (! scalar @systems);
421 my $name = $db->get_name($code);
422 if ($name ne $code) {
423 print OUT "Results of systems for $name ($code) :\n";
424 } else {
425 print OUT "Results of systems for $code :\n";
426 }
427 foreach (@systems)
428 {
429 my $ana = $s->get_stats($_, $code);
430  
431 $buyhold = $ana->[3];
432 if ($ana->[0] > 0) { $nb_gain++ } else { $nb_loss++ };
433 $mean *= (1 + $ana->[0]);
434 my $text = swrite("@>>>>> @>>>>> [@>>>>>]",
435 sprintf("%.1f%%", $ana->[0] * 100),
436 sprintf("%.1f%%", $ana->[1] * 100),
437 sprintf("%.1f%%", $ana->[2] * 100)
438 );
439 print OUT "$text " . _get_name($s, $_) . "\n";
440 }
441 next if ($nb_loss + $nb_gain == 0);
442 $mean = $mean ** (1 / ($nb_loss + $nb_gain));
443 printf OUT "Global results : %d gain(s) and %d loss(es), average " .
444 "%.1f%%", $nb_gain, $nb_loss, ($mean - 1) * 100;
445 printf OUT ", buy&hold %.1f%%\n\n", $buyhold * 100;
446 }
447  
448 # Analysis by system
449 foreach my $sys (sort keys %{$l})
450 {
451 $nb_gain = $nb_loss = 0; $mean = 1; $buyhold = 1;
452 my @codes = sort { ($s->get_stats($sys,$b)->[0] <=>
453 $s->get_stats($sys,$a)->[0]) ||
454 ($s->get_stats($sys,$b)->[1] <=>
455 $s->get_stats($sys,$a)->[1])
456 }
457 grep { defined($s->get_stats($sys,$_))
458 }
459 @{$l->{$sys}};
460 next if (! scalar @codes);
461 print OUT "Results for system ";
462 print OUT _get_name($s, $sys) . " :\n";
463 foreach (@codes)
464 {
465 my $ana = $s->get_stats($sys, $_);
466 if ($ana->[0] > 0) { $nb_gain++ } else { $nb_loss++ };
467 $mean *= (1 + $ana->[0]);
468 $buyhold *= (1 + $ana->[3]);
469 my $text = swrite("@>>>>> @>>>>> [@>>>>>]",
470 sprintf("%.1f%%", $ana->[0] * 100),
471 sprintf("%.1f%%", $ana->[1] * 100),
472 sprintf("%.1f%%", $ana->[2] * 100)
473 );
474 my $name = $db->get_name($_);
475 if ($name ne $_) {
476 print OUT "$text $name ($_)\n";
477 } else {
478 print OUT "$text $_\n";
479 }
480 }
481 next if ($nb_loss + $nb_gain == 0);
482 $mean = $mean ** (1 / ($nb_loss + $nb_gain));
483 $buyhold = $buyhold ** (1 / ($nb_loss + $nb_gain));
484 printf OUT "Global results : %d gain(s) and %d loss(es), average " .
485 "%.1f%%", $nb_gain, $nb_loss, ($mean - 1) * 100;
486 printf OUT ", avg. buy&hold %.1f%%\n\n", ($buyhold - 1) * 100;
487 }
488
489 }
490  
491 =item C<< Finance::GeniusTrader::Report::SimplePortfolioAnalysis >>
492  
493 Pretty prints only the main results of the analysis.
494  
495 =cut
496 sub SimplePortfolioAnalysis {
497 my ($a) = shift;
498  
499 my $format = 'Performance : @>>>>> MaxDrawDown : @>>>>>';
500  
501 my $text = swrite($format,
502 sprintf("%.1f%%", $a->{'performance'} * 100),
503 sprintf("%.1f%%", $a->{'max_draw_down'} * 100) );
504  
505 print OUT $text;
506 }
507  
508 =item C<< Finance::GeniusTrader::Report::CacheValues >>
509  
510 Prints a summary of the content of the cache.
511  
512 =cut
513 sub CacheValues {
514 my ($cache) = @_;
515  
516 # Print statistics of available computed data for each
517 # "name"
518 }
519  
520 sub swrite {
521 my $format = shift;
522 $^A = "";
523 formline($format,@_);
524 return $^A;
525 }
526  
527 =pod
528  
529 =back
530  
531 =cut
532 1;