Framework/VolSurface.pm untested

filter: Statementstmt 0.0% 0 / 582 Branchbran 0.0% 0 / 158 Conditioncond 0.0% 0 / 60 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 72 Podpod 0.0% 0 / 57 totaltotal 0.0% 0 / 929 CC 69 SCAR 27.4
CC
69
Cov
0%
get_smile_spread
90.0
_build_original_term
30.0
_get_atm_spread
30.0
CRAP 15.4
1 package Quant::Framework::VolSurface;
2  
3 =head1 NAME
4  
5 Quant::Framework::VolSurface
6  
7 =head1 DESCRIPTION
8  
9 Base class for all volatility surfaces.
10  
11 =cut
12  
13 use Moose;
14 use Try::Tiny;
15 use DateTime::TimeZone;
16 use List::MoreUtils qw(notall none all);
17 use Scalar::Util qw( looks_like_number weaken );
18 use Scalar::Util::Numeric qw( isnum );
19 use List::Util qw( min max first );
20 use Number::Closest::XS qw(find_closest_numbers_around);
21 use Math::Function::Interpolator;
22  
23 use Quant::Framework::Utils::Types;
24 use Quant::Framework::VolSurface::Cutoff;
25 use Quant::Framework::VolSurface::Validator;
26 use Quant::Framework::VolSurface::Utils;
27 use Quant::Framework::Utils::Builder;
28  
29 =head2 for_date
30  
31 The date for which we want to have the volatility surface data
32  
33 =cut
34  
35 has for_date => (
36 is => 'ro',
37 isa => 'Maybe[Date::Utility]',
38 default => undef,
39 );
40  
41 has chronicle_reader => (
42 is => 'ro',
43 isa => 'Data::Chronicle::Reader',
44 );
45  
46 has chronicle_writer => (
47 is => 'ro',
48 isa => 'Data::Chronicle::Writer',
49 );
50  
51 has underlying_config => (
52 is => 'ro',
53 required => 1,
54 );
55  
56 has calendar => (
57 is => 'ro',
58 isa => 'Quant::Framework::TradingCalendar',
59 lazy_build => 1,
60 );
61  
62 sub _build_calendar {
63 my $self = shift;
64  
65 return $self->builder->build_trading_calendar;
66 }
67  
68 has builder => (
69 is => 'ro',
70 isa => 'Quant::Framework::Utils::Builder',
71 lazy_build => 1,
72 );
73  
74 sub _build_builder {
75 my $self = shift;
76  
77 return Quant::Framework::Utils::Builder->new({
78 for_date => $self->for_date,
79 chronicle_reader => $self->chronicle_reader,
80 chronicle_writer => $self->chronicle_writer,
81 underlying_config => $self->underlying_config,
82 });
83 }
84  
85 =head1 ATTRIBUTES
86  
87 =head2 symbol
88  
89 The symbol of the underlying that this surface is for (e.g. frxUSDJPY)
90  
91 =cut
92  
93 has symbol => (
94 is => 'ro',
95 isa => 'Str',
96 required => 1,
97 );
98  
99 has _market_name => (
100 is => 'ro',
101 isa => 'Str',
102 lazy_build => 1,
103 );
104  
105 sub _build__market_name {
106 return shift->underlying_config->market_name;
107 }
108  
109 =head2 recorded_date
110  
111 The date (and time) that the surface was recorded, as a Date::Utility.
112  
113 =cut
114  
115 has recorded_date => (
116 is => 'ro',
117 isa => 'Date::Utility',
118 lazy_build => 1,
119 );
120  
121 sub _build_recorded_date {
122 my $self = shift;
123 my $recorded_date = Date::Utility->new($self->document->{date});
124  
125 #for a flat volatility surface, we assume it is always fresh with date equal to now or the date for which
126 #we want to fetch the surface (because it never changes)
127 if ($self->type eq 'flat') {
128 $recorded_date = $self->for_date // Date::Utility->new;
129 }
130  
131 return $recorded_date;
132 }
133  
134 =head2 type
135  
136 Type of the surface, delta, moneyness or flat.
137  
138 =cut
139  
140 has type => (
141 is => 'ro',
142 isa => 'qf_surface_type',
143 required => 1,
144 init_arg => undef,
145 default => undef,
146 );
147  
148 =head2 surface
149  
150 Stores the represented surface as a data structure (read-only).
151  
152 Term structures of CALL delta or moneyness to annualized volatilities.
153  
154 =cut
155  
156 has surface => (
157 is => 'ro',
158 isa => 'HashRef',
159 lazy_build => 1,
160 );
161  
162 sub _build_surface {
163 my $self = shift;
164 return $self->document->{surfaces}->{$self->cutoff->code};
165 }
166  
167 =head2 default_vol_spread
168  
169 This will return default volatility spread (difference between ask and bid for atm volatility).
170  
171 =cut
172  
173 has default_vol_spread => (
174 is => 'ro',
175 lazy_build => 1,
176 );
177  
178 sub _build_default_vol_spread {
179 return {shift->atm_spread_point => 0.1};
180 }
181  
182 =head2 smile_points
183  
184 The points across a smile.
185  
186 It can be delta points, moneyness points or any other points that we might have in the future.
187  
188 =cut
189  
190 has smile_points => (
191 is => 'ro',
192 isa => 'ArrayRef',
193 lazy_build => 1,
194 );
195  
196 sub _build_smile_points {
197 my $self = shift;
198  
199 # Default to the point found in the first day we find
200 # in $self->surface that has a smile. As long as each smile
201 # has the same points, this works. If each smile has different
202 # points, the Validator is going to give you trouble!
203 my $surface = $self->surface;
204  
205 my $suitable_day = first { exists $surface->{$_}->{smile} } @{$self->term_by_day};
206 my @smile_points = ();
207 if ($suitable_day) {
208 @smile_points =
209 sort { $a <=> $b } keys %{$surface->{$suitable_day}->{smile}};
210 }
211  
212 return \@smile_points;
213 }
214  
215 =head2 spread_points
216  
217 This will give an array-reference containing volatility spreads for first tenor which has a volatility spread (or ATM if none).
218 =cut
219  
220 has spread_points => (
221 is => 'ro',
222 isa => 'ArrayRef',
223 lazy_build => 1,
224 );
225  
226 sub _build_spread_points {
227 my $self = shift;
228  
229 # Default to the point found in the first day we find
230 # in $self->surface that has a volspread. As long as each volspread
231 # has the same points, this works. If each smile has different
232 # points, the Validator is going to give you trouble!
233 my $surface = $self->surface;
234  
235 my $suitable_day = first { exists $surface->{$_}->{vol_spread} } keys %{$surface};
236  
237 my @spread_points = ();
238 if ($suitable_day) {
239  
240 @spread_points =
241 sort { $a <=> $b } keys %{$surface->{$suitable_day}->{vol_spread}};
242 } else {
243  
244 $suitable_day = first { exists $surface->{$_}->{atm_spread} } keys %{$surface};
245 push @spread_points, 'atm_spread';
246 }
247  
248 return \@spread_points;
249 }
250  
251 =head2 print_precision
252  
253 The precision at which we should output vols, in number of digits after the decimal.
254 If set 0 or undefined, we will use full precision
255  
256 =cut
257  
258 has print_precision => (
259 is => 'ro',
260 isa => 'Maybe[Num]',
261 default => 4,
262 );
263  
264 =head2 term_by_day
265  
266 Get all the terms in a surface in ascending order.
267  
268 =cut
269  
270 has term_by_day => (
271 is => 'ro',
272 isa => 'ArrayRef',
273 init_arg => undef,
274 lazy_build => 1,
275 );
276  
277 sub _build_term_by_day {
278 my $self = shift;
279  
280 my @days = sort { $a <=> $b } keys %{$self->surface};
281  
282 return \@days;
283 }
284  
285 =head2 original_term
286  
287 The terms we were originally supplied for this surface.
288  
289 =cut
290  
291 has original_term => (
292 is => 'ro',
293 isa => 'HashRef',
294 lazy_build => 1,
295 );
296  
297 sub _build_original_term {
298 my $self = shift;
299  
300 my $surface = $self->surface;
301  
302 my $atm_spread_point = $self->atm_spread_point;
303 my $spread_type;
304 my @vol_spreads;
305 my @days = @{$self->term_by_day};
306  
307 my @smiles = grep { exists $surface->{$_}->{smile} } @days;
308  
309 foreach (@days) {
310  
311 if (exists $surface->{$_}->{vol_spread}) {
312 $spread_type = 'vol_spread';
313 push @vol_spreads, $_;
314  
315 } elsif (exists $surface->{$_}->{atm_spread}) {
316  
317 $spread_type = 'atm_spread';
318 push @vol_spreads, $_;
319 }
320  
321 }
322  
323 # We must have at least 2 atm_spreads if this is a valid surface with multiple smiles.
324 # Set the end points to the default if they are unset to make up any difference.
325 if (scalar @vol_spreads < min(2, scalar @smiles)) {
326 foreach my $end_index (0, -1) {
327 if ( exists $surface->{$days[$end_index]}
328 and not defined $surface->{$days[$end_index]}->{vol_spread}
329 and not defined $surface->{$days[$end_index]}->{atm_spread})
330 {
331 $spread_type = 'vol_spread';
332 $surface->{$days[$end_index]}->{vol_spread} = $self->default_vol_spread;
333 push @vol_spreads, $days[$end_index];
334  
335 }
336 }
337 }
338  
339 return +{
340 $spread_type => \@vol_spreads,
341 smile => \@smiles,
342 };
343  
344 }
345  
346 =head2 original_term_for_smile
347  
348 The original term structure we have for smiles on a surface
349  
350 =cut
351  
352 has original_term_for_smile => (
353 is => 'ro',
354 isa => 'ArrayRef',
355 lazy_build => 1,
356 );
357  
358 sub _build_original_term_for_smile {
359 my $self = shift;
360  
361 my @smile_terms = @{$self->original_term->{smile}};
362 my @sorted = sort { $a <=> $b } @smile_terms;
363 return \@sorted;
364 }
365  
366 =head2 original_term_for_spread
367  
368 The original term structure we have for spreads on a surface
369  
370 =cut
371  
372 has original_term_for_spread => (
373 is => 'ro',
374 isa => 'ArrayRef',
375 lazy_build => 1,
376 );
377  
378 sub _build_original_term_for_spread {
379 my $self = shift;
380 my @spread_terms =
381 defined $self->original_term->{vol_spread}
382 ? @{$self->original_term->{vol_spread}}
383 : @{$self->original_term->{atm_spread}};
384  
385 my @sorted = sort { $a <=> $b } @spread_terms;
386  
387 return \@sorted;
388 }
389  
390 =head2 effective_date
391  
392 Surfaces roll over at 5pm NY time, so the vols of any surfaces recorded after 5pm NY but
393 before GMT midnight are effectively for the next GMT day. This attribute holds this
394 effective date.
395  
396 =cut
397  
398 has effective_date => (
399 is => 'ro',
400 isa => 'Date::Utility',
401 init_arg => undef,
402 lazy_build => 1,
403 );
404  
405 sub _build_effective_date {
406 my $self = shift;
407  
408 return $self->_vol_utils->effective_date_for($self->recorded_date);
409 }
410  
411 # PRIVATE ATTRIBUTES:
412  
413 #A flag which determines whether this surface is a newly created surface or a one which is read from historical data.
414 has _new_surface => (
415 is => 'ro',
416 default => 0,
417 );
418  
419 has _vol_utils => (
420 is => 'ro',
421 isa => 'Quant::Framework::VolSurface::Utils',
422 init_arg => undef,
423 lazy_build => 1,
424 );
425  
426 sub _build__vol_utils {
427 return Quant::Framework::VolSurface::Utils->new;
428 }
429  
430 has _vol_surface_validator => (
431 is => 'ro',
432 isa => 'Quant::Framework::VolSurface::Validator',
433 init_arg => undef,
434 lazy_build => 1,
435 );
436  
437 sub _build__vol_surface_validator {
438 return Quant::Framework::VolSurface::Validator->new;
439 }
440  
441 has _ON_day => (
442 is => 'ro',
443 isa => 'Int',
444 lazy_build => 1,
445 );
446  
447 #Returns the day for over-night tenor of this surface
448 #ON = over-night
449 sub _build__ON_day {
450 my $self = shift;
451  
452 return $self->calendar->calendar_days_to_trade_date_after($self->effective_date);
453 }
454  
455 around BUILDARGS => sub {
456 my $orig = shift;
457 my $class = shift;
458 my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
459 my %day_for_tenor;
460  
461 die "Chronicle reader is required to create a vol-surface" if not defined $args{chronicle_reader};
462 die "Attribute underlying_config is required" if not defined $args{underlying_config};
463  
464 my $underlying_config = $args{underlying_config};
465 if (ref $underlying_config
466 and $underlying_config->isa('Quant::Framework::Utils::UnderlyingConfig'))
467 {
468 $args{symbol} = $underlying_config->system_symbol;
469 }
470  
471 if ($args{surface} or $args{recorded_date}) {
472  
473 if (not $args{surface} or not $args{recorded_date}) {
474 die('Must pass both "surface" and "recorded_date" if passing either.');
475 }
476  
477 $args{_new_surface} = 1;
478 my $builder = Quant::Framework::Utils::Builder->new({
479 for_date => $args{for_date},
480 chronicle_reader => $args{chronicle_reader},
481 chronicle_writer => $args{chronicle_writer},
482 underlying_config => $args{underlying_config},
483 });
484  
485 my $expiry_conventions = $builder->build_expiry_conventions;
486  
487 # If the smile's day is given as a tenor, we convert
488 # it to a day and add the tenor to the smile:
489 foreach my $maturity (keys %{$args{surface}}) {
490 my $effective_date;
491  
492 if (_is_tenor($maturity)) {
493 $effective_date ||= Quant::Framework::VolSurface::Utils->new->effective_date_for($args{recorded_date});
494  
495 my $vol_expiry_date = $expiry_conventions->vol_expiry_date({
496 from => $effective_date,
497 term => $maturity
498 });
499 my $day = $vol_expiry_date->days_between($effective_date);
500  
501 $args{surface}->{$day} = $args{surface}->{$maturity};
502 $args{surface}->{$day}->{tenor} = $maturity;
503 delete $args{surface}->{$maturity};
504  
505 $day_for_tenor{$maturity} = $day;
506 }
507 }
508 }
509  
510 if (ref $args{original_term}) {
511 if (
512 not exists $args{original_term}->{smile}
513 and (
514 not( exists $args{original_term}->{vol_spread}
515 or exists $args{original_term}->{atm_spread})))
516 {
517  
518 die('Given original_term attr must have both smile and vol_spread keys present.');
519 }
520 foreach my $which (qw( smile vol_spread )) {
521 if (exists $args{original_term}->{$which}) {
522 $args{original_term}->{$which} = [
523 sort { $a <=> $b }
524 map { _is_tenor($_) ? $day_for_tenor{$_} : $_ } @{$args{original_term}->{$which}}];
525 }
526 }
527 }
528 return $class->$orig(%args);
529 };
530  
531 sub _is_tenor {
532 my $day = shift;
533  
534 return ($day =~ /^(?:ON|\d{1,2}[WMY])$/) ? 1 : 0;
535 }
536  
537 =head2 get_spread
538  
539 Spread is ask-bid difference which can be stored for different tenor and atm/max.
540  
541 USAGE:
542  
543 my $spread = $volsurface->get_spread({sought_point=> 'atm', day=> 7});
544 will return the atm spread for the day.
545  
546 my $spread = $volsurface->get_spread({sought_point=> 'max', day=> 7});
547 will return the max spread for the day.
548  
549  
550 =cut
551  
552 sub get_spread {
553 my ($self, $args) = @_;
554  
555 my $sought_point = $args->{sought_point};
556 my $day = $args->{day};
557 my $spread;
558 $day = $self->get_day_for_tenor($day)
559 if ($day =~ /^(?:ON|\d[WMY])$/); # if day looks like tenor
560  
561 if ($sought_point eq 'atm') {
562  
563 $spread = $self->_get_atm_spread($day);
564 } elsif ($sought_point eq 'max') {
565  
566 $spread = $self->_get_max_spread_from_surface({
567 day => $day,
568 });
569  
570 }
571  
572 return $spread;
573  
574 }
575  
576 sub _get_max_spread_from_surface {
577 my ($self, $args) = @_;
578  
579 my $day = $args->{day};
580 my $atm_spread_point = $self->atm_spread_point;
581 my $spread;
582 my $surface = $self->surface;
583 if (exists $surface->{$day} and exists $surface->{$day}->{atm_spread}) {
584 $spread = $surface->{$day}->{atm_spread};
585 } else {
586  
587 my $smile = $self->get_smile_spread($day);
588 my @spread;
589 if ($atm_spread_point eq 'atm_spread') {
590 @spread = values %{$smile->{atm_spread}};
591 } else {
592 foreach my $point (keys %{$smile->{vol_spread}}) {
593 push @spread, $smile->{vol_spread}->{$point};
594 }
595 }
596  
597 $spread = max(@spread);
598  
599 }
600  
601 return $spread;
602 }
603  
604 =head2 get_smile_spread
605  
606 Returns the ask/bid spread for smile of this volatility surface
607  
608 =cut
609  
610 sub get_smile_spread {
611  
612 my ($self, $day) = @_;
613  
614 my $surface = $self->surface;
615 my @market_points = @{$self->original_term_for_spread};
616  
617 my $smile_spread;
618  
619 if ($self->_market_name eq 'indices' and $self->type eq 'moneyness') {
620  
621 foreach my $day (keys %{$surface}) {
622  
623 #check and add min_vol_spread for shorter term vol_spreads
624 if ($day < 30 and grep { $_ == $day } @market_points) {
625  
626 if (exists $surface->{$day}->{atm_spread}
627 and $surface->{$day}->{atm_spread} < $self->min_vol_spread)
628 {
629  
630 $surface->{$day}->{atm_spread} += $self->min_vol_spread;
631  
632 } elsif (exists $surface->{$day}->{vol_spread}) {
633 my $vol_spread = $surface->{$day}->{vol_spread};
634  
635 foreach my $point (keys %{$vol_spread}) {
636 if ($vol_spread->{$point} < $self->min_vol_spread) {
637 $vol_spread->{$point} += $self->min_vol_spread;
638 }
639 }
640  
641 $surface->{$day}->{vol_spread} = $vol_spread;
642  
643 }
644  
645 }
646  
647 }
648  
649 }
650  
651 if (exists $surface->{$day}) {
652  
653 if (exists $surface->{$day}->{atm_spread}) {
654 $smile_spread->{'atm_spread'} = $surface->{$day}->{atm_spread};
655  
656 } elsif (exists $surface->{$day}->{vol_spread}) {
657  
658 $smile_spread->{'vol_spread'} = $surface->{$day}->{vol_spread};
659 }
660  
661 } else {
662  
663 $smile_spread = $self->_compute_and_set_smile_spread($day);
664 }
665  
666 return $smile_spread;
667  
668 }
669  
670 sub _compute_and_set_smile_spread {
671 my ($self, $day) = @_;
672  
673 my @points = $self->_get_points_to_interpolate($day, $self->original_term_for_spread);
674 my $method =
675 ($self->_is_between($day, \@points))
676 ? '_interpolate_smile_spread'
677 : '_extrapolate_smile_spread';
678 my $smile_spread = $self->$method($day, \@points);
679  
680 $self->set_smile_spread({
681 days => $day,
682 smile_spread => $smile_spread
683 });
684  
685 return $smile_spread;
686 }
687  
688 =head2 set_smile_spread
689  
690 sets smile spread for the given tenor. Input should be a hash-ref with below items:
691 - days: Tenor for which smile_spread needs to be set.
692 - smile_spread
693  
694 =cut
695  
696 sub set_smile_spread {
697 my ($self, $args) = @_;
698  
699 my $day = $args->{days};
700 my $smile_spread = $args->{smile_spread};
701 my $atm_spread_point = $self->atm_spread_point;
702 die("day[$day] must be a number.") unless $day > 0;
703  
704 my $surface = $self->surface;
705  
706 $surface->{$day} = $smile_spread;
707  
708 return;
709 }
710  
711 sub _interpolate_smile_spread {
712 my ($self, $seek, $points) = @_;
713  
714 my $surface = $self->surface;
715 my $first_point = $points->[0];
716 my $second_point = $points->[1];
717 my $interpolation_first_point;
718 my $interpolation_second_point;
719 my $interpolated_smile;
720  
721 foreach my $spread_point (@{$self->spread_points}) {
722  
723 if (exists $surface->{$first_point}->{atm_spread}) {
724 $interpolation_first_point = $surface->{$first_point}->{atm_spread};
725 $interpolation_second_point = $surface->{$second_point}->{atm_spread};
726 } else {
727 $interpolation_first_point = $surface->{$first_point}->{vol_spread}->{$spread_point};
728 $interpolation_second_point = $surface->{$second_point}->{vol_spread}->{$spread_point};
729 }
730  
731 my $interp = Math::Function::Interpolator->new(
732 points => {
733 $first_point => $interpolation_first_point,
734 $second_point => $interpolation_second_point,
735 });
736  
737 if ($spread_point eq 'atm_spread') {
738  
739 $interpolated_smile->{atm_spread} = $interp->linear($seek);
740 } else {
741 $interpolated_smile->{vol_spread}->{$spread_point} = $interp->linear($seek);
742 }
743  
744 }
745  
746 return $interpolated_smile;
747  
748 }
749  
750 sub _extrapolate_smile_spread {
751 my ($self, $seek, $points) = @_;
752  
753 my $extrapolation_direction = $self->_get_extrapolate_direction($seek, $points);
754 my $extrapolation_method = '_extrapolate_smile_spread_' . $extrapolation_direction;
755  
756 return $self->$extrapolation_method($seek, $points);
757 }
758  
759 sub _extrapolate_smile_spread_up {
760 my ($self, $seek, $points) = @_;
761  
762 my @amp = @{$self->original_term_for_smile};
763 my $atm_spread_point = $self->atm_spread_point;
764 my $day = $amp[-1];
765 my $extrapolation;
766  
767 if ($atm_spread_point eq 'atm_spread') {
768 $extrapolation->{'atm_spread'} = $self->surface->{$day}->{'atm_spread'};
769 } else {
770 $extrapolation->{'vol_spread'} = $self->surface->{$day}->{'vol_spread'};
771 }
772  
773 return $extrapolation;
774  
775 }
776  
777 sub _extrapolate_smile_spread_down {
778 my ($self, $seek, $points) = @_;
779  
780 my $surface = $self->surface;
781 my $first_point = $points->[0];
782 my $second_point = $points->[1];
783 my $extrapolation_first_point;
784 my $extrapolation_second_point;
785 my $extrapolated_smile;
786  
787 foreach my $spread_point (@{$self->spread_points}) {
788  
789 if (exists $surface->{$first_point}->{atm_spread}) {
790 $extrapolation_first_point = $surface->{$first_point}->{atm_spread};
791 $extrapolation_second_point = $surface->{$second_point}->{atm_spread};
792 } else {
793 $extrapolation_first_point = $surface->{$first_point}->{vol_spread}->{$spread_point};
794 $extrapolation_second_point = $surface->{$second_point}->{vol_spread}->{$spread_point};
795 }
796  
797 my $interp = Math::Function::Interpolator->new(
798  
799 points => {
800 $first_point => $extrapolation_first_point,
801 $second_point => $extrapolation_second_point,
802 });
803  
804 if ($spread_point eq 'atm_spread') {
805  
806 $extrapolated_smile->{atm_spread} = $interp->linear($seek);
807 } else {
808 $extrapolated_smile->{vol_spread}->{$spread_point} = $interp->linear($seek);
809 }
810  
811 }
812  
813 return $extrapolated_smile;
814  
815 }
816  
817 sub _get_atm_spread {
818 my ($self, $day) = @_;
819  
820 my $atm_spread;
821 my $surface = $self->surface;
822 my $atm_spread_point = $self->atm_spread_point;
823  
824 if (exists $surface->{$day} and exists $surface->{$day}->{atm_spread}) {
825 $atm_spread = $surface->{$day}->{atm_spread};
826 } else {
827  
828 my $smile_spread = $self->get_smile_spread($day);
829  
830 if (
831 grep { $atm_spread_point eq $_ }
832 keys %{$smile_spread->{'vol_spread'}})
833 {
834 $atm_spread = $smile_spread->{'vol_spread'}->{$atm_spread_point};
835 } else {
836  
837 my @points = $self->_get_points_to_interpolate($day, $self->original_term_for_spread);
838  
839 my $method =
840 ($self->_is_between($day, \@points))
841 ? '_interpolate_atm_spread'
842 : '_extrapolate_atm_spread';
843  
844 $smile_spread = $self->$method($day, \@points);
845  
846 if ($atm_spread_point eq 'atm_spread') {
847 $atm_spread = $smile_spread->{$atm_spread_point};
848 } else {
849 $atm_spread = $smile_spread->{'vol_spread'}->{$atm_spread_point};
850 }
851  
852 }
853  
854 }
855  
856 return $atm_spread;
857 }
858  
859 sub _interpolate_atm_spread {
860 my ($self, $seek, $points) = @_;
861  
862 my $surface = $self->surface;
863 my $atm_spread_point = $self->atm_spread_point;
864 my $first = $points->[0];
865 my $second = $points->[1];
866 my $interpolation_first_point;
867 my $interpolation_second_point;
868  
869 if (exists $surface->{$first}->{atm_spread}) {
870 $interpolation_first_point = $surface->{$first}->{atm_spread};
871 $interpolation_second_point = $surface->{$second}->{atm_spread};
872 } else {
873 $interpolation_first_point = $surface->{$first}->{vol_spread}->{$atm_spread_point};
874 $interpolation_second_point = $surface->{$second}->{vol_spread}->{$atm_spread_point};
875 }
876  
877 my $interp = Math::Function::Interpolator->new(
878  
879 points => {
880 $first => $interpolation_first_point,
881 $second => $interpolation_second_point,
882 });
883  
884 my $interpolated_spread;
885  
886 if ($atm_spread_point eq 'atm_spread') {
887 $interpolated_spread->{$atm_spread_point} = $interp->linear($seek);
888 } else {
889 $interpolated_spread->{'vol_spread'}->{$atm_spread_point} = $interp->linear($seek);
890 }
891  
892 return $interpolated_spread;
893 }
894  
895 sub _extrapolate_atm_spread {
896 my ($self, $seek, $points) = @_;
897  
898 my $extrapolation_direction = $self->_get_extrapolate_direction($seek, $points);
899 my $extrapolation_method = '_extrapolate_atm_spread_' . $extrapolation_direction;
900  
901 return $self->$extrapolation_method($seek, $points);
902 }
903  
904 sub _extrapolate_atm_spread_up {
905 my ($self, $seek, $points) = @_;
906  
907 my @amp = @{$self->original_term_for_smile};
908 my $atm_spread_point = $self->atm_spread_point;
909 my $day = $amp[-1];
910 my $extrapolation;
911 if ($atm_spread_point eq 'atm_spread') {
912 $extrapolation->{'atm_spread'} = $self->surface->{$day}->{atm_spread};
913 } else {
914 $extrapolation->{vol_spread}->{$atm_spread_point} = $self->surface->{$day}->{vol_spread}->{$atm_spread_point};
915 }
916  
917 return $extrapolation;
918 }
919  
920 sub _extrapolate_atm_spread_down {
921 my ($self, $seek, $points) = @_;
922  
923 my $surface = $self->surface;
924 my $atm_spread_point = $self->atm_spread_point;
925 my $first_point = $points->[0];
926 my $second_point = $points->[1];
927 my $extrapolation_first_point;
928 my $extrapolation_second_point;
929 my $extrapolated_smile;
930  
931 if (exists $surface->{$first_point}->{atm_spread}) {
932 $extrapolation_first_point = $surface->{$first_point}->{atm_spread};
933 $extrapolation_second_point = $surface->{$second_point}->{atm_spread};
934 } else {
935 $extrapolation_first_point = $surface->{$first_point}->{vol_spread}->{$atm_spread_point};
936 $extrapolation_second_point = $surface->{$second_point}->{vol_spread}->{$atm_spread_point};
937 }
938  
939 my $interp = Math::Function::Interpolator->new(
940 points => {
941 $first_point => $extrapolation_first_point,
942 $second_point => $extrapolation_second_point,
943 });
944  
945 if ($atm_spread_point eq 'atm_spread') {
946  
947 $extrapolated_smile->{atm_spread} = $interp->linear($seek);
948 } else {
949 $extrapolated_smile->{vol_spread}->{$atm_spread_point} = $interp->linear($seek);
950 }
951  
952 return $extrapolated_smile;
953  
954 }
955  
956 =head2 get_day_for_tenor
957  
958 USAGE:
959  
960 my $day = $volsurface->get_day_for_tenor('1W');
961  
962 Get the corresponding day for a given tenor, if one exists.
963  
964 =cut
965  
966 sub get_day_for_tenor {
967 my ($self, $tenor) = @_;
968  
969 my $surface_data = $self->surface;
970 my $day = first {
971 $surface_data->{$_}->{tenor} && $surface_data->{$_}->{tenor} eq $tenor;
972 }
973 @{$self->term_by_day};
974  
975 # If tenor doesn't already exist on surface, get $days via the vol expiry date.
976 if (not $day) {
977 $day = $self->builder->build_expiry_conventions->vol_expiry_date({
978 from => $self->effective_date,
979 term => $tenor,
980 })->days_between($self->effective_date);
981 }
982  
983 return $day;
984 }
985  
986 sub _get_points_to_interpolate {
987 my ($self, $seek, $available_points) = @_;
988 die('Need 2 or more term structures to interpolate.')
989 if scalar @$available_points <= 1;
990  
991 return @{find_closest_numbers_around($seek, $available_points, 2)};
992 }
993  
994 sub _is_between {
995 my ($self, $seek, $points) = @_;
996  
997 my @points = @$points;
998  
999 die('some of the points are not defined')
1000 if (notall { defined $_ } @points);
1001 die('less than two available points')
1002 if (scalar @points < 2);
1003  
1004 return if (all { $_ < $seek } @points);
1005 return if (all { $_ > $seek } @points);
1006 return 1;
1007 }
1008  
1009 sub _market_maturities_interpolation_function {
1010 my ($self, $T, $T1, $T2) = @_;
1011  
1012 # Implements interpolation over time based on the way Iain M Clark does
1013 # it in Foreign Exchange Option Pricing, A Practitioner's Guide, page 70.
1014 my $effective_date = $self->effective_date;
1015  
1016 my %dates = (
1017 T => $effective_date->plus_time_interval($T - 1 . 'd23h59m59s'),
1018 T1 => $effective_date->plus_time_interval($T1 - 1 . 'd23h59m59s'),
1019 T2 => $effective_date->plus_time_interval($T2 - 1 . 'd23h59m59s'),
1020 );
1021  
1022 my $tau1 = $self->builder->build_trading_calendar->weighted_days_in_period($dates{T1}, $dates{T}) / 365;
1023 my $tau2 = $self->builder->build_trading_calendar->weighted_days_in_period($dates{T1}, $dates{T2}) / 365;
1024  
1025 warn( 'Error in volsurface['
1026 . $self->recorded_date->datetime
1027 . '] for symbol['
1028 . $self->underlying_config->symbol
1029 . '] for maturity['
1030 . $T
1031 . '] points ['
1032 . $T1 . ','
1033 . $T2 . "]\n")
1034 unless $tau2;
1035  
1036 return sub {
1037 my ($vol1, $vol2) = @_;
1038 return sqrt(($tau1 / $tau2) * ($T2 / $T) * $vol2**2 + (($tau2 - $tau1) / $tau2) * ($T1 / $T) * $vol1**2);
1039 };
1040 }
1041  
1042 =head1 METHODS
1043  
1044 =head2 get_volatility
1045  
1046 USAGE:
1047  
1048 my $vol = $vol_surface->get_volatility({
1049 days => 7,
1050 delta => 50,
1051 });
1052  
1053 Interpolates (on the two-dimensional vol surface) using Bloomberg's method.
1054  
1055 =cut
1056  
1057 sub get_volatility {
1058 my ($self, $args) = @_;
1059  
1060 my $sought_point = $args->{sought_point};
1061 my $days = $args->{days};
1062  
1063 $self->_validate_sought_values($days, $sought_point);
1064  
1065 my $vol = $self->_get_volatility_from_surface({
1066 days => $days,
1067 sought_point => $sought_point,
1068 });
1069  
1070 return $vol;
1071 }
1072  
1073 sub _convert_expiry_to_day {
1074 my ($self, $args) = @_;
1075  
1076 return $args->{days} if $args->{days};
1077 my $days =
1078 $args->{expiry_date}
1079 ? $self->_get_days_for_expiry_date($args->{expiry_date})
1080 : $self->get_day_for_tenor($args->{tenor});
1081 delete $args->{expiry_date};
1082 delete $args->{tenor};
1083 return $days;
1084 }
1085  
1086 sub _validate_sought_values {
1087 my ($self, $day, $sought_point) = @_;
1088  
1089 if (notall { defined $_ } ($sought_point, $day)) {
1090 $sought_point ||= '';
1091 $day ||= '';
1092 die("Days[$day] or sought_point[$sought_point] is undefined for underlying[" . $self->symbol . "]");
1093 }
1094  
1095 if (!isnum($sought_point)) {
1096 die("Point[$sought_point] must be a number");
1097 }
1098  
1099 if ($day <= 0 or $sought_point < 0) {
1100 die("get_volatility requires positive numeric days[$day] and sought_point[$sought_point]");
1101 }
1102  
1103 return 1;
1104 }
1105  
1106 sub _get_volatility_from_surface {
1107 my ($self, $args) = @_;
1108  
1109 my $day = $args->{days};
1110 my $sought_point = $args->{sought_point};
1111 my $vol;
1112  
1113 my $smile = $self->get_smile($day);
1114 if ($smile->{$sought_point}) {
1115 $vol = $smile->{$sought_point};
1116 } else {
1117 $vol = $self->interpolate({
1118 smile => $smile,
1119 sought_point => $sought_point,
1120 });
1121 }
1122  
1123 return $vol;
1124 }
1125  
1126 =head2 get_smile
1127  
1128 Get the smile for specific day.
1129  
1130 Usage:
1131  
1132 my $smile = $vol_surface->get_smile($days);
1133  
1134 =cut
1135  
1136 sub get_smile {
1137 my ($self, $day) = @_;
1138  
1139 die("day[$day] must be a number.")
1140 unless looks_like_number($day);
1141  
1142 my $surface = $self->surface;
1143 my $smile =
1144 (exists $surface->{$day} and exists $surface->{$day}->{smile})
1145 ? $surface->{$day}->{smile}
1146 : $self->_compute_and_set_smile($day);
1147  
1148 return $smile;
1149 }
1150  
1151 sub _compute_and_set_smile {
1152 my ($self, $day) = @_;
1153  
1154 my @points = $self->_get_points_to_interpolate($day, $self->original_term_for_smile);
1155 my $method =
1156 ($self->_is_between($day, \@points))
1157 ? '_interpolate_smile'
1158 : '_extrapolate_smile';
1159 my $smile = $self->$method($day, \@points);
1160  
1161 $self->set_smile({
1162 days => $day,
1163 smile => $smile
1164 });
1165  
1166 return $smile;
1167 }
1168  
1169 sub _days_with_smiles {
1170 my $self = shift;
1171 my @days_with_smiles =
1172 grep { exists $self->surface->{$_}->{smile} } @{$self->term_by_day};
1173 return \@days_with_smiles;
1174 }
1175  
1176 sub _interpolate_smile {
1177 my ($self, $seek, $points) = @_;
1178  
1179 my $surface = $self->surface;
1180 my $first_point = $points->[0];
1181 my $second_point = $points->[1];
1182 my $interpolate_func = $self->_market_maturities_interpolation_function($seek, $first_point, $second_point);
1183 my $interpolated_smile;
1184  
1185 foreach my $smile_point (@{$self->smile_points}) {
1186 my $first_iv = $surface->{$first_point}->{smile}->{$smile_point};
1187 my $second_iv = $surface->{$second_point}->{smile}->{$smile_point};
1188 $interpolated_smile->{smile}->{$smile_point} = $interpolate_func->($first_iv, $second_iv);
1189 }
1190  
1191 return $interpolated_smile->{smile};
1192 }
1193  
1194 sub _extrapolate_smile {
1195 my ($self, $seek, $points) = @_;
1196  
1197 my $extrapolation_direction = $self->_get_extrapolate_direction($seek, $points);
1198 my $extrapolation_method = '_extrapolate_smile_' . $extrapolation_direction;
1199  
1200 return $self->$extrapolation_method($seek);
1201 }
1202  
1203 #returns initial risk reversal as a hash-ref
1204 sub _get_initial_rr {
1205 my ($self, $market) = @_;
1206  
1207 my %initial_rr;
1208 my $rr_adjustment;
1209 if ($self->_market_name ne 'indices') {
1210 $rr_adjustment = {
1211 rr_25 => 0.1,
1212 rr_10 => 0.1
1213 };
1214 $initial_rr{RR_25} = $rr_adjustment->{rr_25} * $market->{RR_25};
1215 $initial_rr{RR_10} = $rr_adjustment->{rr_10} * $market->{RR_10} if (exists $market->{RR_10});
1216 }
1217  
1218 return \%initial_rr;
1219 }
1220  
1221 sub _extrapolate_smile_up {
1222 my $self = shift;
1223  
1224 # This is not an ideal solution and duration of contracts is not supposed to be more than 1 year
1225 # But, you'll get a 1 year smile if the unexpected happens :-P
1226 my $last_term = $self->original_term_for_smile->[-1];
1227 return $self->surface->{$last_term}->{smile};
1228 }
1229  
1230 sub _get_extrapolate_direction {
1231 my ($self, $seek, $points) = @_;
1232  
1233 my @points = @$points;
1234 my $direction = ($seek > max(@points)) ? 'up' : 'down';
1235  
1236 return $direction;
1237 }
1238  
1239 sub _get_days_for_expiry_date {
1240 my ($self, $expiry_date) = @_;
1241  
1242 # In general, days_between the effective_date of the surface and the asked-for
1243 # expiry_date gives us what we want.
1244 #
1245 # However, due to vol-cuts logic cutting to wherever the cut time falls within the
1246 # effective day of the vol, and due to FX end-of-day being at GMT23:59, we
1247 # cut the vol back into the previous GMT day, e.g. we cut the NY1000 vol for contracts
1248 # expiring on the 24th back to GMT23:59 on the 23rd. This means that if we ask
1249 # for a vol for the 23rd, and the underling closes after NY1700, we need to use the
1250 # vol for the next day. We do this by considering days between the effective day of
1251 # the recorded date and the expiry.
1252 # This can potentially cause problems if the effective date (surface recorded date) is too old
1253 my $days = $self->_vol_utils->effective_date_for($expiry_date)->days_between($self->effective_date);
1254  
1255 # If we asked for the vol for an expiry date (which translated to an integer number
1256 # of days), default to the 1-day vol if
1257 return max($days, 1);
1258 }
1259  
1260 =head2 set_smile
1261  
1262 Set a smile into the volatility surface
1263 Input: day and smile (key: smile_point ; value: volatility)
1264  
1265 Usage:
1266  
1267 $vol_surface->set_smile($day, \%smile);
1268  
1269 =cut
1270  
1271 sub set_smile {
1272 my ($self, $args) = @_;
1273  
1274 my $day = $args->{days};
1275 die("day[$day] must be a number.")
1276 unless looks_like_number($day);
1277  
1278 my $surface = $self->surface;
1279 my $atm_spread_point = $self->atm_spread_point;
1280 my $smile = $args->{smile};
1281 my $vol_spread = $self->get_smile_spread($day);
1282  
1283 # throws exception on error.
1284 $self->_vol_surface_validator->check_smile($day, $smile, $self->symbol);
1285  
1286 $surface->{$day}->{smile} = $smile;
1287  
1288 if ($atm_spread_point eq 'atm_spread') {
1289 $surface->{$day}->{atm_spread} = $vol_spread->{'atm_spread'};
1290 } else {
1291 $surface->{$day}->{vol_spread} = $vol_spread->{'vol_spread'};
1292 }
1293  
1294 # We just changed the surface, so clear the caches.
1295 $self->clear_term_by_day;
1296  
1297 return;
1298 }
1299  
1300 =head2 get_rr_bf_for_smile
1301  
1302 Return the rr and bf values for a given smile
1303 For more info see: https://en.wikipedia.org/wiki/Risk_reversal and https://en.wikipedia.org/wiki/Butterfly_(options)
1304  
1305 =cut
1306  
1307 sub get_rr_bf_for_smile {
1308 my ($self, $market_smile) = @_;
1309  
1310 my $result = {
1311 ATM => $market_smile->{50},
1312 RR_25 => $market_smile->{25} - $market_smile->{75},
1313 BF_25 => ($market_smile->{25} + $market_smile->{75}) / 2 - $market_smile->{50},
1314 };
1315 if (exists $market_smile->{10}) {
1316 $result->{RR_10} = $market_smile->{10} - $market_smile->{90};
1317 $result->{BF_10} = ($market_smile->{10} + $market_smile->{90}) / 2 - $market_smile->{50};
1318 }
1319 return $result;
1320 }
1321  
1322 =head2 get_market_rr_bf
1323  
1324 Returns the rr and bf values for a given day
1325  
1326 =cut
1327  
1328 sub get_market_rr_bf {
1329 my ($self, $day) = @_;
1330  
1331 my %smile = %{$self->get_smile($day)};
1332  
1333 return $self->get_rr_bf_for_smile(\%smile);
1334 }
1335  
1336 =head2 set_smile_flag
1337  
1338 Sets a flag to a smile.
1339  
1340 It is an ArrayRef of smile flag messages.
1341 If a flag is set we will not allow clients to buy new contracts.
1342  
1343 Usage:
1344  
1345 $vol_surface->set_smile_flag($time_days, $flag)
1346  
1347 =cut
1348  
1349 sub set_smile_flag {
1350 my ($self, $day, $flag_message) = @_;
1351  
1352 $day = $self->_ON_day if ($day eq 'ON');
1353  
1354 my $flag_array_ref = $self->get_smile_flag($day);
1355 if (not defined $flag_array_ref) {
1356 $flag_array_ref = [];
1357 $self->surface->{$day}->{flag} = $flag_array_ref;
1358 }
1359  
1360 push @{$flag_array_ref}, $flag_message;
1361  
1362 return 1;
1363 }
1364  
1365 =head2 get_smile_flag
1366  
1367 Get the flag (as an array-ref) for a specific smile.
1368  
1369 A flag means there is an error/irregularity of the smile/quote too old/ etc.
1370  
1371 Usage:
1372  
1373 my $smile_flag = $vol_surface->get_smile_flag($day)
1374  
1375 =cut
1376  
1377 sub get_smile_flag {
1378 my ($self, $day) = @_;
1379  
1380 my $daily_vol_info = $self->surface->{$day};
1381  
1382 return $daily_vol_info->{flag};
1383 }
1384  
1385 =head2 get_smile_flags
1386  
1387 Get all flags of the surface. Takes no args.
1388 Return value is a string in the format "day1:flag1;day2:flag2;day3:flag3..."
1389  
1390 =cut
1391  
1392 sub get_smile_flags {
1393 my ($self) = @_;
1394  
1395 my @days = @{$self->term_by_day};
1396 my @flag_strs;
1397  
1398 foreach my $day (@days) {
1399 if (my $flag = $self->get_smile_flag($day)) {
1400 push @flag_strs, join '', ($day, ': ', @{$flag});
1401 }
1402 }
1403  
1404 return join '; ', @flag_strs;
1405 }
1406  
1407 =head2 fetch_historical_surface_date
1408  
1409 Get historical vol surface dates going back a given number of historical revisions.
1410  
1411 =cut
1412  
1413 sub fetch_historical_surface_date {
1414 my ($self, $args) = @_;
1415 my $back_to = $args->{back_to} || 1;
1416  
1417 my $vdoc = $self->chronicle_reader->get('volatility_surfaces', $self->symbol);
1418 my $current_date = $vdoc->{date};
1419  
1420 my @dates;
1421 push @dates, $current_date;
1422  
1423 for (2 .. $back_to) {
1424 $vdoc = $self->chronicle_reader->get_for('volatility_surfaces', $self->symbol, Date::Utility->new($current_date)->epoch - 1);
1425  
1426 last if not $vdoc or not %{$vdoc};
1427  
1428 $current_date = $vdoc->{date};
1429  
1430 push @dates, $current_date;
1431 }
1432  
1433 return \@dates;
1434 }
1435  
1436 =head2 is_valid
1437  
1438 Validates this volatility surface and returns possible errors (or empty if surface is valid).
1439  
1440 =cut
1441  
1442 sub is_valid {
1443 my $self = shift;
1444  
1445 # An old/saved surface is always valid.
1446 # It has to be validated before it gets saved.
1447 return 1 if not $self->_new_surface;
1448  
1449 my $err;
1450  
1451 # This should not die.
1452 try {
1453 Quant::Framework::VolSurface::Validator->new->validate_surface($self);
1454 $err = 'Surface has smile flags: ' . $self->get_smile_flags
1455 if $self->get_smile_flags;
1456 }
1457 catch {
1458 $err = 'Die while being validated with error: ' . $_;
1459 };
1460  
1461 # Updates validation error.
1462 $self->validation_error($err) if $err;
1463  
1464 return !$err;
1465 }
1466  
1467 has validation_error => (
1468 is => 'rw',
1469 default => '',
1470 );
1471  
1472 =head2 get_existing_surface
1473  
1474 Returns original surface and not the cut surface
1475  
1476 =cut
1477  
1478 sub get_existing_surface {
1479 my $self = shift;
1480  
1481 # existing surface will return you the original surface and not the cut surface
1482 return $self->_new_surface
1483 ? $self->new({
1484 underlying_config => $self->underlying_config,
1485 cutoff => $self->cutoff,
1486 chronicle_reader => $self->chronicle_reader,
1487 chronicle_writer => $self->chronicle_writer,
1488 })
1489 : $self;
1490 }
1491  
1492 no Moose;
1493 __PACKAGE__->meta->make_immutable;
1494 1;