Framework/TradingCalendar.pm untested

filter: Statementstmt 0.0% 0 / 496 Branchbran 0.0% 0 / 162 Conditioncond 0.0% 0 / 125 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 76 Podpod 0.0% 0 / 55 totaltotal 0.0% 0 / 914 CC 82 SCAR 35.1
CC
82
Cov
0%
_market_opens
210.0
_get_exchange_open_times
72.0
_find_dst_switch
42.0
CRAP 33.6
1 package Quant::Framework::TradingCalendar;
2  
3 =head1 NAME
4  
5 Quant::Framework::TradingCalendar
6  
7 =head1 DESCRIPTION
8  
9 This module is responsible about everything related to time-based status of an exchange (whether exchange is open/closed, has holiday, is partially open, ...)
10 Plus all related helper modules (trading days between two days where exchange is open, trading breaks, DST effect, open/close time, ...).
11 One important feature of this module is that it is designed for READING information not writing.
12  
13 =cut
14  
15 =head1 USAGE
16  
17 my $calendar = Quant::Framework::TradingCalendar->new({
18 symbol => 'LSE',
19 chronicle_reader => $chronicle_r,
20 });
21  
22 =cut
23  
24 use strict;
25 use warnings;
26 use feature 'state';
27  
28 use Moose;
29 use DateTime;
30 use DateTime::TimeZone;
31 use List::Util qw(min max);
32 use Memoize;
33 use Carp;
34 use Scalar::Util qw(looks_like_number);
35 use File::ShareDir ();
36 use Data::Chronicle::Reader;
37  
38 use Quant::Framework::Holiday;
39 use Quant::Framework::PartialTrading;
40 use Date::Utility;
41 use Memoize::HashKey::Ignore;
42 use Time::Duration::Concise;
43 use YAML::XS qw(LoadFile);
44 use Clone qw(clone);
45  
46 # We're going to do this from time to time.
47 # I claim it's under control.
48 ## no critic(TestingAndDebugging::ProhibitNoWarnings)
49 no warnings 'recursion';
50  
51 =head1 ATTRIBUTES
52  
53 =head2 symbol
54  
55 The standard symbol used to reference this exchange
56  
57 =cut
58  
59 has symbol => (
60 is => 'ro',
61 isa => 'Str',
62 );
63  
64 =head2 underlying_config
65  
66 UnderlyingConfig used for query on weighting of an underlying. Not required if this modules is not used for
67 that purpose.
68  
69 =cut
70  
71 has underlying_config => (
72 is => 'ro',
73 isa => 'Quant::Framework::Utils::UnderlyingConfig',
74 );
75  
76 =head2 locale
77  
78 localization language (default is 'en')
79  
80 =cut
81  
82 has locale => (
83 is => 'ro',
84 default => 'EN'
85 );
86  
87 =head2 chronicle_reader
88  
89 Used to work with Chronicle storage data (Holidays and Partial trading data)
90  
91 =cut
92  
93 has chronicle_reader => (
94 is => 'ro',
95 isa => 'Data::Chronicle::Reader',
96 );
97  
98 =head2 for_date
99  
100 for_date is to for historical search of holiday information
101  
102 =cut
103  
104 has for_date => (
105 is => 'ro',
106 );
107  
108 =head2 holidays
109  
110 The hashref mapping of the days_since_epoch of all the holidays to their
111 descriptions or weights. If the weight is non-zero, the exchange still trades on
112 that day.
113  
114 =cut
115  
116 has holidays => (
117 is => 'ro',
118 lazy_build => 1,
119 );
120  
121 sub _build_holidays {
122 my $self = shift;
123  
124 my $ref = Quant::Framework::Holiday::get_holidays_for($self->chronicle_reader, $self->symbol, $self->for_date);
125 my %exchange_holidays = map { Date::Utility->new($_)->days_since_epoch => $ref->{$_} } keys %$ref;
126  
127 return \%exchange_holidays;
128 }
129  
130 =head2 pseudo_holidays
131  
132 These are holidays defined by us. During this period, market is still open but less volatile.
133  
134 =cut
135  
136 has pseudo_holidays => (
137 is => 'ro',
138 lazy => 1,
139 builder => '_build_pseudo_holidays',
140 );
141  
142 sub _build_pseudo_holidays {
143 my $self = shift;
144  
145 # pseudo-holidays for exchanges are 1 week before and after Christmas Day.
146 my $year = $self->for_date ? $self->for_date->year : Date::Utility->new->year;
147 my $christmas_day = Date::Utility->new('25-Dec-' . $year);
148 my $pseudo_start = $christmas_day->minus_time_interval('7d');
149 my %pseudo_holidays = map { $pseudo_start->plus_time_interval($_ . 'd')->days_since_epoch => 'pseudo-holiday' } (0 .. 14);
150  
151 return \%pseudo_holidays;
152 }
153  
154 has [qw(early_closes late_opens)] => (
155 is => 'ro',
156 lazy_build => 1,
157 );
158  
159 sub _build_early_closes {
160 my $self = shift;
161  
162 my $ref = Quant::Framework::PartialTrading->new({
163 chronicle_reader => $self->chronicle_reader,
164 type => 'early_closes'
165 })->get_partial_trading_for($self->symbol, $self->for_date);
166 my %early_closes = map { Date::Utility->new($_)->days_since_epoch => $ref->{$_} } keys %$ref;
167  
168 return \%early_closes;
169 }
170  
171 sub _build_late_opens {
172 my $self = shift;
173  
174 my $ref = Quant::Framework::PartialTrading->new({
175 chronicle_reader => $self->chronicle_reader,
176 type => 'late_opens'
177 })->get_partial_trading_for($self->symbol, $self->for_date);
178 my %late_opens = map { Date::Utility->new($_)->days_since_epoch => $ref->{$_} } keys %$ref;
179  
180 return \%late_opens;
181 }
182  
183 ## attribute market_times
184 #
185 # A hashref of human-readable times, which are converted to epochs for a given day
186 #
187 has market_times => (
188 is => 'ro',
189 isa => 'HashRef',
190 default => sub { return {}; },
191 );
192  
193 has is_affected_by_dst => (
194 is => 'ro',
195 isa => 'Bool',
196 lazy_build => 1,
197 );
198  
199 =head2 trading_days
200  
201 An exchange's trading day category. The list is enumerated in the exchanges_trading_days_aliases.yml file.
202  
203 =cut
204  
205 has trading_days => (
206 is => 'ro',
207 default => 'weekdays',
208 );
209  
210 =head2 trading_days_list
211  
212 List the trading day index which defined on exchanges_trading_days_aliases.yml
213  
214 =cut
215  
216 has trading_days_list => (
217 is => 'ro',
218 isa => 'ArrayRef',
219 lazy_build => 1,
220 );
221  
222 my $trading_days_aliases;
223  
224 BEGIN {
225 $trading_days_aliases = YAML::XS::LoadFile(File::ShareDir::dist_file('Quant-Framework', 'exchanges_trading_days_aliases.yml'));
226 }
227  
228 sub _build_trading_days_list {
229  
230 my $self = shift;
231 return \@{$trading_days_aliases->{$self->trading_days}};
232  
233 }
234  
235 =head2 trading_timezone
236  
237  
238 The timezone in which the exchange conducts business.
239  
240 This should be a string which will allow the standard DateTime modules to find the proper information.
241  
242 =cut
243  
244 has [qw(trading_timezone)] => (
245 is => 'ro',
246 isa => 'Maybe[Str]',
247 );
248  
249 =head2 BUILDARGS
250  
251 Internal method to pre-process construction arguments
252  
253 =cut
254  
255 my $exchanges;
256  
257 BEGIN {
258 $exchanges = YAML::XS::LoadFile(File::ShareDir::dist_file('Quant-Framework', 'exchange.yml'));
259 }
260  
261 sub BUILDARGS {
262 my ($class, $orig_params_ref) = @_;
263  
264 my $symbol = $orig_params_ref->{symbol};
265  
266 croak "Exchange symbol must be specified" unless $symbol;
267 my $params_ref = clone($exchanges->{$symbol});
268 $params_ref = {%$params_ref, %$orig_params_ref};
269  
270 my $locale = $orig_params_ref->{locale} // 'EN';
271  
272 foreach my $key (keys %{$params_ref->{market_times}}) {
273 foreach my $trading_segment (keys %{$params_ref->{market_times}->{$key}}) {
274 if ($trading_segment eq 'day_of_week_extended_trading_breaks') { next; }
275 elsif ($trading_segment ne 'trading_breaks') {
276 $params_ref->{market_times}->{$key}->{$trading_segment} = Time::Duration::Concise::Localize->new(
277 interval => $params_ref->{market_times}->{$key}->{$trading_segment},
278 locale => $locale,
279 );
280 } else {
281 my $break_intervals = $params_ref->{market_times}->{$key}->{$trading_segment};
282 my @converted;
283 foreach my $int (@$break_intervals) {
284 my $open_int = Time::Duration::Concise::Localize->new(
285 interval => $int->[0],
286 locale => $locale,
287 );
288 my $close_int = Time::Duration::Concise::Localize->new(
289 interval => $int->[1],
290 locale => $locale,
291 );
292 push @converted, [$open_int, $close_int];
293 }
294 $params_ref->{market_times}->{$key}->{$trading_segment} = \@converted;
295 }
296 }
297 }
298  
299 return $params_ref;
300 }
301  
302 =head1 METHODS
303  
304 =head2 new($symbol)
305  
306 Returns object for given exchange. Accepts single parameter - exchange symbol.
307  
308 =cut
309  
310 has _build_time => (
311 is => 'ro',
312 default => sub { time },
313 );
314  
315 # we cache objects, when we're getting object from cache we should check if it isn't too old
316 # currently we allow age to be up to 30 seconds
317 sub _object_expired {
318 return shift->_build_time + 30 < time;
319 }
320  
321 =head2 simple_weight_on
322  
323 Returns the weight assigned to the day of a given Date::Utility object. Return 0
324 if the exchange does not trade on this day and 1 if there is no pseudo-holiday.
325  
326 =cut
327  
328 sub simple_weight_on {
329 my ($self, $when) = @_;
330  
331 return 0 if not $self->trades_on($when);
332 return 0.5 if exists $self->pseudo_holidays->{$when->days_since_epoch};
333 return 1;
334 }
335  
336 =head2 has_holiday_on
337  
338 Returns true if the exchange has a holiday on the day of a given Date::Utility
339 object.
340  
341 =cut
342  
343 sub has_holiday_on {
344 my ($self, $when) = @_;
345  
346 return $self->holidays->{$when->days_since_epoch};
347 }
348  
349 =head2 trades_on
350  
351 Returns true if trading is done on the day of a given Date::Utility.
352  
353 =cut
354  
355 sub trades_on {
356 my ($self, $when) = @_;
357  
358 state %trades_cache;
359  
360 my $really_when = $self->trading_date_for($when);
361 my $days_since = $really_when->days_since_epoch;
362 my $symbol = $self->symbol;
363 $trades_cache{$symbol}->{$days_since} //=
364 (@{$self->trading_days_list}[$really_when->day_of_week] and not $self->has_holiday_on($really_when)) ? 1 : 0;
365  
366 return $trades_cache{$symbol}->{$days_since};
367 }
368  
369 =head2 trade_date_after
370  
371 Returns a Date::Utility for the date on which trading is open after the given Date::Utility
372  
373 =cut
374  
375 sub trade_date_after {
376 my ($self, $when) = @_;
377  
378 my $date_next;
379 my $counter = 1;
380 my $begin = $self->trading_date_for($when);
381  
382 while (not $date_next and $counter <= 15) {
383 my $possible = $begin->plus_time_interval($counter . 'd');
384 $date_next = ($self->trades_on($possible)) ? $possible : undef;
385 $counter++;
386 }
387  
388 return $date_next;
389 }
390  
391 =head2 trading_date_for
392  
393 The date on which trading is considered to be taking place even if it is not the same as the GMT date.
394  
395 Returns a Date object representing midnight GMT of the trading date.
396  
397 Note that this does not handle trading dates are offset forward beyond the next day (24h). It will need additional work if these are found to exist.
398  
399 =cut
400  
401 sub trading_date_for {
402 my ($self, $date) = @_;
403  
404 return $date->truncate_to_day unless ($self->trading_date_can_differ);
405  
406 my $next_day = $date->plus_time_interval('1d')->truncate_to_day;
407 my $open_ti =
408 $self->market_times->{$self->_times_dst_key($next_day)}->{daily_open};
409  
410 return ($open_ti and $next_day->epoch + $open_ti->seconds <= $date->epoch)
411 ? $next_day
412 : $date->truncate_to_day;
413  
414 }
415  
416 has trading_date_can_differ => (
417 is => 'ro',
418 isa => 'Bool',
419 lazy_build => 1,
420 init_arg => undef,
421 );
422  
423 # This presumes we only ever move on the open side, never past the end of a day.
424 sub _build_trading_date_can_differ {
425 my $self = shift;
426 my @premidnight_opens =
427 grep { $_->seconds < 0 }
428 map { $self->market_times->{$_}->{daily_open} }
429 grep { exists $self->market_times->{$_}->{daily_open} }
430 keys %{$self->market_times};
431 return (scalar @premidnight_opens) ? 1 : 0;
432 }
433  
434 =head2 calendar_days_to_trade_date_after
435  
436 Returns the number of calendar days between a given Date::Utility
437 and the next day on which trading is open.
438  
439 =cut
440  
441 sub calendar_days_to_trade_date_after {
442 my ($self, $when) = @_;
443  
444 return $self->trade_date_after($when)->days_between($when);
445 }
446 Memoize::memoize('calendar_days_to_trade_date_after', NORMALIZER => '_normalize_on_dates');
447  
448 =head2 trade_date_before
449  
450 Returns a Date::Utility representing the trading day before a given Date::Utility
451  
452 If given the additional arg 'lookback', will look back X number of
453 trading days, rather than just one.
454  
455 =cut
456  
457 sub trade_date_before {
458 my ($self, $when, $additional_args) = @_;
459  
460 my $begin = $self->trading_date_for($when);
461 my $lookback = (ref $additional_args) ? $additional_args->{'lookback'} : 1;
462  
463 my $date_behind;
464 my $counter = 0;
465  
466 while (not $date_behind and $counter < 15) {
467 my $possible = $begin->minus_time_interval(($lookback + $counter) . 'd');
468 $date_behind =
469 ($self->trades_on($possible) and $self->trading_days_between($possible, $when) == $lookback - 1) ? $possible : undef;
470 $counter++;
471 }
472  
473 return $date_behind;
474 }
475  
476 sub _days_between {
477  
478 my ($self, $begin, $end) = @_;
479  
480 my @days_between = ();
481  
482 # Don't include start and end days.
483 my $current = $begin->truncate_to_day->plus_time_interval('1d');
484 $end = $end->truncate_to_day->minus_time_interval('1d');
485  
486 # Generate all days between.
487 while (not $current->is_after($end)) {
488 push @days_between, $current;
489 $current = $current->plus_time_interval('1d'); # Next day, please!
490 }
491  
492 return \@days_between;
493 }
494 Memoize::memoize('_days_between', NORMALIZER => '_normalize_on_dates');
495  
496 =head2 trading_days_between
497  
498 Returns the number of trading days _between_ two given dates.
499  
500 $exchange->trading_days_between(Date::Utility->new('4-May-10'),Date::Utility->new('5-May-10'));
501  
502 =cut
503  
504 sub trading_days_between {
505 my ($self, $begin, $end) = @_;
506  
507 # Count up how many are trading days.
508 return scalar grep { $self->trades_on($_) } @{$self->_days_between($begin, $end)};
509 }
510 Memoize::memoize('trading_days_between', NORMALIZER => '_normalize_on_dates');
511  
512 =head2 holiday_days_between
513  
514 Returns the number of holidays _between_ two given dates.
515  
516 $exchange->trading_days_between(Date::Utility->new('4-May-10'),Date::Utility->new('5-May-10'));
517  
518 =cut
519  
520 sub holiday_days_between {
521 my ($self, $begin, $end) = @_;
522  
523 # Count up how many are trading days.
524 return scalar grep { $self->has_holiday_on($_) } @{$self->_days_between($begin, $end)};
525 }
526 Memoize::memoize('holiday_days_between', NORMALIZER => '_normalize_on_dates');
527  
528 =head1 OPEN/CLOSED QUESTIONS ETC.
529  
530 Quant::Framework::TradingCalendar can be questioned about various things related to opening/closing.
531 The following shows all these questions via code examples:
532  
533 =head2 is_open
534  
535 if ($self->is_open)
536  
537 =cut
538  
539 sub is_open {
540 my $self = shift;
541 return $self->is_open_at(time);
542 }
543  
544 =head2 is_open_at
545  
546 if ($self->is_open_at($epoch))
547  
548 =cut
549  
550 sub is_open_at {
551 my ($self, $when) = @_;
552  
553 my $open;
554 my $date = (ref $when) ? $when : Date::Utility->new($when);
555 if (my $opening = $self->opening_on($date)) {
556 $open = 1
557 if (not $date->is_before($opening)
558 and not $date->is_after($self->closing_on($date)));
559 if ($self->is_in_trading_break($date)) {
560 $open = undef;
561 }
562 }
563  
564 return $open;
565 }
566  
567 =head2 will_open
568  
569 if ($self->will_open)
570  
571 =cut
572  
573 sub will_open {
574 my $self = shift;
575 return $self->will_open_after(time);
576 }
577  
578 =head2 will_open_after
579  
580 if ($self->will_open_after($epoch))
581  
582 =cut
583  
584 sub will_open_after {
585 my ($self, $epoch) = @_;
586  
587 # basically, if open is "0", but not undef. Annoying _market_opens logic
588 if (defined $self->_market_opens($epoch)->{'open'}
589 and not $self->_market_opens($epoch)->{'open'})
590 {
591 return 1;
592 }
593 return;
594 }
595  
596 =head2 seconds_since_open_at
597  
598 my $seconds = $self->seconds_since_open_at($epoch);
599  
600 =cut
601  
602 sub seconds_since_open_at {
603 my ($self, $epoch) = @_;
604 return $self->_market_opens($epoch)->{'opened'};
605 }
606  
607 =head2 seconds_since_close_at
608  
609 my $seconds = $self->seconds_since_close_at($epoch);
610  
611 =cut
612  
613 sub seconds_since_close_at {
614 my ($self, $epoch) = @_;
615 return $self->_market_opens($epoch)->{'closed'};
616 }
617  
618 ## PRIVATE _market_opens
619 #
620 # PARAMETERS :
621 # - time : the time as a timestamp
622 #
623 # RETURNS : A reference to a hash with the following keys:
624 # - open : is set to 1 if the market is currently open, 0 if market is closed
625 # but will open, 'undef' if market is closed and will not open again
626 # today.
627 # - closed : undefined if market has not been open yet, otherwise contains the
628 # seconds for how long the market was closed.
629 # - opens : undefined if market is currently open and does not open anymore today,
630 # otherwise the market will open in 'opens' seconds.
631 # - closes : undefined if open is undef, otherwise market will close in 'closes' seconds.
632 # - opened : undefined if market is closed, contains the seconds the market has
633 # been open.
634 #
635 #
636 ########
637 sub _market_opens {
638 my ($self, $time) = @_;
639  
640 # Date::Utility should handle this, but let's not bother;
641 my $when = (ref $time) ? $time : Date::Utility->new($time);
642 my $date = $when;
643  
644 # Figure out which "trading day" we are on
645 # even if it differs from the GMT calendar day.
646 my $next_day = $date->plus_time_interval('1d')->truncate_to_day;
647 my $next_open = $self->opening_on($next_day);
648 $date = $next_day if ($next_open and not $date->is_before($next_open));
649  
650 my $open = $self->opening_on($date);
651 my $close = $self->closing_on($date);
652  
653 if (not $open) {
654  
655 # date is not a trading day: will not and has not been open today
656 my $next_open = $self->opening_on($self->trade_date_after($when));
657 return {
658 open => undef,
659 opens => $next_open->epoch - $when->epoch,
660 opened => undef,
661 closes => undef,
662 closed => undef,
663 };
664 }
665  
666 my $breaks = $self->trading_breaks($when);
667 # not trading breaks
668 if (not $breaks) {
669 # Past closing time: opens next trading day, and has been open today
670 if ($close and not $when->is_before($close)) {
671 return {
672 open => undef,
673 opens => undef,
674 opened => $when->epoch - $open->epoch,
675 closes => undef,
676 closed => $when->epoch - $close->epoch,
677 };
678 } elsif ($when->is_before($open)) {
679 return {
680 open => 0,
681 opens => $open->epoch - $when->epoch,
682 opened => undef,
683 closes => $close->epoch - $when->epoch,
684 closed => undef,
685 };
686 } elsif ($when->is_same_as($open) or ($when->is_after($open) and $when->is_before($close)) or $when->is_same_same($close)) {
687 return {
688 open => 1,
689 opens => undef,
690 opened => $when->epoch - $open->epoch,
691 closes => $close->epoch - $when->epoch,
692 closed => undef,
693 };
694 }
695 } else {
696 my @breaks = @$breaks;
697 # Past closing time: opens next trading day, and has been open today
698 if ($close and not $when->is_before($close)) {
699 return {
700 open => undef,
701 opens => undef,
702 opened => $when->epoch - $breaks[-1][1]->epoch,
703 closes => undef,
704 closed => $when->epoch - $close->epoch,
705 };
706 } elsif ($when->is_before($open)) {
707 return {
708 open => 0,
709 opens => $open->epoch - $when->epoch,
710 opened => undef,
711 closes => $breaks[0][0]->epoch - $when->epoch,
712 closed => undef,
713 };
714 } else {
715 my $current_open = $open;
716 for (my $i = 0; $i <= $#breaks; $i++) {
717 my $int_open = $breaks[$i][0];
718 my $int_close = $breaks[$i][1];
719 my $next_open = exists $breaks[$i + 1] ? $breaks[$i + 1][0] : $close;
720  
721 if ($when->is_after($current_open) and $when->is_before($int_open)) {
722 return {
723 open => 1,
724 opens => undef,
725 opened => $when->epoch - $current_open->epoch,
726 closes => $int_open->epoch - $when->epoch,
727 closed => undef,
728 };
729 } elsif ($when->is_same_as($int_open)
730 or ($when->is_after($int_open) and $when->is_before($int_close))
731 or $when->is_same_as($int_close))
732 {
733 return {
734 open => 0,
735 opens => $int_close->epoch - $when->epoch,
736 opened => undef,
737 closes => $close->epoch - $when->epoch, # we want to know seconds to official close
738 closed => $when->epoch - $int_open->epoch,
739 };
740 } elsif ($when->is_after($int_close) and $when->is_before($next_open)) {
741 return {
742 open => 1,
743 opens => undef,
744 opened => $when->epoch - $int_close->epoch,
745 closes => $next_open->epoch - $when->epoch,
746 closed => undef,
747 };
748 }
749 }
750  
751 }
752 }
753  
754 return;
755 }
756  
757 =head1 OPENING TIMES
758  
759 The following methods tell us when the exchange opens/closes on a given date.
760  
761 =head2 opening_on
762  
763 Returns the opening time (Date::Utility) of the exchange for a given Date::Utility.
764  
765 my $opening_epoch = $exchange->opening_on(Date::Utility->new('25-Dec-10')); # returns undef (given Xmas is a holiday)
766  
767 =cut
768  
769 sub opening_on {
770 my ($self, $when) = @_;
771  
772 return $self->opens_late_on($when) // $self->_get_exchange_open_times($when, 'daily_open');
773 }
774  
775 =head2 closing_on
776  
777 Similar to opening_on.
778  
779 my $closing_epoch = $exchange->closing_on(Date::Utility->new('25-Dec-10')); # returns undef (given Xmas is a holiday)
780  
781 =cut
782  
783 sub closing_on {
784 my ($self, $when) = @_;
785  
786 return $self->closes_early_on($when) // $self->_get_exchange_open_times($when, 'daily_close');
787 }
788  
789 =head2 standard_closing_on
790  
791 This is used to fetch regular non dst closing time for an exchange.
792  
793 =cut
794  
795 sub standard_closing_on {
796 my ($self, $when) = @_;
797  
798 $when = $self->trading_date_for($when);
799  
800 return $self->closes_early_on($when) if (($self->symbol eq 'FOREX' or $self->symbol eq 'METAL') and $when->day_of_week == 5);
801 return $when->truncate_to_day->plus_time_interval($self->market_times->{standard}->{daily_close});
802 }
803  
804 =head2 settlement_on
805  
806 Similar to opening_on.
807  
808 my $settlement_epoch = $exchange->settlement_on(Date::Utility->new('25-Dec-10')); # returns undef (given Xmas is a holiday)
809  
810 =cut
811  
812 sub settlement_on {
813 my ($self, $when) = @_;
814  
815 return $self->_get_exchange_open_times($when, 'daily_settlement');
816 }
817  
818 =head2 trading_breaks
819  
820 Defines the breaktime for this exchange.
821  
822 =cut
823  
824 sub trading_breaks {
825 my ($self, $when) = @_;
826 return $self->_get_exchange_open_times($when, 'trading_breaks');
827 }
828  
829 =head2 is_in_trading_break
830  
831 Given an epoch returns true if exchange in in break time
832  
833 =cut
834  
835 sub is_in_trading_break {
836 my ($self, $when) = @_;
837  
838 $when = Date::Utility->new($when);
839 my $in_trading_break = 0;
840 if (my $breaks = $self->trading_breaks($when)) {
841 foreach my $break_interval (@{$breaks}) {
842 if ($when->epoch >= $break_interval->[0]->epoch and $when->epoch <= $break_interval->[1]->epoch) {
843 $in_trading_break++;
844 last;
845 }
846 }
847 }
848  
849 return $in_trading_break;
850 }
851  
852 =head2 closes_early_on
853  
854 Returns true if the exchange closes early on the given date.
855  
856 =cut
857  
858 sub closes_early_on {
859 my ($self, $when) = @_;
860  
861 my $closes_early;
862 if ($self->trades_on($when)) {
863 my $listed = $self->early_closes->{$when->days_since_epoch};
864 if ($listed) {
865 $closes_early = $when->truncate_to_day->plus_time_interval($listed);
866 } elsif (my $scheduled_changes = $self->regularly_adjusts_trading_hours_on($when)) {
867 $closes_early = $when->truncate_to_day->plus_time_interval($scheduled_changes->{daily_close}->{to})
868 if ($scheduled_changes->{daily_close});
869 }
870 }
871  
872 return $closes_early;
873 }
874  
875 =head2 opens_late_on
876  
877 Returns true if the exchange opens late on the given date.
878  
879 =cut
880  
881 sub opens_late_on {
882 my ($self, $when) = @_;
883  
884 my $opens_late;
885 if ($self->trades_on($when)) {
886 my $listed = $self->late_opens->{$when->days_since_epoch};
887 if ($listed) {
888 $opens_late = $when->truncate_to_day->plus_time_interval($listed);
889 } elsif (my $scheduled_changes = $self->regularly_adjusts_trading_hours_on($when)) {
890 $opens_late = $when->truncate_to_day->plus_time_interval($scheduled_changes->{daily_open}->{to})
891 if ($scheduled_changes->{daily_open});
892 }
893 }
894  
895 return $opens_late;
896 }
897  
898 sub _get_exchange_open_times {
899 my ($self, $date, $which) = @_;
900  
901 my $when = (ref $date) ? $date : Date::Utility->new($date);
902 my $that_midnight = $self->trading_date_for($when);
903 my $requested_time;
904 if ($self->trades_on($that_midnight)) {
905 my $dst_key = $self->_times_dst_key($that_midnight);
906 my $ti = $self->market_times->{$dst_key}->{$which};
907 my $extended_lunch_hour;
908 if ($which eq 'trading_breaks') {
909 my $extended_trading_breaks = $self->market_times->{$dst_key}->{day_of_week_extended_trading_breaks};
910 $extended_lunch_hour = ($extended_trading_breaks and $when->day_of_week == $extended_trading_breaks) ? 1 : 0;
911 }
912 if ($ti) {
913 if (ref $ti eq 'ARRAY') {
914 my $trading_breaks = $extended_lunch_hour ? @$ti[1] : @$ti[0];
915 my $start_of_break = $that_midnight->plus_time_interval($trading_breaks->[0]);
916 my $end_of_break = $that_midnight->plus_time_interval($trading_breaks->[1]);
917 push @{$requested_time}, [$start_of_break, $end_of_break];
918 } else {
919 $requested_time = $that_midnight->plus_time_interval($ti);
920 }
921 }
922 }
923 return $requested_time; # returns null on no trading days.
924 }
925  
926 =head2 trades_normal_hours_on
927  
928 Boolean which indicates if the exchange is trading in its normal hours on a given Date::Utility
929  
930 =cut
931  
932 sub trades_normal_hours_on {
933 my ($self, $when) = @_;
934  
935 my $trades_normal_hours =
936 ($self->trades_on($when) and not $self->closes_early_on($when) and not $self->opens_late_on($when));
937  
938 return $trades_normal_hours;
939 }
940  
941 =head2 regularly_adjusts_trading_hours_on
942  
943 Does this Exchange always shift from regular trading hours on Dates "like"
944 the provided Date?
945  
946 =cut
947  
948 sub regularly_adjusts_trading_hours_on {
949  
950 my ($self, $when) = @_;
951  
952 my $changes;
953  
954 if ($when->day_of_week == 5) {
955 my $rule = 'Fridays';
956 if ($self->symbol eq 'FOREX' or $self->symbol eq 'METAL') {
957 $changes = {
958 'daily_close' => {
959 to => '21h',
960 rule => $rule,
961 }};
962 } elsif ($self->symbol eq 'JSC') {
963 $changes = {
964 'morning_close' => {
965 to => '4h30m',
966 rule => $rule,
967 },
968 'afternoon_open' => {
969 to => '7h',
970 rule => $rule
971 }};
972 }
973 }
974  
975 return $changes;
976 }
977  
978 =head2 is_in_dst_at
979  
980 Is this exchange trading on daylight savings times for the given epoch?
981  
982 =cut
983  
984 sub is_in_dst_at {
985 my ($self, $epoch) = @_;
986  
987 my $in_dst = 0;
988  
989 if ($self->is_affected_by_dst) {
990 my $dt = DateTime->from_epoch(epoch => $epoch);
991 $dt->set_time_zone($self->trading_timezone);
992 $in_dst = $dt->is_dst;
993 }
994  
995 return $in_dst;
996 }
997 Memoize::memoize(
998 'is_in_dst_at',
999 NORMALIZER => '_normalize_on_symbol_and_args',
1000 );
1001  
1002 sub _times_dst_key {
1003 my ($self, $when) = @_;
1004  
1005 my $epoch = (ref $when) ? $when->epoch : $when;
1006  
1007 return ($self->is_in_dst_at($epoch)) ? 'dst' : 'standard';
1008 }
1009  
1010 =head2 seconds_of_trading_between_epochs
1011  
1012 Get total number of seconds of trading time between two epochs accounting for breaks.
1013  
1014 =cut
1015  
1016 my $full_day = 86400;
1017  
1018 sub seconds_of_trading_between_epochs {
1019 my ($self, $start_epoch, $end_epoch) = @_;
1020  
1021 my $result = 0;
1022  
1023 # step 1: calculate non-cached incomplete start-day and end_dates
1024 my $day_start = $start_epoch - ($start_epoch % $full_day);
1025 my $day_end = $end_epoch - ($end_epoch % $full_day);
1026 if (($day_start != $start_epoch) && ($start_epoch < $end_epoch)) {
1027 $result += $self->_computed_trading_seconds($start_epoch, min($day_start + 86399, $end_epoch));
1028 $start_epoch = $day_start + $full_day;
1029 }
1030 if (($day_end != $end_epoch) && ($start_epoch < $end_epoch)) {
1031 $result += $self->_computed_trading_seconds(max($start_epoch, $day_end), $end_epoch);
1032 $end_epoch = $day_end;
1033 }
1034  
1035 # step 2: calculate intermediated values (which are guaranteed to be day-boundary)
1036 # with cache-aware way
1037 if ($start_epoch < $end_epoch) {
1038 $result += $self->_seconds_of_trading_between_epochs_days_boundary($start_epoch, $end_epoch);
1039 }
1040  
1041 return $result;
1042 }
1043  
1044 my %cached_seconds_for_interval; # key ${epoch1}-${epoch2}, value: seconds
1045  
1046 # there is a strict assumption, that start and end epoch are day boundaries
1047 sub _seconds_of_trading_between_epochs_days_boundary {
1048 my ($self, $start_epoch, $end_epoch) = @_;
1049 my $cache_key = join('-', $self->symbol, $start_epoch, $end_epoch);
1050 my $result = $cached_seconds_for_interval{$cache_key} //= do {
1051 my $head = $self->_computed_trading_seconds($start_epoch, $start_epoch + 86399);
1052 if ($end_epoch - $start_epoch > $full_day - 1) {
1053 my $tail = $self->_seconds_of_trading_between_epochs_days_boundary($start_epoch + $full_day, $end_epoch);
1054 $head + $tail;
1055 }
1056 };
1057 return $result;
1058 }
1059  
1060 ## PRIVATE method _computed_trading_seconds
1061 #
1062 # This one ACTUALLY does the heavy lifting of determining the number of trading seconds in an intraday period.
1063 #
1064 sub _computed_trading_seconds {
1065 my ($self, $start, $end) = @_;
1066  
1067 my $total_trading_time = 0;
1068 my $when = Date::Utility->new($start);
1069  
1070 if ($self->trades_on($when)) {
1071  
1072 # Do the full computation.
1073 my $opening_epoch = $self->opening_on($when)->epoch;
1074 my $closing_epoch = $self->closing_on($when)->epoch;
1075  
1076 # Total trading time left in interval. This is always between 0 to $period_secs_basis.
1077 # This will automatically take care of early close because market close will just be the early close time.
1078 my $total_trading_time_including_lunchbreaks =
1079 max(min($closing_epoch, $end), $opening_epoch) - min(max($opening_epoch, $start), $closing_epoch);
1080  
1081 my $total_lunch_break_time = 0;
1082  
1083 # Now take care of lunch breaks. But handle early close properly. It could be that
1084 # the early close already wipes out the need to handle lunch breaks.
1085 # Handle early close. For example on 24 Dec 2009, HKSE opens at 2:00, and stops
1086 # for lunch at 4:30 and never reopens. In that case the value of $self->closing_on($thisday)
1087 # is 4:30, and lunch time between 4:30 to 6:00 is no longer relevant.
1088 if (my $breaks = $self->trading_breaks($when)) {
1089 for my $break_interval (@{$breaks}) {
1090 my $interval_open = $break_interval->[0];
1091 my $interval_close = $break_interval->[1];
1092 my $close_am = min($interval_open->epoch, $closing_epoch);
1093 my $open_pm = min($interval_close->epoch, $closing_epoch);
1094  
1095 $total_lunch_break_time = max(min($open_pm, $end), $close_am) - min(max($close_am, $start), $open_pm);
1096  
1097 if ($total_lunch_break_time < 0) {
1098 die 'Total lunch break time between ' . $start . '] and [' . $end . '] for exchange[' . $self->symbol . '] is negative';
1099 }
1100 }
1101 }
1102  
1103 $total_trading_time = $total_trading_time_including_lunchbreaks - $total_lunch_break_time;
1104 if ($total_trading_time < 0) {
1105 croak 'Total trading time (minus lunch) between ' . $start . '] and [' . $end . '] for exchange[' . $self->symbol . '] is negative.';
1106 }
1107 }
1108  
1109 return $total_trading_time;
1110 }
1111  
1112 =head2 is_affected_by_dst
1113  
1114 Tells whether the exchange's opening times change due to daylight savings
1115 at some point in the year.
1116  
1117 =cut
1118  
1119 sub _build_is_affected_by_dst {
1120 my $self = shift;
1121  
1122 my $tz = DateTime::TimeZone->new(name => $self->trading_timezone);
1123  
1124 # This returns some incomprehensible number... so make it a nice bool.
1125 return ($tz->has_dst_changes) ? 1 : 0;
1126 }
1127  
1128 # PRIVATE method
1129 # Takes a two arguments: an epoch timestamp and which switch to find 'next' or 'prev'
1130 sub _find_dst_switch {
1131 my ($self, $epoch, $direction) = @_;
1132  
1133 $direction = 'next'
1134 if (not defined $direction
1135 or scalar grep { $direction ne $_ } qw(next prev));
1136  
1137 # Assumption: there is exactly one switch (each way) per year and no period is over 250 days long.
1138 # If we limit our search in this way, we'll definitely find the closest switch
1139 my $SEARCHWIDTH = 250 * 24 * 60 * 60;
1140 my $low_time = ($direction eq 'next') ? $epoch : $epoch - $SEARCHWIDTH;
1141 my $high_time = ($direction eq 'next') ? $epoch + $SEARCHWIDTH : $epoch;
1142  
1143 # Now we need to find out the unswitched state of DST.
1144 # This will let us know which way to continue the search when we miss.
1145 my $unswitched_state = $self->is_in_dst_at($epoch);
1146  
1147 my $ret_val; # Presume failure.
1148 my $continue_search = 1;
1149  
1150 while ($continue_search and $high_time > $low_time) {
1151 my $mid_time = int $low_time + ($high_time - $low_time) / 2;
1152 my $mid_state = $self->is_in_dst_at($mid_time);
1153  
1154 # Do we have the epoch where the switch happens?
1155 # If so, it should be different a second earlier.
1156 if ($mid_state != $self->is_in_dst_at($mid_time - 1)) {
1157 $continue_search = 0;
1158 $ret_val = $mid_time;
1159 } elsif (($direction eq 'next' and $mid_state == $unswitched_state)
1160 or ($direction eq 'prev' and $mid_state != $unswitched_state))
1161 {
1162 # We're in the past of the switch.
1163 $low_time = $mid_time + 1;
1164 } else {
1165 # We're in the future from the switch
1166 $high_time = $mid_time;
1167 }
1168 }
1169  
1170 return $ret_val;
1171 }
1172  
1173 =head2 closed_for_the_day
1174  
1175 Syntatic sugar to easily identify if the exchange is closed(already closed for the day or holiday or weekend).
1176 We are not expecting any more activity in this exchange for today.
1177  
1178 =cut
1179  
1180 sub closed_for_the_day {
1181 my $self = shift;
1182 my $now = Date::Utility->new;
1183 return (not $self->trades_on($now) or (not $self->is_open and $self->will_open));
1184 }
1185  
1186 =head2 last_trading_period
1187  
1188 Returns the last_trading_period as { begin => ..., end => ... }
1189 =cut
1190  
1191 sub last_trading_period {
1192 my $self = shift;
1193  
1194 my $now = Date::Utility->new;
1195 my $last_trading_day = $now;
1196 $last_trading_day = $self->trade_date_before($last_trading_day);
1197  
1198 my $open = $self->opening_on($last_trading_day);
1199 my $close = $self->closing_on($last_trading_day);
1200  
1201 #For ASX, NSX and TSE Indices that can wrap around
1202 if ($close->is_before($open)) {
1203 $open = $open->minus_time_interval('1d');
1204 }
1205  
1206 return {
1207 begin => $open,
1208 end => $close,
1209 };
1210 }
1211  
1212 =head2 regular_trading_day_after
1213  
1214 a trading day that has no late open or early close
1215  
1216 =cut
1217  
1218 sub regular_trading_day_after {
1219 my ($self, $when) = @_;
1220  
1221 return if $self->closing_on($when);
1222  
1223 my $counter = 0;
1224 my $regular_trading_day = $self->trade_date_after($when);
1225 while ($counter <= 10) {
1226 my $possible = $regular_trading_day->plus_time_interval($counter . 'd');
1227 if ( not $self->closes_early_on($possible)
1228 and not $self->opens_late_on($possible)
1229 and $self->trades_on($possible))
1230 {
1231 $regular_trading_day = $possible;
1232 last;
1233 }
1234 $counter++;
1235 }
1236  
1237 return $regular_trading_day;
1238 }
1239  
1240 ## PRIVATE static method _normalize_on_dates
1241 #
1242 # Many of these functions don't change their results if asked for the
1243 # same dates many times. Let's exploit that for time over space
1244 #
1245 # This actually comes up in our pricing where we have to do many interpolations
1246 # over the same ranges on different values.
1247 #
1248 # This attaches to the static method on the class for the lifetime of this instance.
1249 # Since we only want the cache for our specific symbol, we need to include an identifier.
1250  
1251 sub _normalize_on_dates {
1252 my ($self, @dates) = @_;
1253  
1254 return join '|', ($self->symbol, map { $_->days_since_epoch } @dates);
1255 }
1256  
1257 ## PRIVATE static method _normalize_on_symbol_and_args
1258 #
1259 # Normalize on the args, but don't take the self part too seriously.
1260  
1261 sub _normalize_on_symbol_and_args {
1262 my ($self, @other_args) = @_;
1263  
1264 return join ',', ($self->symbol, @other_args);
1265 }
1266  
1267 =head2 trading_period
1268  
1269 Given an epoch returns the period of trading of the exchange in that day
1270  
1271 =cut
1272  
1273 sub trading_period {
1274 my ($self, $when) = @_;
1275  
1276 return [] if not $self->trades_on($when);
1277 my $open = $self->opening_on($when);
1278 my $close = $self->closing_on($when);
1279 my $breaks = $self->trading_breaks($when);
1280  
1281 my @times = ($open);
1282 if (defined $breaks) {
1283 push @times, @{$_} for @{$breaks};
1284 }
1285 push @times, $close;
1286  
1287 my @periods;
1288 for (my $i = 0; $i < $#times; $i += 2) {
1289 push @periods,
1290 {
1291 open => $times[$i]->epoch,
1292 close => $times[$i + 1]->epoch
1293 };
1294 }
1295  
1296 return \@periods;
1297 }
1298  
1299 =head2 weighted_days_in_period
1300  
1301 Returns the sum of the weights we apply to each day in the requested period.
1302  
1303 =cut
1304  
1305 sub weighted_days_in_period {
1306 my ($self, $begin, $end) = @_;
1307  
1308 $end = $end->truncate_to_day;
1309 my $current = $begin->truncate_to_day->plus_time_interval('1d');
1310 my $days = 0.0;
1311  
1312 while (not $current->is_after($end)) {
1313 $days += $self->weight_on($current);
1314 $current = $current->plus_time_interval('1d');
1315 }
1316  
1317 return $days;
1318 }
1319  
1320 sub _build_asset {
1321 my $self = shift;
1322  
1323 return unless $self->underlying_config->asset_symbol;
1324 my $type = $self->underlying_config->asset_class;
1325  
1326 my $which = $type eq 'currency' ? 'Quant::Framework::Currency' : 'Quant::Framework::Asset';
1327  
1328 return $which->new({
1329 symbol => $self->underlying_config->asset_symbol,
1330 for_date => $self->for_date,
1331 chronicle_reader => $self->chronicle_reader,
1332 });
1333 }
1334  
1335 =head2 weight_on
1336  
1337 Returns the weight for a given day (given as a Date::Utility object).
1338 Returns our closed weight for days when the market is closed.
1339  
1340 =cut
1341  
1342 sub weight_on {
1343 my ($self, $date) = @_;
1344  
1345 my $base = $self->_build_asset;
1346 my $numeraire = Quant::Framework::Currency->new({
1347 symbol => $self->underlying_config->quoted_currency_symbol,
1348 for_date => $self->for_date,
1349 chronicle_reader => $self->chronicle_reader,
1350 });
1351  
1352 my $weight = $self->simple_weight_on($date) || $self->closed_weight;
1353 if ($self->underlying_config->market_name eq 'forex') {
1354 my $currency_weight =
1355 0.5 * ($base->weight_on($date) + $numeraire->weight_on($date));
1356  
1357 # If both have a holiday, set to 0.25
1358 if (!$currency_weight) {
1359 $currency_weight = 0.25;
1360 }
1361  
1362 $weight = min($weight, $currency_weight);
1363 } elsif ($self->symbol eq 'METAL') {
1364 my $usd = Quant::Framework::Currency->new({
1365 symbol => 'USD',
1366 for_date => $self->for_date,
1367 chronicle_reader => $self->chronicle_reader,
1368 });
1369 my $commodities_weight = $usd->has_holiday_on($date) ? 0.5 : 1;
1370 $weight = min($weight, $commodities_weight);
1371 }
1372  
1373 return $weight;
1374 }
1375  
1376 =head2 closed_weight
1377  
1378 Weights assigned for days when the markets are closed, based on empirical study and industry standards.
1379  
1380 =cut
1381  
1382 sub closed_weight {
1383 my $self = shift;
1384  
1385 return ($self->underlying_config->market_name eq 'indices') ? 0.55 : 0.06;
1386 }
1387  
1388 no Moose;
1389 __PACKAGE__->meta->make_immutable;
1390  
1391 1;