Framework/VolSurface/Delta.pm untested

filter: Statementstmt 0.0% 0 / 251 Branchbran 0.0% 0 / 52 Conditioncond 0.0% 0 / 27 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 377 CC 27 SCAR 34.0
CC
27
Cov
0%
get_volatility
90.0
_admissible_check
72.0
get_weight
20.0
CRAP 29.8
1 package Quant::Framework::VolSurface::Delta;
2  
3 =head1 NAME
4  
5 Quant::Framework::VolSurface::Delta
6  
7 =head1 DESCRIPTION
8  
9 Represents a volatility surface, built from market implied volatilities.
10  
11 =head1 SYNOPSIS
12  
13 my $surface = Quant::Framework::VolSurface::Delta->new({underlying_config => $underlying_config});
14  
15 =cut
16  
17 use Moose;
18  
19 extends 'Quant::Framework::VolSurface';
20  
21 use Math::Business::BlackScholes::Binaries;
22 use Number::Closest::XS qw(find_closest_numbers_around);
23 use List::Util qw(min);
24 use List::MoreUtils qw(any);
25 use Date::Utility;
26 use VolSurface::Utils qw( get_delta_for_strike get_strike_for_moneyness get_strike_for_spot_delta );
27 use Math::Function::Interpolator;
28  
29 =head1 ATTRIBUTES
30  
31 =head2 type
32  
33 Return the surface type
34  
35 =cut
36  
37 has '+type' => (
38 default => 'delta',
39 );
40  
41 has atm_spread_point => (
42 is => 'ro',
43 isa => 'Num',
44 default => '50',
45 );
46  
47 =head2 variance_table
48  
49 A variance surface. Converted from raw volatility input surface.
50  
51 =cut
52  
53 has variance_table => (
54 is => 'ro',
55 lazy_build => 1,
56 );
57  
58 sub _build_variance_table {
59 my $self = shift;
60  
61 my $raw_surface = $self->surface;
62 my $effective_date = $self->effective_date;
63 # New York 10:00
64 my $ny_offset_from_gmt = $effective_date->timezone_offset('America/New_York')->hours;
65 my $seconds_after_midnight = $effective_date->plus_time_interval(10 - $ny_offset_from_gmt . 'h')->seconds_after_midnight;
66  
67 # keys are tenor in epoch, values are associated variances.
68 my %table = ($self->recorded_date->epoch => {map { $_ => 0 } @{$self->smile_points}});
69 foreach my $tenor (@{$self->original_term_for_smile}) {
70 my $epoch = $effective_date->plus_time_interval($tenor . 'd' . $seconds_after_midnight . 's')->epoch;
71 foreach my $delta (@{$self->smile_points}) {
72 my $volatility = $raw_surface->{$tenor}{smile}{$delta};
73 $table{$epoch}{$delta} = $volatility**2 * $tenor if defined $volatility;
74 }
75 }
76  
77 return \%table;
78 }
79  
80 =head2 surface_data
81  
82 The original surface data.
83  
84 =cut
85  
86 has surface_data => (
87 is => 'ro',
88 lazy_build => 1,
89 );
90  
91 sub _build_surface_data {
92 my $self = shift;
93  
94 # For backward compatibility
95 my $surface = $self->document->{surface} // $self->document->{surfaces}{'New York 10:00'};
96 die('surface data not found for ' . $self->symbol) unless $surface;
97  
98 return $self->_clean($surface);
99 }
100  
101 =head2 get_volatility
102  
103 Expects 3 mandatory arguments as input.
104  
105 1) from - Date::Utility object
106 2) to - Date::Utility object
107 3) delta | strike | moneyness.
108  
109 Calculates volatility from the surface based input parameters.
110  
111 USAGE:
112  
113 my $from = Date::Utility->new('2016-06-01 10:00:00');
114 my $to = Date::Utility->new('2016-06-01 15:00:00');
115 my $vol = $s->get_volatility({delta => 25, from => $from, to => $to});
116 my $vol = $s->get_volatility({strike => $bet->barrier, from => $from, to => $to});
117 my $vol = $s->get_volatility({delta => 50, from => $from, to => $to});
118  
119 =cut
120  
121 sub get_volatility {
122 my ($self, $args) = @_;
123  
124 # args validity checks
125 die("Must pass exactly one of delta, strike or moneyness to get_volatility.")
126 if (scalar(grep { defined $args->{$_} } qw(delta strike moneyness)) != 1);
127  
128 die "Must pass two dates [from, to] to get volatility." if (not($args->{from} and $args->{to}));
129  
130 die 'Inverted dates[from=' . $args->{from}->datetime . ' to= ' . $args->{to}->datetime . '] to get volatility.'
131 if $args->{from}->epoch > $args->{to}->epoch;
132  
133 # This sanity check prevents negative variance
134 # This will happen when we are trying to price a contract that has expired but not settled.
135 if ($args->{from}->epoch < $self->recorded_date->epoch) {
136 $self->validation_error('Requesting a volatility for date in the past. Volatility surface date['
137 . $self->recorded_date->datetime
138 . '] requested date['
139 . $args->{from}->datetime
140 . ']');
141 return 0.01; # return a 1% volatility but we will not sell on this volatility.
142 }
143  
144 my $delta =
145 (defined $args->{delta}) ? $args->{delta}
146 : (defined $args->{strike}) ? $self->_convert_strike_to_delta($args)
147 : $self->_convert_moneyness_to_delta($args);
148  
149 die 'Delta cannot be zero or negative.' if $delta < 0;
150  
151 my $smile = $self->get_smile($args->{from}, $args->{to});
152  
153 return $smile->{$delta} if $smile->{$delta};
154  
155 return $self->interpolate({
156 smile => $smile,
157 sought_point => $delta,
158 });
159 }
160  
161 =head2 get_smile
162  
163 Calculate the requested smile from volatility surface.
164  
165 =cut
166  
167 sub get_smile {
168 my ($self, $from, $to) = @_;
169  
170 # each smile is calculated on the fly.
171 my $number_of_days = ($to->epoch - $from->epoch) / 86400;
172 my $variances_from = $self->get_variances($from);
173 my $variances_to = $self->get_variances($to);
174 my $smile;
175  
176 foreach my $delta (@{$self->smile_points}) {
177 $smile->{$delta} = sqrt(($variances_to->{$delta} - $variances_from->{$delta}) / $number_of_days);
178 }
179  
180 if (not $self->_is_valid_volatility_smile($smile)) {
181 $self->validation_error(
182 "Invalid smile volatility on smile calculated from[" . $from->datetime . "] to[" . $to->datetime . "] for " . $self->symbol);
183 }
184  
185 return $smile;
186 }
187  
188 =head2 get_variances
189  
190 Calculate the variance for a given date based on volatility surface data.
191  
192 =cut
193  
194 sub get_variances {
195 my ($self, $date) = @_;
196  
197 my $epoch = $date->epoch;
198 my $table = $self->variance_table;
199  
200 return $table->{$epoch} if $table->{$epoch};
201  
202 my @available_tenors = sort { $a <=> $b } keys %{$table};
203 my @closest = map { Date::Utility->new($_) } @{find_closest_numbers_around($date->epoch, \@available_tenors, 2)};
204 my $weight = $self->get_weight($closest[0], $date);
205 my $weight2 = $weight + $self->get_weight($date, $closest[1]);
206  
207 my %variances;
208 foreach my $delta (@{$self->smile_points}) {
209 my $var1 = $table->{$closest[0]->epoch}{$delta};
210 my $var2 = $table->{$closest[1]->epoch}{$delta};
211 $variances{$delta} = $var1 + ($var2 - $var1) / $weight2 * $weight;
212 }
213  
214 return \%variances;
215 }
216  
217 =head2 get_weight
218  
219 Get the weight between to given dates.
220  
221 =cut
222  
223 # We sliced the weight of a given into 4-hour period for easier manipulation in the future.
224 # We might incorporate seasonality into weights.
225 # A 4-hour interval for weight calculation is good enough for now.
226 my $weight_interval = 4 * 3600;
227  
228 sub get_weight {
229 my ($self, $date1, $date2) = @_;
230  
231 my $same_day = !$date2->days_between($date1);
232 my $diff = $date2->epoch - $date1->epoch;
233 my $next_interval = Date::Utility->new($date1->epoch - ($date1->epoch % $weight_interval) + $weight_interval);
234  
235 my @dates;
236 if ($same_day) {
237 @dates = ($diff < $weight_interval) ? ($date1->epoch, $date2->epoch) : ($date1->epoch, $self->_break($next_interval, $date2));
238 } else {
239 my $next_day = $date1->plus_time_interval('1d')->truncate_to_day;
240 @dates =
241 ($next_interval->epoch < $next_day->epoch)
242 ? ($date1->epoch, $self->_break($next_interval, $date2))
243 : ($date1->epoch, $self->_break($next_day, $date2));
244 }
245  
246 my $calendar = $self->calendar;
247 my $total_weight = 0;
248 for (my $i = 0; $i < $#dates; $i++) {
249 my $dt = $dates[$i + 1] - $dates[$i];
250 $total_weight += $calendar->weight_on(Date::Utility->new($dates[$i])) * $dt / 86400;
251 }
252  
253 return $total_weight;
254 }
255  
256 sub _break {
257 my ($self, $d1, $d2) = @_;
258  
259 my ($e1, $e2) = ($d1->epoch, $d2->epoch);
260 my @dates;
261 while ($e1 <= $e2) {
262 push @dates, $e1;
263 my $diff = $e2 - $e1;
264 last if $diff == 0;
265 $e1 += min($e2 - $e1, $weight_interval);
266 }
267  
268 return @dates;
269 }
270  
271 =head2 interpolate
272  
273 Quadratic interpolation to interpolate across smile
274 ->interpolate({smile => $smile, sought_point => $sought_point});
275  
276 =cut
277  
278 sub interpolate {
279 my ($self, $args) = @_;
280  
281 return Math::Function::Interpolator->new(points => $args->{smile})->quadratic($args->{sought_point});
282 }
283  
284 =head2 get_market_rr_bf
285  
286 Returns the rr and bf values for a given day
287  
288 =cut
289  
290 sub get_market_rr_bf {
291 my ($self, $days) = @_;
292  
293 my $smile = $self->get_surface_smile($days);
294  
295 return $self->get_rr_bf_for_smile($smile);
296 }
297  
298 =head2 get_smile_expiries
299  
300 An array reference of that contains expiry dates for smiles on the volatility surface.
301  
302 =cut
303  
304 sub get_smile_expiries {
305 my $self = shift;
306  
307 return [map { Date::Utility->new($_) } sort { $a <=> $b } keys %{$self->variance_table}];
308 }
309  
310 # PRIVATE #
311  
312 sub _convert_moneyness_to_delta {
313 my ($self, $args) = @_;
314  
315 $args->{strike} = get_strike_for_moneyness({
316 moneyness => $args->{moneyness},
317 spot => $self->builder->build_spot->spot_quote,
318 });
319  
320 delete $args->{moneyness};
321 my $delta = $self->_convert_strike_to_delta($args);
322  
323 return $delta;
324 }
325  
326 sub _convert_strike_to_delta {
327 my ($self, $args) = @_;
328  
329 my $conversion_args = $self->_ensure_conversion_args($args);
330  
331 return 100 * get_delta_for_strike($conversion_args);
332 }
333  
334 sub _ensure_conversion_args {
335 my ($self, $args) = @_;
336  
337 my %new_args = %{$args};
338 my $underlying_config = $self->underlying_config;
339  
340 $new_args{t} ||= ($args->{to}->epoch - $args->{from}->epoch) / (365 * 86400);
341 $new_args{spot} ||= $self->builder->build_spot->spot_quote;
342 $new_args{premium_adjusted} ||= $underlying_config->{market_convention}->{delta_premium_adjusted};
343 $new_args{r_rate} ||= $self->builder->build_interest_rate->interest_rate_for($new_args{t});
344 $new_args{q_rate} ||= $self->builder->build_dividend->dividend_rate_for($new_args{t});
345  
346 $new_args{atm_vol} ||= $self->get_volatility({
347 delta => 50,
348 from => $args->{from},
349 to => $args->{to},
350 });
351  
352 return \%new_args;
353 }
354  
355 sub _max_allowed_term {
356 return 380;
357 }
358  
359 sub _max_difference_between_smile_points {
360 return 30;
361 }
362  
363 sub _validate_smile_consistency {
364 my $self = shift;
365  
366 my $surface_hash_ref = $self->surface;
367 my @days = sort { $a <=> $b } keys %$surface_hash_ref;
368 my @prev_smile;
369  
370 foreach my $day (grep { exists $surface_hash_ref->{$_}->{smile} } @days) {
371 my $smile = $surface_hash_ref->{$day}->{smile};
372 my @current_smile = sort { $a <=> $b } keys %{$smile};
373  
374 if (not @prev_smile) {
375 @prev_smile = @current_smile;
376 next;
377 }
378  
379 if (@prev_smile != @current_smile || (any { $prev_smile[$_] != $current_smile[$_] } (0 .. $#current_smile))) {
380 die( 'Deltas['
381 . join(',', @current_smile)
382 . "] for maturity[$day], underlying["
383 . $self->symbol
384 . '] are not the same as deltas for rest of surface['
385 . join(',', @prev_smile)
386 . '].');
387 }
388 }
389  
390 return;
391 }
392  
393 #
394 # To ensure that the volatility is arbitrage-free, the total implied variance must be strictly
395 # increasing by forward moneyness.
396 # As proven by Fengler, 2005 "Arbitrage-free smoothing of the implied volatility surface"
397 # p.10, Proposition 2.1
398 #
399 # We check the surface market points. This is usually done at startup when volsurface object is
400 # being created.
401 #
402 # Forward Moneyness = K/F_T
403 sub _validate_termstructure_for_calendar_arbitrage {
404 my $self = shift;
405  
406 my @sorted_expiries = @{$self->original_term_for_smile};
407 for (my $i = 1; $i < scalar(@sorted_expiries); $i++) {
408 my $smile = $self->surface->{$sorted_expiries[$i]}->{smile};
409 my $smile_prev = $self->surface->{$sorted_expiries[$i - 1]}->{smile};
410 my $vol = $smile->{50};
411 my $vol_prev = $smile_prev->{50};
412 my $T = $sorted_expiries[$i];
413 my $T_prev = $sorted_expiries[$i - 1];
414 if (((($vol)**2) * $T) < (($vol_prev**2) * $T_prev)) {
415 die('Negative variance found on ' . $self->symbol . ' for maturity ' . $sorted_expiries[$i - 1] . ' for ATM');
416 }
417 }
418  
419 return;
420 }
421  
422 sub _admissible_check {
423 my $self = shift;
424  
425 my $underlying_config = $self->underlying_config;
426 my $builder = $self->builder;
427 my $S = $self->builder->build_spot->spot_quote;
428 my $premium_adjusted = $underlying_config->{market_convention}->{delta_premium_adjusted};
429 my @expiries = @{$self->get_smile_expiries};
430 my @tenors = @{$self->original_term_for_smile};
431 my $now = Date::Utility->new;
432  
433 for (my $i = 1; $i <= $#expiries; $i++) {
434 my $day = $tenors[$i - 1];
435 my $expiry = $expiries[$i];
436  
437 die("Invalid tenor[$day] with expiry[" . $expiry->date . "] on surface. Current date[" . $now->date . ']')
438 if ($expiry->days_between($now) <= 0);
439  
440 my $adjustment;
441 if ($underlying_config->market_prefer_discrete_dividend) {
442 $adjustment = $builder->build_dividend->dividend_adjustments_for_period({
443 start => $now,
444 end => $expiry,
445 });
446 $S += $adjustment->{spot};
447 }
448  
449 my $t = ($expiry->epoch - $now->epoch) / (365 * 86400);
450 my $r = $builder->build_interest_rate->interest_rate_for($t);
451 my $q = ($underlying_config->market_prefer_discrete_dividend) ? 0 : $builder->build_dividend->dividend_rate_for($t);
452 my $smile = $self->surface->{$day}->{smile};
453  
454 my @volatility_level = sort { $a <=> $b } keys %{$smile};
455 my $first_vol_level = $volatility_level[0];
456 my $last_vol_level = $volatility_level[-1];
457  
458 my %prev;
459  
460 foreach my $vol_level (@volatility_level) {
461 my $vol = $smile->{$vol_level};
462 # Temporarily get the Call strike via the Put side of the algorithm,
463 # as it seems not to go crazy at the extremities. Should give the same barrier.
464 my $conversion_args = {
465 atm_vol => $vol,
466 t => $t,
467 r_rate => $r,
468 q_rate => $q,
469 spot => $S,
470 premium_adjusted => $premium_adjusted
471 };
472  
473 if ($vol_level > 50) {
474 $conversion_args->{delta} = exp(-$r * $t) - $vol_level / 100;
475 $conversion_args->{option_type} = 'VANILLA_PUT';
476 } else {
477 $conversion_args->{delta} = $vol_level / 100;
478 $conversion_args->{option_type} = 'VANILLA_CALL';
479 }
480 my $barrier = get_strike_for_spot_delta($conversion_args);
481  
482 if ($underlying_config->market_prefer_discrete_dividend) {
483 $barrier += $adjustment->{barrier};
484 }
485 my $prob = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier, $t, $r, $r - $q, $vol);
486 my $slope;
487  
488 if (exists $prev{prob}) {
489 $slope = ($prob - $prev{prob}) / ($vol_level - $prev{vol_level});
490 # Admissible Check 1.
491 # For delta surface, the strike(prob) is decreasing(increasing) across delta point, hence the slope is positive
492 if ($slope <= 0) {
493 die( "Admissible check 1 failure for symbol["
494 . $self->symbol
495 . "] maturity[$day]. BS digital call price decreases between $prev{vol_level} and "
496 . $vol_level);
497 }
498 }
499  
500 %prev = (
501 slope => $slope,
502 prob => $prob,
503 vol_level => $vol_level,
504 );
505 }
506 }
507  
508 return;
509 }
510  
511 sub _validation_methods {
512 return
513 qw(_validate_age _validate_structure _validate_smile_consistency _validate_identical_surface _validate_volatility_jumps _validate_termstructure_for_calendar_arbitrage _admissible_check);
514 }
515  
516 no Moose;
517 __PACKAGE__->meta->make_immutable;
518  
519 1;