Framework/TradingCalendar.pm untested

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