| 1 | package Finance::GeniusTrader::BackTest; | ||
| 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(@EXPORT @ISA); | ||
| 9 | |||
| 10 | require Exporter; | ||
| 11 | @ISA = qw(Exporter); | ||
| 12 | @EXPORT = qw(backtest_single backtest_all backtest_multi); | ||
| 13 | |||
| 14 | use Finance::GeniusTrader::Portfolio; | ||
| 15 | use Finance::GeniusTrader::Prices; | ||
| 16 | use Finance::GeniusTrader::Eval; | ||
| 17 | use Finance::GeniusTrader::Conf; | ||
| 18 | use Finance::GeniusTrader::DateTime; | ||
| 19 | #ALL# use Log::Log4perl qw(:easy); | ||
| 20 | use Finance::GeniusTrader::Indicators::MaxDrawDown; | ||
| 21 | use Finance::GeniusTrader::Tools qw(:timeframe); | ||
| 22 | |||
| 23 | |||
| 24 | =head1 NAME | ||
| 25 | |||
| 26 | Finance::GeniusTrader::BackTest - Backtest trading systems in different conditions | ||
| 27 | |||
| 28 | =head1 OPTIONS | ||
| 29 | |||
| 30 | =over 4 | ||
| 31 | |||
| 32 | =item Analysis::ReferenceTimeFrame | ||
| 33 | |||
| 34 | You can set this configuration item to day, week, month or year. There | ||
| 35 | will be a standardized performance result based on that timeframe. By | ||
| 36 | default the value is "year". | ||
| 37 | |||
| 38 | =back | ||
| 39 | |||
| 40 | =head1 DESCRIPTION | ||
| 41 | |||
| 42 | =over | ||
| 43 | |||
| 44 | =item C<< backtest_single($pf_man, $sys_man, $broker, $calc, $first, $last) >> | ||
| 45 | |||
| 46 | Backtest the a system using the given portfolio manager (ie set of money | ||
| 47 | management rules) on the data contained by $calc during the period $first | ||
| 48 | to $last (indices used by the calculator). | ||
| 49 | |||
| 50 | =cut | ||
| 51 | sub backtest_single { | ||
| 52 | my ($pf_manager, $sys_manager, $broker, $calc, $first, $last) = @_; | ||
| 53 | my $systemname = $sys_manager->get_name; | ||
| 54 | my $broker_object; | ||
| 55 | |||
| 56 | # Create an empty portfolio object and make the manager use it | ||
| 57 | my $p = Finance::GeniusTrader::Portfolio->new; | ||
| 58 | $pf_manager->set_portfolio($p); | ||
| 59 | # XXX: Beuh why do I always need to have to hardcode such a stupid value ? | ||
| 60 | $p->set_initial_value(10000); | ||
| 61 | |||
| 62 | # Set up the broker used for cost calculation | ||
| 63 | if (defined($broker) && $broker) { | ||
| 64 | $broker_object = create_standard_object( | ||
| 65 | split (/\s+/, "Brokers::$broker")); | ||
| 66 | } else { | ||
| 67 | my $broker_module = Finance::GeniusTrader::Conf::get("Brokers::module"); | ||
| 68 | if (defined($broker_module) && $broker_module) { | ||
| 69 | $broker_object = create_standard_object("Brokers::$broker_module"); | ||
| 70 | } | ||
| 71 | } | ||
| 72 | if (defined($broker_object) && $broker_object) { | ||
| 73 | $p->set_broker($broker_object); | ||
| 74 | } | ||
| 75 | |||
| 76 | |||
| 77 | # Calculate the indicators | ||
| 78 | $sys_manager->precalculate_interval($calc, $first, $last); | ||
| 79 | # Run the system | ||
| 80 | for(my $i = $first; $i <= $last; $i++) | ||
| 81 | { | ||
| 82 | # Apply the orders available | ||
| 83 | $p->apply_pending_orders($calc, $i, $systemname, $pf_manager); | ||
| 84 | |||
| 85 | # Manage the open positions | ||
| 86 | foreach my $position ($p->list_open_positions($systemname)) | ||
| 87 | { | ||
| 88 | $p->apply_pending_orders_on_position($position, $calc, $i); | ||
| 89 | if ($position->is_open) | ||
| 90 | { | ||
| 91 | $sys_manager->manage_position($calc, $i, $position, | ||
| 92 | $pf_manager); | ||
| 93 | } | ||
| 94 | } | ||
| 95 | |||
| 96 | # Store the portfolio evaluation | ||
| 97 | $p->store_evaluation($calc->prices->at($i)->[$DATE]); | ||
| 98 | |||
| 99 | # Detect new opportunities | ||
| 100 | $sys_manager->apply_system($calc, $i, $pf_manager); | ||
| 101 | } | ||
| 102 | |||
| 103 | # Close the open positions | ||
| 104 | foreach my $position ($p->list_open_positions($systemname)) | ||
| 105 | { | ||
| 106 | my $close = Finance::GeniusTrader::Portfolio::Order->new; | ||
| 107 | if ($position->is_long) | ||
| 108 | { | ||
| 109 | $close->set_sell_order; | ||
| 110 | } else { | ||
| 111 | $close->set_buy_order; | ||
| 112 | } | ||
| 113 | $close->set_quantity($position->quantity); | ||
| 114 | $close->set_type_limited; | ||
| 115 | $close->set_price($calc->prices->at($last)->[$LAST]); | ||
| 116 | |||
| 117 | $position->add_order($close); | ||
| 118 | $p->apply_pending_orders_on_position($position, $calc, $last); | ||
| 119 | $p->store_evaluation($calc->prices->at($last)->[$DATE]); | ||
| 120 | } | ||
| 121 | |||
| 122 | # Buy & hold | ||
| 123 | my $buyhold = 0; | ||
| 124 | $buyhold = $calc->prices->at($last)->[$LAST] / | ||
| 125 | $calc->prices->at($first)->[$LAST] - 1 if ( $calc->prices->at($first)->[$LAST] != 0); | ||
| 126 | |||
| 127 | # Launch the analysis | ||
| 128 | my $re = $p->real_global_analysis(); | ||
| 129 | $re->{'buyandhold'} = $buyhold; | ||
| 130 | |||
| 131 | # Standardized performance | ||
| 132 | Finance::GeniusTrader::Conf::default("Analysis::ReferenceTimeFrame", "year"); | ||
| 133 | my $tf_name = Finance::GeniusTrader::Conf::get("Analysis::ReferenceTimeFrame"); | ||
| 134 | my $ref_tf = Finance::GeniusTrader::DateTime::name_to_timeframe($tf_name); | ||
| 135 | my $exp = Finance::GeniusTrader::DateTime::timeframe_ratio($ref_tf, $calc->current_timeframe) | ||
| 136 | / ($last - $first + 1); | ||
| 137 | |||
| 138 | $re->{'std_buyandhold'} = (($buyhold + 1) ** $exp) - 1; | ||
| 139 | |||
| 140 | $re->{'std_performance'} = (($re->{'performance'} + 1) ** $exp) - 1; | ||
| 141 | |||
| 142 | $re->{'std_timeframe'} = $tf_name; | ||
| 143 | |||
| 144 | # Complete analysis with some data (first_date and last_date) | ||
| 145 | $re->{'first_date'} = $calc->prices->at($first)->[$DATE]; | ||
| 146 | |||
| 147 | $re->{'last_date'} = $calc->prices->at($last)->[$DATE]; | ||
| 148 | |||
| 149 | my $timeframe = $DAY; | ||
| 150 | if (defined($calc->prices->timeframe)) { | ||
| 151 | $timeframe = $calc->prices->timeframe; | ||
| 152 | } | ||
| 153 | $re->{'duration'} = (Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $re->{'last_date'}) - Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $re->{'first_date'})) / 31557600; | ||
| 154 | |||
| 155 | # Calculate Buy & Hold Max Draw Down with our MaxDrawDown Indicator | ||
| 156 | my $indicator_maxdd = Finance::GeniusTrader::Indicators::MaxDrawDown->new(); | ||
| 157 | $indicator_maxdd->calculate($calc, $last); | ||
| 158 | my $buyandhold_maxdd = $calc->indicators->get($indicator_maxdd->get_name, $last); | ||
| 159 | if (defined($buyandhold_maxdd)) { | ||
| 160 | $re->{'buyandhold_max_draw_down'} = $buyandhold_maxdd; | ||
| 161 | } | ||
| 162 | |||
| 163 | # Hack to remove code reference in portfolio | ||
| 164 | delete $p->{'date2int'}; | ||
| 165 | |||
| 166 | my $analysis = { | ||
| 167 | "real" => $re, | ||
| 168 | "portfolio" => $p | ||
| 169 | }; | ||
| 170 | return $analysis; | ||
| 171 | } | ||
| 172 | |||
| 173 | |||
| 174 | sub backtest_multi { | ||
| 175 | my ($db, $pf_manager, $sys_manager_ref, $broker_ref, $code_ref, $timeframe, $full, $start, $end, $nb_item, $max_loaded_items, $init) = @_; | ||
| 176 | my @sysmanager = @{$sys_manager_ref}; | ||
| 177 | my @brokers = @{$broker_ref}; | ||
| 178 | my @codes = @{$code_ref}; | ||
| 179 | $init = 10000 unless ( defined($init) ); | ||
| 180 | |||
| 181 | # Create an empty portfolio object and make the manager use it | ||
| 182 | my $p = Finance::GeniusTrader::Portfolio->new; | ||
| 183 | $pf_manager->set_portfolio($p); | ||
| 184 | $p->set_initial_value( $init ); | ||
| 185 | |||
| 186 | # Set up the Brokers: | ||
| 187 | my @broker_object = (); | ||
| 188 | my $cnt = 0; | ||
| 189 | foreach my $broker ( @brokers ) { | ||
| 190 | if (defined($broker) && $broker) { | ||
| 191 | $broker_object[$cnt] = create_standard_object(split (/\s+/, "Brokers::$broker")); | ||
| 192 | } else { | ||
| 193 | my $broker_module = Finance::GeniusTrader::Conf::get("Brokers::module"); | ||
| 194 | if (defined($broker_module) && $broker_module) { | ||
| 195 | $broker_object[$cnt] = create_standard_object("Brokers::$broker_module"); | ||
| 196 | } | ||
| 197 | } | ||
| 198 | $cnt++; | ||
| 199 | } | ||
| 200 | |||
| 201 | # Precalc the intervals | ||
| 202 | my $long_first = 0; | ||
| 203 | my $long_last = 0; | ||
| 204 | my $long_code = 0; | ||
| 205 | my @calc; | ||
| 206 | foreach my $i ( 0..$#codes ) { | ||
| 207 | |||
| 208 | my ($calc, $first, $last) = find_calculator($db, $codes[$i], $timeframe, $full, $start, $end, $nb_item, $max_loaded_items); | ||
| 209 | |||
| 210 | $calc[$i] = $calc; | ||
| 211 | |||
| 212 | # Set this code as reference if possible | ||
| 213 | if ( ($last - $first) > ($long_last - $long_first) ) { | ||
| 214 | $long_last = $last; | ||
| 215 | $long_first = $first; | ||
| 216 | $long_code = $i; | ||
| 217 | } | ||
| 218 | |||
| 219 | # print STDERR $calc->code() . " --> " . $first . " / " . $last . "\n"; | ||
| 220 | |||
| 221 | # Insert the calc_ojects in the portfolio.. | ||
| 222 | $p->{objects}->{calc}->{$calc->code()} = $calc; | ||
| 223 | |||
| 224 | foreach my $j ( 0..$#sysmanager ) { | ||
| 225 | |||
| 226 | $sysmanager[$j]->precalculate_interval($calc, $first, $last); | ||
| 227 | |||
| 228 | } | ||
| 229 | } | ||
| 230 | |||
| 231 | print STDERR "LONG-CODE: " . $calc[$long_code]->code() . "\n"; | ||
| 232 | print STDERR "LONG-FIRST: " . $long_first . "\n"; | ||
| 233 | print STDERR "LONG-LAST: " . $long_last . "\n"; | ||
| 234 | |||
| 235 | print STDERR "LONG-FIRST: " . $calc[$long_code]->prices->at($long_first)->[$DATE] . "\n"; | ||
| 236 | print STDERR "LONG-LAST: " . $calc[$long_code]->prices->at($long_last)->[$DATE] . "\n"; | ||
| 237 | |||
| 238 | # Run the system | ||
| 239 | for(my $i = $long_first; $i <= $long_last; $i++) { | ||
| 240 | |||
| 241 | my $date = $calc[$long_code]->prices->at($i)->[$DATE]; | ||
| 242 | |||
| 243 | $pf_manager->submit_parked_orders(); | ||
| 244 | |||
| 245 | foreach my $j ( 0..$#sysmanager ) { | ||
| 246 | my $systemname = $sysmanager[$j]->get_name; | ||
| 247 | |||
| 248 | # Set the right broker | ||
| 249 | if (defined($broker_object[$j]) && $broker_object[$j]) { | ||
| 250 | $p->set_broker($broker_object[$j]); | ||
| 251 | } | ||
| 252 | foreach my $calc ( @calc ) { | ||
| 253 | next if (!$calc->prices->has_date($date)); | ||
| 254 | my $ii = $calc->prices->date($date); | ||
| 255 | |||
| 256 | # Apply the orders available | ||
| 257 | $p->apply_pending_orders($calc, $ii, $systemname, $pf_manager); | ||
| 258 | |||
| 259 | # Manage the open positions | ||
| 260 | foreach my $position ($p->list_open_positions($systemname)) { | ||
| 261 | $p->apply_pending_orders_on_position($position, $calc, $ii); | ||
| 262 | if ($position->is_open) { | ||
| 263 | $sysmanager[$j]->manage_position($calc, $ii, $position, | ||
| 264 | $pf_manager); | ||
| 265 | } | ||
| 266 | } | ||
| 267 | # Store the portfolio evaluation | ||
| 268 | $p->store_evaluation($calc->prices->at($ii)->[$DATE]); | ||
| 269 | } | ||
| 270 | } | ||
| 271 | |||
| 272 | foreach my $j ( 0..$#sysmanager ) { | ||
| 273 | my $systemname = $sysmanager[$j]->get_name; | ||
| 274 | my $sys_manager = $sysmanager[$j]; | ||
| 275 | |||
| 276 | # Try out the signals for all codes | ||
| 277 | foreach my $calc ( @calc ) { | ||
| 278 | |||
| 279 | next if (!$calc->prices->has_date($date)); | ||
| 280 | my $ii = $calc->prices->date($date); | ||
| 281 | |||
| 282 | # Detect new opportunities | ||
| 283 | $sys_manager->apply_system_parked($calc, $ii, $pf_manager); | ||
| 284 | |||
| 285 | } | ||
| 286 | } | ||
| 287 | |||
| 288 | } | ||
| 289 | |||
| 290 | |||
| 291 | # Close the open positions | ||
| 292 | foreach my $j ( 0..$#sysmanager ) { | ||
| 293 | my $systemname = $sysmanager[$j]->get_name; | ||
| 294 | |||
| 295 | foreach my $position ($p->list_open_positions($systemname)) { | ||
| 296 | |||
| 297 | foreach my $calc ( @calc ) { | ||
| 298 | |||
| 299 | next if ($position->code() ne $calc->code()); | ||
| 300 | |||
| 301 | my $close = Finance::GeniusTrader::Portfolio::Order->new; | ||
| 302 | if ($position->is_long) { | ||
| 303 | $close->set_sell_order; | ||
| 304 | } else { | ||
| 305 | $close->set_buy_order; | ||
| 306 | } | ||
| 307 | $close->set_quantity($position->quantity); | ||
| 308 | $close->set_type_limited; | ||
| 309 | |||
| 310 | my $last_date = $calc->prices->find_nearest_date( $calc[$long_code]->prices->at($long_last)->[$DATE] ); | ||
| 311 | my $last = $calc->prices->date( $last_date ); | ||
| 312 | $close->set_price($calc->prices->at($last)->[$LAST]); | ||
| 313 | $position->add_order($close); | ||
| 314 | $p->apply_pending_orders_on_position($position, $calc, $last); | ||
| 315 | $p->store_evaluation($calc->prices->at($last)->[$DATE]); | ||
| 316 | |||
| 317 | last; | ||
| 318 | } | ||
| 319 | } | ||
| 320 | |||
| 321 | } | ||
| 322 | |||
| 323 | # Delete the parked orders | ||
| 324 | $pf_manager->delete_parked_orders(); | ||
| 325 | |||
| 326 | # Buy & hold | ||
| 327 | my $buyhold = 0; #$calc->prices->at($last)->[$LAST] / | ||
| 328 | #$calc->prices->at($first)->[$LAST] - 1; | ||
| 329 | |||
| 330 | # Launch the analysis | ||
| 331 | my $re = $p->real_global_analysis(); | ||
| 332 | my $th = {}; #$p->theoretical_analysis_by_code($calc->code); | ||
| 333 | $re->{'buyandhold'} = $buyhold; | ||
| 334 | $th->{'buyandhold'} = $buyhold; | ||
| 335 | |||
| 336 | # # Standardized performance | ||
| 337 | Finance::GeniusTrader::Conf::default("Analysis::ReferenceTimeFrame", "year"); | ||
| 338 | my $tf_name = Finance::GeniusTrader::Conf::get("Analysis::ReferenceTimeFrame"); | ||
| 339 | my $ref_tf = Finance::GeniusTrader::DateTime::name_to_timeframe($tf_name); | ||
| 340 | my $exp = Finance::GeniusTrader::DateTime::timeframe_ratio($ref_tf, $calc[0]->current_timeframe) | ||
| 341 | / ($long_last - $long_first + 1); | ||
| 342 | |||
| 343 | $re->{'std_buyandhold'} = (($buyhold + 1) ** $exp) - 1; | ||
| 344 | $th->{'std_buyandhold'} = (($buyhold + 1) ** $exp) - 1; | ||
| 345 | |||
| 346 | $re->{'std_performance'} = (($re->{'performance'} + 1) ** $exp) - 1; | ||
| 347 | $th->{'std_performance'} = (($th->{'performance'} + 1) ** $exp) - 1; | ||
| 348 | |||
| 349 | $re->{'std_timeframe'} = $tf_name; | ||
| 350 | $th->{'std_timeframe'} = $tf_name; | ||
| 351 | |||
| 352 | # # Complete analysis with some data (first_date and last_date) | ||
| 353 | $re->{'first_date'} = $calc[$long_code]->prices->at($long_first)->[$DATE]; | ||
| 354 | $th->{'first_date'} = $calc[$long_code]->prices->at($long_first)->[$DATE]; | ||
| 355 | $re->{'last_date'} = $calc[$long_code]->prices->at($long_last)->[$DATE]; | ||
| 356 | $th->{'last_date'} = $calc[$long_code]->prices->at($long_last)->[$DATE]; | ||
| 357 | |||
| 358 | $re->{'duration'} = (Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $re->{'last_date'}) - Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $re->{'first_date'})) / 31557600; | ||
| 359 | $th->{'duration'} = (Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $re->{'last_date'}) - Finance::GeniusTrader::DateTime::map_date_to_time($timeframe, $re->{'first_date'})) / 31557600; | ||
| 360 | |||
| 361 | # Calculate Buy & Hold Max Draw Down with our MaxDrawDown Indicator | ||
| 362 | # my $indicator_maxdd = Finance::GeniusTrader::Indicators::MaxDrawDown->new(); | ||
| 363 | # $indicator_maxdd->calculate($calc, $last); | ||
| 364 | # my $buyandhold_maxdd = $calc->indicators->get($indicator_maxdd->get_name, $last); | ||
| 365 | # if (defined($buyandhold_maxdd)) { | ||
| 366 | # $re->{'buyandhold_max_draw_down'} = $buyandhold_maxdd; | ||
| 367 | # $th->{'buyandhold_max_draw_down'} = $buyandhold_maxdd; | ||
| 368 | # } | ||
| 369 | ### NOTE: Need to assign something to these to avoid undef value in output | ||
| 370 | $re->{'buyandhold_max_draw_down'} = 0; | ||
| 371 | $th->{'buyandhold_max_draw_down'} = 0; | ||
| 372 | |||
| 373 | |||
| 374 | # Hack to remove code reference in portfolio | ||
| 375 | delete $p->{'date2int'}; | ||
| 376 | |||
| 377 | my $analysis = { | ||
| 378 | "theoretical" => $th, | ||
| 379 | "real" => $re, | ||
| 380 | "portfolio" => $p | ||
| 381 | }; | ||
| 382 | |||
| 383 | return $analysis; | ||
| 384 | } | ||
| 385 | |||
| 386 | |||
| 387 | =item C<< Finance::GeniusTrader::BackTest::combinate_system_and_manager(\@systems, \@managers) >> | ||
| 388 | |||
| 389 | Returns a hash that can be used by backtest_combinations | ||
| 390 | |||
| 391 | =cut | ||
| 392 | sub combinate_system_and_manager { | ||
| 393 | my ($self, $systems, $managers) = @_; | ||
| 394 | |||
| 395 | my $combi = {}; | ||
| 396 | foreach (@{$systems}) | ||
| 397 | { | ||
| 398 | $combi->{$_->get_name}{"system"} = $_; | ||
| 399 | $combi->{$_->get_name}{"managers"} = $managers; | ||
| 400 | } | ||
| 401 | return $combi; | ||
| 402 | } | ||
| 403 | |||
| 404 | =item C<< Finance::GeniusTrader::BackTest::create_managers_with_filters(\@filters) >> | ||
| 405 | |||
| 406 | Create all possible managers with all the possible combinations | ||
| 407 | of filters. | ||
| 408 | |||
| 409 | =cut | ||
| 410 | sub create_managers_with_filters { | ||
| 411 | |||
| 412 | my $managers = {}; | ||
| 413 | |||
| 414 | |||
| 415 | |||
| 416 | return $managers; | ||
| 417 | } | ||
| 418 | |||
| 419 | =pod | ||
| 420 | |||
| 421 | =back | ||
| 422 | |||
| 423 | =cut | ||
| 424 | 1; |