| 1 | package Finance::GeniusTrader::Portfolio; | ||
| 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 | use vars qw(@ISA); | ||
| 9 | |||
| 10 | #ALL# use Log::Log4perl qw(:easy); | ||
| 11 | use Finance::GeniusTrader::Prices; | ||
| 12 | use Finance::GeniusTrader::SystemManager; | ||
| 13 | |||
| 14 | use Finance::GeniusTrader::Portfolio::Order; | ||
| 15 | use Finance::GeniusTrader::Portfolio::Position; | ||
| 16 | |||
| 17 | use Finance::GeniusTrader::Serializable; | ||
| 18 | |||
| 19 | @ISA = qw(Finance::GeniusTrader::Serializable); | ||
| 20 | |||
| 21 | =head1 NAME | ||
| 22 | |||
| 23 | Finance::GeniusTrader::Portfolio - A portfolio | ||
| 24 | |||
| 25 | =head1 DESCRIPTION | ||
| 26 | |||
| 27 | A Portfolio is used to keep track of orders. It can calculate a | ||
| 28 | performance and give useful statistics about what you've done | ||
| 29 | (average trade gain/loss, percentage of winning/losing trades, | ||
| 30 | max draw down, ...). | ||
| 31 | |||
| 32 | =over | ||
| 33 | |||
| 34 | =item C<< my $p = Finance::GeniusTrader::Portfolio->new; >> | ||
| 35 | |||
| 36 | Create a portfolio object without any open positions and without any | ||
| 37 | pendings orders (ie an empty portfolio). | ||
| 38 | |||
| 39 | =cut | ||
| 40 | sub new { | ||
| 41 | my $type = shift; | ||
| 42 | my $class = ref($type) || $type; | ||
| 43 | |||
| 44 | my $self = { "pending_orders" => [], | ||
| 45 | "open_positions" => [], # pointer to positions{uniqid} | ||
| 46 | "history" => [], # pointer to positions{uniqid} | ||
| 47 | "positions" => {}, # all positions | ||
| 48 | "discarded_orders" => [], # discarded pending orders | ||
| 49 | "order_id" => 0, | ||
| 50 | "global_position_id" => 0, # for all positions | ||
| 51 | "cash" => 0, | ||
| 52 | "position_evaluation" => {}, | ||
| 53 | "position_marged_gains" => {}, | ||
| 54 | "evaluation_history" => {} | ||
| 55 | }; | ||
| 56 | bless $self, $class; | ||
| 57 | return $self; | ||
| 58 | } | ||
| 59 | |||
| 60 | =item C<< $p->add_order($order) >> | ||
| 61 | |||
| 62 | Add $order to the list of pending orders. | ||
| 63 | |||
| 64 | =cut | ||
| 65 | sub add_order { | ||
| 66 | my ($self, $order) = @_; | ||
| 67 | |||
| 68 | #WAR# WARN "valid type for order" if ( ref($order) =~ /Portfolio::Order/); | ||
| 69 | #WAR# WARN "order quantity is positive" if ( $order->quantity > 0); | ||
| 70 | |||
| 71 | $order->set_id($self->{'order_id'}); | ||
| 72 | |||
| 73 | $self->{'order_id'}++; | ||
| 74 | $self->{'pending_orders'}[$order->id] = $order; | ||
| 75 | return $order->id; | ||
| 76 | } | ||
| 77 | |||
| 78 | =item C<< $p->discard_order($order) >> | ||
| 79 | |||
| 80 | Discard the order. Usually that means that it hasn't been executed or | ||
| 81 | that it has been cancelled. | ||
| 82 | |||
| 83 | =cut | ||
| 84 | sub discard_order { | ||
| 85 | my ($self, $order) = @_; | ||
| 86 | |||
| 87 | #WAR# WARN "valid type for order" if ( ref($order) =~ /Portfolio::Order/); | ||
| 88 | #WAR# WARN "order id is positive" if ( $order->id >= 0); | ||
| 89 | |||
| 90 | push @{$self->{'discarded_orders'}}, | ||
| 91 | $self->{'pending_orders'}[$order->id]; | ||
| 92 | $self->{'pending_orders'}[$order->id] = undef; | ||
| 93 | |||
| 94 | return; | ||
| 95 | } | ||
| 96 | |||
| 97 | sub delete_order { | ||
| 98 | my ($self, $order) = @_; | ||
| 99 | |||
| 100 | #WAR# WARN "valid type for order" if ( ref($order) =~ /Portfolio::Order/); | ||
| 101 | #WAR# WARN "order id is positive" if ( $order->id >= 0); | ||
| 102 | |||
| 103 | $self->{'pending_orders'}[$order->id] = undef; | ||
| 104 | return; | ||
| 105 | } | ||
| 106 | |||
| 107 | =item C<< $p->new_position($code, $source, $date) >> | ||
| 108 | |||
| 109 | Create a new open position in the portfolio. | ||
| 110 | |||
| 111 | =cut | ||
| 112 | sub new_position { | ||
| 113 | my ($self, $code, $source, $date) = @_; | ||
| 114 | |||
| 115 | my $position = Finance::GeniusTrader::Portfolio::Position->new($code, $source, $date); | ||
| 116 | $position->set_id($self->{'global_position_id'}++); | ||
| 117 | push @{$self->{'open_positions'}}, $position; | ||
| 118 | #DEB# DEBUG "position " . $position->id . " opened"; | ||
| 119 | |||
| 120 | return $position; | ||
| 121 | } | ||
| 122 | |||
| 123 | =item C<< $p->apply_order_on_position($position, $order, $price, $date) >> | ||
| 124 | |||
| 125 | Add the given order to the position and modify the money available in the | ||
| 126 | portfolio accordingly. | ||
| 127 | |||
| 128 | =cut | ||
| 129 | sub apply_order_on_position { | ||
| 130 | my ($self, $position, $order, $price, $date) = @_; | ||
| 131 | |||
| 132 | #WAR# WARN "valid type for position" if ( ref($position) =~ /Finance::GeniusTrader::Portfolio::Position/); | ||
| 133 | #WAR# WARN "valid type for order" if ( ref($order) =~ /Finance::GeniusTrader::Portfolio::Order/); | ||
| 134 | |||
| 135 | my $stats_before = $position->stats($self); | ||
| 136 | $position->apply_order($order, $price, $date); | ||
| 137 | my $stats_after = $position->stats($self); | ||
| 138 | |||
| 139 | # Update the cash | ||
| 140 | if (! $position->is_marged) | ||
| 141 | { | ||
| 142 | $self->{'cash'} += $stats_after->{'sold'} - $stats_before->{'sold'}; | ||
| 143 | $self->{'cash'} -= $stats_after->{'bought'} - | ||
| 144 | $stats_before->{'bought'}; | ||
| 145 | } | ||
| 146 | $self->{'cash'} -= $stats_after->{'cost'} - $stats_before->{'cost'}; | ||
| 147 | |||
| 148 | if (! $position->is_open) | ||
| 149 | { | ||
| 150 | $position->set_close_date($date); | ||
| 151 | $self->close_position($position); | ||
| 152 | } | ||
| 153 | } | ||
| 154 | |||
| 155 | =item C<< $p->close_position($pos) >> | ||
| 156 | |||
| 157 | Move the position from the list of open positions to the historic list. | ||
| 158 | Update the cash with the marged gain. | ||
| 159 | |||
| 160 | =cut | ||
| 161 | sub close_position { | ||
| 162 | my ($self, $position) = @_; | ||
| 163 | |||
| 164 | #WAR# WARN "valid type for position" if ( ref($position) =~ /Finance::GeniusTrader::Portfolio::Position/); | ||
| 165 | |||
| 166 | push @{$self->{'history'}}, $position; | ||
| 167 | |||
| 168 | # Closed position has no evaluation any more | ||
| 169 | delete $self->{'position_evaluation'}{$position->id}; | ||
| 170 | |||
| 171 | # Add the gains/losses if the position is marged | ||
| 172 | my $stats = $position->stats($self); | ||
| 173 | if ($position->is_marged) | ||
| 174 | { | ||
| 175 | $self->{'cash'} += $stats->{'sold'} - | ||
| 176 | $stats->{'bought'}; | ||
| 177 | # Closed positions has no marged gains anymore | ||
| 178 | delete $self->{'position_marged_gains'}{$position->id}; | ||
| 179 | } | ||
| 180 | |||
| 181 | # Complicated way of removing a position from the list | ||
| 182 | # of open positions | ||
| 183 | my $index = -1; | ||
| 184 | foreach (@{$self->{'open_positions'}}) | ||
| 185 | { | ||
| 186 | $index++; | ||
| 187 | next if (! defined($_)); | ||
| 188 | if ($_->id eq $position->id) | ||
| 189 | { | ||
| 190 | last; | ||
| 191 | } | ||
| 192 | } | ||
| 193 | $self->{'open_positions'}[$index] = undef if ($index != -1); | ||
| 194 | #DEB# DEBUG "position " . $position->id . " closed"; | ||
| 195 | |||
| 196 | } | ||
| 197 | |||
| 198 | =item C<< $p->apply_pending_orders($calc, $i, $source, $pf_manager, [ $cb ]) >> | ||
| 199 | |||
| 200 | Check the pending order for the value indicated by $calc, try to execute | ||
| 201 | them on the day $i. It restricts itself to the orders coming from | ||
| 202 | the indicated source. You can pass an optionnal callback for managing | ||
| 203 | specially the position_opened callback. Not giving this arg and leaving | ||
| 204 | to its default value is usually ok. | ||
| 205 | |||
| 206 | =cut | ||
| 207 | sub apply_pending_orders { | ||
| 208 | my ($self, $calc, $i, $source, $pf_manager, $cb) = @_; | ||
| 209 | |||
| 210 | if (! defined($cb)) | ||
| 211 | { | ||
| 212 | $cb = sub { | ||
| 213 | my ($calc, $i, $position) = @_; | ||
| 214 | my $sm; | ||
| 215 | $sm = Finance::GeniusTrader::SystemManager::get_registered_object($position->{'source'}); | ||
| 216 | $sm->position_opened($calc, $i, $position, $pf_manager) | ||
| 217 | if (defined($sm)); | ||
| 218 | }; | ||
| 219 | } | ||
| 220 | |||
| 221 | foreach (@{$self->{'pending_orders'}}) { | ||
| 222 | next if (! defined($_)); | ||
| 223 | next if ($_->code ne $calc->code); | ||
| 224 | next if ($_->source ne $source); | ||
| 225 | |||
| 226 | my $price = $_->is_executed($calc, $i); | ||
| 227 | |||
| 228 | if ($price) { | ||
| 229 | # New position ! | ||
| 230 | my $position = $self->new_position($calc->code, $source, | ||
| 231 | $calc->prices->at($i)->[$DATE]); | ||
| 232 | $position->set_timeframe($calc->current_timeframe); | ||
| 233 | $position->set_marged if ($_->is_marged); | ||
| 234 | |||
| 235 | $self->apply_order_on_position($position, $_, $price, $calc->prices->at($i)->[$DATE]); | ||
| 236 | |||
| 237 | $self->update_position_evaluation($position, $calc, $i); | ||
| 238 | |||
| 239 | # Call the position_opened callback | ||
| 240 | if (defined($cb)) | ||
| 241 | { | ||
| 242 | &$cb($calc, $i, $position); | ||
| 243 | } | ||
| 244 | $self->delete_order($_); | ||
| 245 | } else { | ||
| 246 | if ($_->discardable) | ||
| 247 | { | ||
| 248 | $self->discard_order($_); | ||
| 249 | } else { | ||
| 250 | # Not discarded | ||
| 251 | } | ||
| 252 | } | ||
| 253 | } | ||
| 254 | return; | ||
| 255 | } | ||
| 256 | |||
| 257 | =item C<< $p->apply_pending_orders_on_position($position, $calc, $i) >> | ||
| 258 | |||
| 259 | Apply all pending orders on the position, this does include | ||
| 260 | the stop. | ||
| 261 | |||
| 262 | =cut | ||
| 263 | sub apply_pending_orders_on_position { | ||
| 264 | my ($self, $position, $calc, $i) = @_; | ||
| 265 | |||
| 266 | return if ($position->code() ne $calc->code()); | ||
| 267 | |||
| 268 | my $stats_before = $position->stats($self); | ||
| 269 | $position->apply_pending_orders($calc, $i); | ||
| 270 | my $stats_after = $position->stats($self); | ||
| 271 | |||
| 272 | # Update the cash | ||
| 273 | if (! $position->is_marged) | ||
| 274 | { | ||
| 275 | $self->{'cash'} += $stats_after->{'sold'} - $stats_before->{'sold'}; | ||
| 276 | $self->{'cash'} -= $stats_after->{'bought'} - | ||
| 277 | $stats_before->{'bought'}; | ||
| 278 | } | ||
| 279 | $self->{'cash'} -= $stats_after->{'cost'} - $stats_before->{'cost'}; | ||
| 280 | |||
| 281 | $self->update_position_evaluation($position, $calc, $i); | ||
| 282 | |||
| 283 | if (! $position->is_open) | ||
| 284 | { | ||
| 285 | $position->set_close_date($calc->prices->at($i)->[$DATE]); | ||
| 286 | $self->close_position($position); | ||
| 287 | } | ||
| 288 | } | ||
| 289 | |||
| 290 | =item C<< $p->update_position_evaluation($position, $calc, $i) >> | ||
| 291 | |||
| 292 | Update the evaluation of the position with data of day $i. | ||
| 293 | |||
| 294 | =cut | ||
| 295 | sub update_position_evaluation { | ||
| 296 | my ($self, $position, $calc, $i) = @_; | ||
| 297 | my $eval = 0; | ||
| 298 | if ($position->is_marged) | ||
| 299 | { | ||
| 300 | my $s = $position->stats($self); | ||
| 301 | if ($position->is_short) | ||
| 302 | { | ||
| 303 | $eval = $s->{'sold'} - $s->{'bought'} - | ||
| 304 | $calc->prices->at($i)->[$LAST] * $position->quantity; | ||
| 305 | } else { | ||
| 306 | $eval = $calc->prices->at($i)->[$LAST] * $position->quantity | ||
| 307 | + $s->{'sold'} - $s->{'bought'}; | ||
| 308 | } | ||
| 309 | $self->{'position_marged_gains'}{$position->id} = $eval; | ||
| 310 | } | ||
| 311 | $eval = $position->quantity * $calc->prices->at($i)->[$LAST]; | ||
| 312 | $self->{'position_evaluation'}{$position->id} = $eval; | ||
| 313 | return; | ||
| 314 | } | ||
| 315 | |||
| 316 | =item C<< $p->store_evaluation($date) >> | ||
| 317 | |||
| 318 | Store the cash level and the evaluation of the portfolio for the indicated | ||
| 319 | date. | ||
| 320 | |||
| 321 | =cut | ||
| 322 | sub store_evaluation { | ||
| 323 | my ($self, $date) = @_; | ||
| 324 | $self->{'evaluation_history'}{$date} = [ $self->current_cash, | ||
| 325 | $self->current_evaluation, | ||
| 326 | $self->current_marged_gains, | ||
| 327 | $self->current_marged_investment ]; | ||
| 328 | return; | ||
| 329 | } | ||
| 330 | |||
| 331 | =item C<< $p->current_cash() >> | ||
| 332 | |||
| 333 | Returns the sum of cash available (may return a negative value if | ||
| 334 | "effet de levier" is used). | ||
| 335 | |||
| 336 | =cut | ||
| 337 | sub current_cash { $_[0]->{'cash'} } | ||
| 338 | |||
| 339 | =item C<< $p->current_evaluation() >> | ||
| 340 | |||
| 341 | Returns the evaluation of all the open positions in the portfolio. | ||
| 342 | |||
| 343 | =cut | ||
| 344 | sub current_evaluation { | ||
| 345 | my ($self) = @_; | ||
| 346 | |||
| 347 | my $eval = 0; | ||
| 348 | foreach my $position ($self->list_open_positions) | ||
| 349 | { | ||
| 350 | if (! $position->is_marged) | ||
| 351 | { | ||
| 352 | $eval += $self->{'position_evaluation'}{$position->id}; | ||
| 353 | } | ||
| 354 | } | ||
| 355 | return $eval; | ||
| 356 | } | ||
| 357 | |||
| 358 | =item C<< $p->current_marged_gains() >> | ||
| 359 | |||
| 360 | Returns the sum of gains (or losses if the number is negative) made with | ||
| 361 | marged positions. | ||
| 362 | |||
| 363 | =cut | ||
| 364 | sub current_marged_gains { | ||
| 365 | my ($self) = @_; | ||
| 366 | |||
| 367 | my $eval = 0; | ||
| 368 | foreach my $position ($self->list_open_positions) | ||
| 369 | { | ||
| 370 | if ($position->is_marged) | ||
| 371 | { | ||
| 372 | $eval += $self->{'position_marged_gains'}{$position->id}; | ||
| 373 | } | ||
| 374 | } | ||
| 375 | return $eval; | ||
| 376 | } | ||
| 377 | |||
| 378 | =item C<< $p->current_marged_investment() >> | ||
| 379 | |||
| 380 | Returns the sum of gains (or losses if the number is negative) made with | ||
| 381 | marged positions. | ||
| 382 | |||
| 383 | =cut | ||
| 384 | sub current_marged_investment { | ||
| 385 | my ($self) = @_; | ||
| 386 | |||
| 387 | my $eval = 0; | ||
| 388 | foreach my $position ($self->list_open_positions) | ||
| 389 | { | ||
| 390 | if ($position->is_marged) | ||
| 391 | { | ||
| 392 | $eval += $self->{'position_evaluation'}{$position->id}; | ||
| 393 | } | ||
| 394 | } | ||
| 395 | return $eval; | ||
| 396 | } | ||
| 397 | |||
| 398 | |||
| 399 | =item C<< my($cash, $evaluation, $gains) = $p->get_historic_evaluation($date) >> | ||
| 400 | |||
| 401 | Return the historic information (cash and portfolio evaluation) about the | ||
| 402 | portfolio. | ||
| 403 | |||
| 404 | =cut | ||
| 405 | sub get_historic_evaluation { | ||
| 406 | my ($self, $date) = @_; | ||
| 407 | |||
| 408 | #WAR# WARN "the evaluation must exist for the given date" if ( exists $self->{'evaluation_history'}{$date}); | ||
| 409 | |||
| 410 | my @eval = @{$self->{'evaluation_history'}{$date}}; | ||
| 411 | if (wantarray) | ||
| 412 | { | ||
| 413 | return @eval; | ||
| 414 | } else { | ||
| 415 | # Marged investment is left out on purpose ! | ||
| 416 | my $sum = $eval[0] + $eval[1] + $eval[2]; | ||
| 417 | return $sum; | ||
| 418 | } | ||
| 419 | } | ||
| 420 | |||
| 421 | =item C<< $p->has_historic_evaluation($date) >> | ||
| 422 | |||
| 423 | Returns true if an evaluation of the portfolio exists for the given date. | ||
| 424 | |||
| 425 | =cut | ||
| 426 | sub has_historic_evaluation { | ||
| 427 | my ($self, $date) = @_; | ||
| 428 | |||
| 429 | return exists $self->{'evaluation_history'}{$date}; | ||
| 430 | } | ||
| 431 | |||
| 432 | =item C<< $p->list_pending_orders([$source]) >> | ||
| 433 | |||
| 434 | Returns the list of orders that are pending and that have been submitted | ||
| 435 | by the corresponding source. If source argument is missing (or undef), | ||
| 436 | returns all the pending orders. | ||
| 437 | |||
| 438 | =cut | ||
| 439 | sub list_pending_orders { | ||
| 440 | my ($self, $source) = @_; | ||
| 441 | |||
| 442 | if (defined($source)) { | ||
| 443 | return grep { defined($_) && ($_->source eq $source) } | ||
| 444 | @{$self->{'pending_orders'}}; | ||
| 445 | } else { | ||
| 446 | return grep { defined($_) } @{$self->{'pending_orders'}}; | ||
| 447 | } | ||
| 448 | } | ||
| 449 | |||
| 450 | =item C<< $p->list_open_positions([$source]) >> | ||
| 451 | |||
| 452 | Returns the list of positions that are open and that have been submitted | ||
| 453 | by the corresponding source. If source argument is missing (or undef), | ||
| 454 | returns all the open positions. | ||
| 455 | |||
| 456 | =cut | ||
| 457 | sub list_open_positions { | ||
| 458 | my ($self, $source) = @_; | ||
| 459 | |||
| 460 | if (defined($source)) { | ||
| 461 | return grep { defined($_) && ($_->source eq $source) } | ||
| 462 | @{$self->{'open_positions'}}; | ||
| 463 | } else { | ||
| 464 | return grep { defined($_) } @{$self->{'open_positions'}}; | ||
| 465 | } | ||
| 466 | } | ||
| 467 | |||
| 468 | =item C<< $p->get_position($code, $source) >> | ||
| 469 | |||
| 470 | Return the position (if any) corresponding to $code and $source. | ||
| 471 | This assumes that only one such position exists. | ||
| 472 | |||
| 473 | =cut | ||
| 474 | sub get_position { | ||
| 475 | my ($self, $code, $source) = @_; | ||
| 476 | |||
| 477 | my @res = grep { defined($_) && ($_->code eq $code) && | ||
| 478 | ($_->source eq $source) } | ||
| 479 | @{$self->{'open_positions'}}; | ||
| 480 | if (scalar(@res)) { | ||
| 481 | return wantarray ? @res : $res[0]; | ||
| 482 | } else { | ||
| 483 | return undef; | ||
| 484 | } | ||
| 485 | } | ||
| 486 | |||
| 487 | =item C<< $p->list_history_positions($code, $source) >> | ||
| 488 | |||
| 489 | Return the list of historical positions corresponding to $code and $source. | ||
| 490 | |||
| 491 | =cut | ||
| 492 | sub list_history_positions { | ||
| 493 | my ($self, $code, $source) = @_; | ||
| 494 | |||
| 495 | return grep { defined($_) && ($_->code eq $code) && | ||
| 496 | ($_->source eq $source) } | ||
| 497 | @{$self->{'history'}}; | ||
| 498 | } | ||
| 499 | |||
| 500 | =item C<< $p->set_initial_value() >> | ||
| 501 | |||
| 502 | Set the amount of money available initially on the portfolio. | ||
| 503 | |||
| 504 | =cut | ||
| 505 | sub set_initial_value { | ||
| 506 | my ($self, $value) = @_; | ||
| 507 | |||
| 508 | $self->{'initial_sum'} = $value; | ||
| 509 | if (! $self->{'cash'}) | ||
| 510 | { | ||
| 511 | $self->{'cash'} = $value; | ||
| 512 | } | ||
| 513 | } | ||
| 514 | |||
| 515 | =item C<< $p->set_broker($broker) >> | ||
| 516 | |||
| 517 | Defines which broker to use for the calculation of order commissions and | ||
| 518 | annual account charge. | ||
| 519 | |||
| 520 | =cut | ||
| 521 | sub set_broker { | ||
| 522 | my ($self, $broker) = @_; | ||
| 523 | |||
| 524 | $self->{'broker'} = $broker; | ||
| 525 | |||
| 526 | return; | ||
| 527 | } | ||
| 528 | |||
| 529 | =item C<< $p->get_order_cost($order) >> | ||
| 530 | |||
| 531 | Apply all broker rules and return the amount ask by the broker for the | ||
| 532 | given order. | ||
| 533 | |||
| 534 | =cut | ||
| 535 | sub get_order_cost { | ||
| 536 | my ($self, $order) = @_; | ||
| 537 | |||
| 538 | if (defined($self->{'broker'})) { | ||
| 539 | my $cost = $self->{'broker'}->calculate_order_commission($order); | ||
| 540 | return $cost; | ||
| 541 | } | ||
| 542 | return 0; | ||
| 543 | } | ||
| 544 | |||
| 545 | =item C<< $p->real_global_analysis() >> | ||
| 546 | |||
| 547 | =item C<< $p->real_analysis_by_code($code) >> | ||
| 548 | |||
| 549 | Analyzes the evolution of the portfolio. Either globally or for each | ||
| 550 | share individually. | ||
| 551 | |||
| 552 | Real analysis uses just the information provided. For a global analysis, | ||
| 553 | it needs an initial value for the portfolio. | ||
| 554 | |||
| 555 | The informations calculated are : | ||
| 556 | |||
| 557 | - global gain/loss (sum & percentage) | ||
| 558 | - number of winning trades | ||
| 559 | - number of loosing trades | ||
| 560 | - average loss (percentage) | ||
| 561 | - average gain (percentage) | ||
| 562 | - max gain in single trade (percentage) | ||
| 563 | - max loss in single trade (percentage) | ||
| 564 | - max global gain | ||
| 565 | - max global loss | ||
| 566 | - max draw down (biggest cumulated loss after a new high) (percentage) | ||
| 567 | |||
| 568 | =cut | ||
| 569 | sub real_global_analysis { | ||
| 570 | my ($self) = @_; | ||
| 571 | my $date2int = sub { | ||
| 572 | Finance::GeniusTrader::DateTime::map_date_to_time($_[0]->timeframe, $_[0]->open_date) | ||
| 573 | }; | ||
| 574 | |||
| 575 | my $ana = $self->new_analysis(); | ||
| 576 | |||
| 577 | foreach (sort { &$date2int($a) <=> &$date2int($b) } @{$self->{'history'}}) | ||
| 578 | { | ||
| 579 | $self->update_analysis($ana, $_); | ||
| 580 | } | ||
| 581 | |||
| 582 | return $self->return_analysis($ana); | ||
| 583 | } | ||
| 584 | |||
| 585 | sub real_analysis_by_code { | ||
| 586 | my ($self, $code) = @_; | ||
| 587 | my $date2int = sub { | ||
| 588 | Finance::GeniusTrader::DateTime::map_date_to_time($_[0]->timeframe, $_[0]->open_date) | ||
| 589 | }; | ||
| 590 | |||
| 591 | my $ana = $self->new_analysis(); | ||
| 592 | |||
| 593 | foreach (sort { &$date2int($a) <=> &$date2int($b) } | ||
| 594 | grep { $_->code eq $code } @{$self->{'history'}}) | ||
| 595 | { | ||
| 596 | $self->update_analysis($ana, $_); | ||
| 597 | } | ||
| 598 | |||
| 599 | return $self->return_analysis($ana); | ||
| 600 | } | ||
| 601 | |||
| 602 | # Create the analysis hash | ||
| 603 | sub new_analysis { | ||
| 604 | my ($self) = @_; | ||
| 605 | my $ana = { | ||
| 606 | "initial_sum" => $self->{'initial_sum'}, | ||
| 607 | map { $_ => 0 } | ||
| 608 | ("gain", "nb_gain", "nb_loss", | ||
| 609 | "expectancy", "sum_gain", "sum_loss", "cum_gain_pc", | ||
| 610 | "cum_loss_pc", "max_single_gain", "max_single_loss", "max_gain", | ||
| 611 | "max_loss", "max_draw_down", "draw_down_high", "draw_down_low", | ||
| 612 | "nb_orders", "sum_bought", "sum_sold", "commissions", | ||
| 613 | "max_consec_gain", "max_consec_loss", "consec_gain", | ||
| 614 | "consec_loss") | ||
| 615 | }; | ||
| 616 | $ana->{'cum_loss_pc'} = 1; | ||
| 617 | $ana->{'cum_gain_pc'} = 1; | ||
| 618 | return $ana; | ||
| 619 | } | ||
| 620 | |||
| 621 | # Update the analysis hash with a new operation | ||
| 622 | # This must be called with operation in chronological order | ||
| 623 | sub update_analysis { | ||
| 624 | my ($self, $a, $o, $quantity_factor) = @_; # analysis, operation | ||
| 625 | my ($diff, $variation, $draw_down) = (0, 0, 0); | ||
| 626 | |||
| 627 | # Calculate the mean open/close price and the total quantity | ||
| 628 | |||
| 629 | my $pstats = $o->stats($self, $quantity_factor); | ||
| 630 | |||
| 631 | $a->{'nb_orders'} += $pstats->{'nb_orders'}; | ||
| 632 | $a->{'sum_bought'} += $pstats->{'bought'}; | ||
| 633 | $a->{'sum_sold'} += $pstats->{'sold'}; | ||
| 634 | $a->{'commissions'} += $pstats->{'cost'}; | ||
| 635 | |||
| 636 | # Calculate the gain for this position (set of operation) | ||
| 637 | # $diff => in currency | ||
| 638 | # $variation => in percentage | ||
| 639 | |||
| 640 | $diff = $pstats->{'sold'} - $pstats->{'bought'} - $pstats->{'cost'}; | ||
| 641 | if ($o->is_long) { | ||
| 642 | $variation = ($pstats->{'bought'} !=0) ? | ||
| 643 | ($diff / $pstats->{'bought'}) : 0; | ||
| 644 | } else { | ||
| 645 | $variation = ($pstats->{'sold'} !=0) ? ($diff / $pstats->{'sold'}) : 0; | ||
| 646 | } | ||
| 647 | |||
| 648 | # Update the total gain | ||
| 649 | $a->{'gain'} += $diff; | ||
| 650 | |||
| 651 | # Check for new max_gain or max_loss | ||
| 652 | if ($a->{'gain'} > $a->{'max_gain'}) { | ||
| 653 | $a->{'max_gain'} = $a->{'gain'}; | ||
| 654 | $a->{'max_gain_date'} = $o->close_date; | ||
| 655 | } | ||
| 656 | if ($a->{'gain'} < $a->{'max_loss'}) { | ||
| 657 | $a->{'max_loss'} = $a->{'gain'}; | ||
| 658 | $a->{'max_loss_date'} = $o->close_date; | ||
| 659 | } | ||
| 660 | |||
| 661 | # Check if we have a new max_draw_down | ||
| 662 | $draw_down = 1 - (($a->{'initial_sum'} + $a->{'gain'}) / ($a->{'initial_sum'} + $a->{'max_gain'})); | ||
| 663 | if ($draw_down > $a->{'max_draw_down'}) { | ||
| 664 | $a->{'max_draw_down'} = $draw_down; | ||
| 665 | $a->{'draw_down_high'} = $a->{'max_gain'}; | ||
| 666 | $a->{'draw_down_low'} = $a->{'gain'}; | ||
| 667 | $a->{'max_draw_down_date'} = $o->close_date; | ||
| 668 | } | ||
| 669 | |||
| 670 | # Stats on single trade | ||
| 671 | if ($variation > 0) { | ||
| 672 | $a->{'nb_gain'}++; | ||
| 673 | $a->{'sum_gain'} += $diff; | ||
| 674 | $a->{'cum_gain_pc'} *= (1 + $variation); | ||
| 675 | if ($variation > $a->{'max_single_gain'}) { | ||
| 676 | $a->{'max_single_gain'} = $variation; | ||
| 677 | $a->{'max_single_gain_date'} = $o->close_date; | ||
| 678 | } | ||
| 679 | $a->{'consec_gain'}++; | ||
| 680 | $a->{'consec_loss'} = 0; | ||
| 681 | if ($a->{'consec_gain'} > $a->{'max_consec_gain'}) | ||
| 682 | { | ||
| 683 | $a->{'max_consec_gain'} = $a->{'consec_gain'}; | ||
| 684 | $a->{'max_consec_gain_date'} = $o->close_date; | ||
| 685 | } | ||
| 686 | } else { | ||
| 687 | $a->{'nb_loss'}++; | ||
| 688 | $a->{'sum_loss'} += $diff; | ||
| 689 | $a->{'cum_loss_pc'} *= (1 + $variation); | ||
| 690 | if ($variation < $a->{'max_single_loss'}) { | ||
| 691 | $a->{'max_single_loss'} = $variation; | ||
| 692 | $a->{'max_single_loss_date'} = $o->close_date; | ||
| 693 | } | ||
| 694 | $a->{'consec_loss'}++; | ||
| 695 | $a->{'consec_gain'} = 0; | ||
| 696 | if ($a->{'consec_loss'} > $a->{'max_consec_loss'}) | ||
| 697 | { | ||
| 698 | $a->{'max_consec_loss'} = $a->{'consec_loss'}; | ||
| 699 | $a->{'max_consec_loss_date'} = $o->close_date; | ||
| 700 | } | ||
| 701 | } | ||
| 702 | } | ||
| 703 | |||
| 704 | sub return_analysis { | ||
| 705 | my ($self, $ana) = @_; | ||
| 706 | my $average_loss = 0; | ||
| 707 | my $average_gain = 0; | ||
| 708 | my $win_loss_ratio = 0; | ||
| 709 | my $profit_factor = 0; | ||
| 710 | my $expectancy = 0; | ||
| 711 | my $average_trade = 0; | ||
| 712 | |||
| 713 | if ($ana->{'nb_loss'} != 0) { | ||
| 714 | $average_loss = ($ana->{'cum_loss_pc'} ** (1 / $ana->{'nb_loss'})) - 1; | ||
| 715 | } | ||
| 716 | if ($ana->{'nb_gain'} != 0) { | ||
| 717 | $average_gain = ($ana->{'cum_gain_pc'} ** (1 / $ana->{'nb_gain'})) - 1; | ||
| 718 | } | ||
| 719 | if ($ana->{'nb_loss'} + $ana->{'nb_gain'} != 0) | ||
| 720 | { | ||
| 721 | $win_loss_ratio = $ana->{'nb_gain'} / | ||
| 722 | ($ana->{'nb_gain'} + $ana->{'nb_loss'}); | ||
| 723 | $average_trade = (1 + ($ana->{'gain'} / $ana->{'initial_sum'})) ** | ||
| 724 | ( 1 / ($ana->{'nb_gain'} + $ana->{'nb_loss'})) - 1; | ||
| 725 | } | ||
| 726 | if ($average_loss != 0) | ||
| 727 | { | ||
| 728 | $profit_factor = $average_gain / ($average_loss * -1); | ||
| 729 | $expectancy = $win_loss_ratio * $average_gain + (1 - $win_loss_ratio) * $average_loss; | ||
| 730 | } | ||
| 731 | else | ||
| 732 | { | ||
| 733 | $profit_factor = 999999; | ||
| 734 | $expectancy = $win_loss_ratio * $average_gain; | ||
| 735 | } | ||
| 736 | |||
| 737 | # Calculate Vince's "R4" (Risk Of Ruin) | ||
| 738 | # | ||
| 739 | # Example on system TFS with Alcatel : | ||
| 740 | # There is a 19.2 % probability of the account falling 40 % below the start | ||
| 741 | # equity (10 000 EUR) before it rises above 20 000 EUR. | ||
| 742 | |||
| 743 | # Probability of a win | ||
| 744 | my $PW = $win_loss_ratio; | ||
| 745 | |||
| 746 | # Average winning trade | ||
| 747 | my $AW = ($ana->{'nb_gain'} eq 0) ? 0 : $ana->{'sum_gain'} / $ana->{'nb_gain'}; | ||
| 748 | |||
| 749 | # Average losing trade | ||
| 750 | my $AL = ($ana->{'nb_loss'} eq 0) ? 0 : $ana->{'sum_loss'} / $ana->{'nb_loss'}; | ||
| 751 | |||
| 752 | # Size of starting account | ||
| 753 | my $Q = $ana->{'initial_sum'}; | ||
| 754 | |||
| 755 | # Quit trading and celebrate if account reaches this | ||
| 756 | my $L = $ana->{'initial_sum'} * 2; | ||
| 757 | |||
| 758 | # Drawdown to start equity that constitutes "ruin" | ||
| 759 | my $G = 0.40; | ||
| 760 | |||
| 761 | # Initialize the risk of ruin to 100 % before we calculate it, so that | ||
| 762 | # the ratio is already set up if we have no winning trades... | ||
| 763 | my $R4 = 1.0; | ||
| 764 | |||
| 765 | # Calculate the risk or ruin only if we have some winning trades and | ||
| 766 | # losing ones ! | ||
| 767 | if (($AW != 0) and ($AL != 0)) { | ||
| 768 | my $a = sqrt( ($PW * ($AW / $Q) * ($AW / $Q)) + ((1.0 - $PW) * ($AL / $Q) * ($AL / $Q)) ); | ||
| 769 | my $z = (abs($AW / $Q) * $PW) - (abs($AL / $Q) * (1.0 - $PW)); | ||
| 770 | my $p = 0.5 * (1.0 + ($z / $a)); | ||
| 771 | my $U = $G / $a; | ||
| 772 | my $c = (($L - ((1.0 - $G) * $Q)) / $Q) / $a; | ||
| 773 | my $temp1 = exp($U * log((1.0 - $p) / $p)); | ||
| 774 | my $temp2 = exp($c * log((1.0 - $p) / $p)); | ||
| 775 | if ($temp2 != 1) { | ||
| 776 | $R4 = 1.0 - (($temp1 - 1.0) / ($temp2 - 1.0)); | ||
| 777 | } else { | ||
| 778 | $R4 = 0; | ||
| 779 | } | ||
| 780 | } | ||
| 781 | |||
| 782 | # Set up the risk of ruin to 0 % if we don't have losing trades ! | ||
| 783 | $R4 = 0 if ($AL eq 0); | ||
| 784 | |||
| 785 | return { | ||
| 786 | "performance" => $ana->{'gain'} / $ana->{'initial_sum'}, | ||
| 787 | "max_performance" => $ana->{'max_gain'} / $ana->{'initial_sum'}, | ||
| 788 | "max_performance_date" => $ana->{'max_gain_date'}, | ||
| 789 | "min_performance" => $ana->{'max_loss'} / $ana->{'initial_sum'}, | ||
| 790 | "min_performance_date" => $ana->{'max_loss_date'}, | ||
| 791 | "max_draw_down" => $ana->{'max_draw_down'}, | ||
| 792 | "max_draw_down_date" => $ana->{'max_draw_down_date'}, | ||
| 793 | "nb_gain" => $ana->{'nb_gain'}, | ||
| 794 | "nb_loss" => $ana->{'nb_loss'}, | ||
| 795 | "win_loss_ratio" => $win_loss_ratio, | ||
| 796 | "biggest_gain" => $ana->{'max_single_gain'}, | ||
| 797 | "biggest_gain_date" => $ana->{'max_single_gain_date'}, | ||
| 798 | "biggest_loss" => $ana->{'max_single_loss'}, | ||
| 799 | "biggest_loss_date" => $ana->{'max_single_loss_date'}, | ||
| 800 | "average_loss" => $average_loss, | ||
| 801 | "average_gain" => $average_gain, | ||
| 802 | "average_performance" => $average_trade, | ||
| 803 | "profit_factor" => $profit_factor, | ||
| 804 | "expectancy" => $expectancy, | ||
| 805 | "global_gain" => $ana->{'gain'}, | ||
| 806 | "gross_gain" => $ana->{'gain'} + $ana->{'commissions'}, | ||
| 807 | "sum_of_gain" => $ana->{'sum_gain'}, | ||
| 808 | "sum_of_loss" => $ana->{'sum_loss'}, | ||
| 809 | "max_consecutive_winner" => $ana->{'max_consec_gain'}, | ||
| 810 | "max_consecutive_winner_date" => $ana->{'max_consec_gain_date'}, | ||
| 811 | "max_consecutive_loser" => $ana->{'max_consec_loss'}, | ||
| 812 | "max_consecutive_loser_date" => $ana->{'max_consec_loss_date'}, | ||
| 813 | "risk_of_ruin" => $R4 | ||
| 814 | }; | ||
| 815 | } | ||
| 816 | |||
| 817 | =pod | ||
| 818 | |||
| 819 | =back | ||
| 820 | |||
| 821 | =cut | ||
| 822 | 1; |