Framework/VolSurface/Moneyness.pm untested

filter: Statementstmt 0.0% 0 / 220 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 18 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 338 CC 29 SCAR 35.3
CC
29
Cov
0%
get_volatility
90.0
_admissible_check
90.0
get_smile
20.0
CRAP 34.3
1 package Quant::Framework::VolSurface::Moneyness;
2  
3 =head1 NAME
4  
5 Quant::Framework::VolSurface::Moneyness
6  
7 =head1 DESCRIPTION
8  
9 Base class for strike-based volatility surfaces by moneyness.
10  
11 =cut
12  
13 use Moose;
14 extends 'Quant::Framework::VolSurface';
15  
16 use Date::Utility;
17 use VolSurface::Utils qw(get_delta_for_strike get_strike_for_moneyness);
18 use Scalar::Util qw( looks_like_number );
19 use Math::Function::Interpolator;
20 use List::MoreUtils qw(indexes);
21 use List::Util qw(min max);
22  
23 =head2 surface_data
24  
25 The original surface data.
26  
27 =cut
28  
29 has surface_data => (
30 is => 'ro',
31 lazy_build => 1,
32 );
33  
34 sub _build_surface_data {
35 my $self = shift;
36  
37 # For backward compatibility
38 my $date = $self->for_date // Date::Utility->new;
39 my $surface = $self->document->{surface} // $self->document->{surfaces}{'UTC ' . $self->calendar->standard_closing_on($date)->time_hhmm};
40 die('surface data not found for ' . $self->symbol) unless $surface;
41  
42 return $self->_clean($surface);
43 }
44  
45 =head2 type
46  
47 Return the surface type
48  
49 =cut
50  
51 has '+type' => (
52 default => 'moneyness',
53 );
54  
55 =head2 min_vol_spread
56  
57 minimum volatility spread that we can accept for this volatility surface.
58  
59 =cut
60  
61 has min_vol_spread => (
62 is => 'ro',
63 isa => 'Num',
64 default => 3.1 / 100,
65 );
66  
67 has atm_spread_point => (
68 is => 'ro',
69 isa => 'Num',
70 default => 100,
71 );
72  
73 =head2 spot_reference
74  
75 Get the spot reference used to calculate the surface.
76 We should always use reference spot of the surface for any moneyness-related vol calculation
77  
78 =cut
79  
80 has spot_reference => (
81 is => 'rw',
82 isa => 'Num',
83 lazy_build => 1,
84 );
85  
86 sub _build_spot_reference {
87 my $self = shift;
88  
89 return $self->document->{spot_reference};
90 }
91  
92 =head2 get_volatility
93  
94 USAGE:
95  
96 my $vol = $s->get_volatility({moneyness => 96, from => $from, to => $to});
97 my $vol = $s->get_volatility({strike => $bet->barrier, from => $from, to => $to});
98 my $vol = $s->get_volatility({moneyness => 90, from => $from, to => $to});
99  
100 =cut
101  
102 sub get_volatility {
103 my ($self, $args) = @_;
104  
105 if (scalar(grep { defined $args->{$_} } qw(delta moneyness strike)) != 1) {
106 die("Must pass exactly one of [delta, moneyness, strike] to get_volatility.");
107 }
108  
109 die "Must pass two dates [from, to] to get volatility." if (not($args->{from} and $args->{to}));
110  
111 my %internal_args = %{$args};
112 $internal_args{days} = ($internal_args{to}->epoch - $internal_args{from}->epoch) / 86400;
113 delete $internal_args{to};
114 delete $internal_args{from};
115  
116 die "Argument 'days' must be positive, non-zero number." if $internal_args{days} <= 0;
117  
118 # we are handling delta seperately because it involves
119 # a lot more steps to calculate vol for a delta point
120 # on a moneyness surface
121 return $self->_calculate_vol_for_delta(\%internal_args) if $internal_args{delta};
122  
123 my $moneyness =
124 $internal_args{strike}
125 ? $internal_args{strike} / $self->spot_reference * 100
126 : $internal_args{moneyness};
127  
128 die "Sought point must be a number." if not looks_like_number($moneyness);
129 die "Sought point must be a positive number." if $moneyness < 0;
130  
131 my $smile = $self->get_smile($internal_args{days});
132  
133 return $smile->{$moneyness} if $smile->{$moneyness};
134  
135 return $self->interpolate({
136 smile => $smile,
137 sought_point => $moneyness,
138 });
139 }
140  
141 =head2 get_smile
142  
143 Get the smile for specific day.
144  
145 Usage:
146  
147 my $smile = $vol_surface->get_smile($days);
148  
149 =cut
150  
151 sub get_smile {
152 my ($self, $day) = @_;
153  
154 die("day[$day] must be a number.")
155 unless looks_like_number($day);
156  
157 my $surface = $self->surface;
158 my $smile;
159 # autovivification
160 if (exists $surface->{$day} and exists $surface->{$day}{smile}) {
161 $smile = $surface->{$day}{smile};
162 } else {
163 $smile = $self->_compute_smile($day);
164 }
165  
166 if (not $self->_is_valid_volatility_smile($smile)) {
167 $self->validation_error("Invalid smile volatility on smile calculated on day[$day] for " . $self->symbol);
168 }
169  
170 return $smile;
171 }
172  
173 sub _compute_smile {
174 my ($self, $day) = @_;
175  
176 my @points = $self->_get_points_to_interpolate($day, $self->original_term_for_smile);
177 my $method =
178 ($self->_is_between($day, \@points))
179 ? '_interpolate_smile'
180 : '_extrapolate_smile';
181 my $smile = $self->$method($day, \@points);
182  
183 return $smile;
184 }
185  
186 sub _interpolate_smile {
187 my ($self, $seek, $points) = @_;
188  
189 my $surface = $self->surface;
190 my $first_point = $points->[0];
191 my $second_point = $points->[1];
192 my $interpolate_func = $self->_market_maturities_interpolation_function($seek, $first_point, $second_point);
193 my $interpolated_smile;
194  
195 foreach my $smile_point (@{$self->smile_points}) {
196 my $first_iv = $surface->{$first_point}->{smile}->{$smile_point};
197 my $second_iv = $surface->{$second_point}->{smile}->{$smile_point};
198 $interpolated_smile->{$smile_point} = $interpolate_func->($first_iv, $second_iv);
199 }
200  
201 return $interpolated_smile;
202 }
203  
204 sub _extrapolate_smile {
205 my ($self, $seek, $points) = @_;
206  
207 my $index = $seek > max(@$points) ? -1 : 0;
208  
209 # we do not extrapolate for moneyness smiles. We will take the market points at both ends.
210 return $self->surface->{$self->original_term_for_smile->[$index]}->{smile};
211 }
212  
213 sub _market_maturities_interpolation_function {
214 my ($self, $T, $T1, $T2) = @_;
215  
216 # Implements interpolation over time based on the way Iain M Clark does
217 # it in Foreign Exchange Option Pricing, A Practitioner's Guide, page 70.
218 my $effective_date = $self->effective_date;
219 my $day_in_seconds = 86400;
220  
221 # Setting it to end of day. That's why we need to minus 1 second.
222 my %dates = (
223 T => $effective_date->plus_time_interval($T * $day_in_seconds - 1),
224 T1 => $effective_date->plus_time_interval($T1 * $day_in_seconds - 1),
225 T2 => $effective_date->plus_time_interval($T2 * $day_in_seconds - 1),
226 );
227  
228 my $tau1 = $self->builder->build_trading_calendar->weighted_days_in_period($dates{T1}, $dates{T}) / 365;
229 my $tau2 = $self->builder->build_trading_calendar->weighted_days_in_period($dates{T1}, $dates{T2}) / 365;
230  
231 warn( 'Error in volsurface['
232 . $self->recorded_date->datetime
233 . '] for symbol['
234 . $self->underlying_config->symbol
235 . '] for maturity['
236 . $T
237 . '] points ['
238 . $T1 . ','
239 . $T2 . "]\n")
240 unless $tau2;
241  
242 return sub {
243 my ($vol1, $vol2) = @_;
244 return sqrt(($tau1 / $tau2) * ($T2 / $T) * $vol2**2 + (($tau2 - $tau1) / $tau2) * ($T1 / $T) * $vol1**2);
245 };
246 }
247  
248 =head2 interpolate
249  
250 This is how you could interpolate across smile.
251 This uses the default interpolation method of the surface.
252  
253 $surface->interpolate({smile => $smile, sought_point => $sought_point});
254 =cut
255  
256 sub interpolate {
257 my ($self, $args) = @_;
258  
259 my $method = keys %{$args->{smile}} < 5 ? 'quadratic' : 'cubic';
260  
261 return Math::Function::Interpolator->new(points => $args->{smile})->$method($args->{sought_point});
262 }
263  
264 =head2 get_market_rr_bf
265  
266 Returns the rr and bf values for a given day
267  
268 =cut
269  
270 sub get_market_rr_bf {
271 my ($self, $day) = @_;
272  
273 # rr and bf only make sense in delta term. Here we convert the smile to a delta smile.
274 my %smile = map { $_ => $self->_calculate_vol_for_delta({delta => $_, days => $day}) } qw(25 50 75);
275  
276 return $self->get_rr_bf_for_smile(\%smile);
277 }
278  
279 =head2 get_smile_expiries
280  
281 An array reference of that contains expiry dates for smiles on the volatility surface.
282  
283 =cut
284  
285 sub get_smile_expiries {
286 my $self = shift;
287  
288 my $raw_surface = $self->surface;
289 my $effective_date = $self->effective_date;
290 my $close = $self->calendar->standard_closing_on($effective_date);
291  
292 die 'Attempt to update volatility surface for ' . $self->symbol . ' when the exchange is closed' unless $close;
293  
294 return [map { $effective_date->plus_time_interval($_ . 'd' . $close->seconds_after_midnight . 's') } @{$self->original_term_for_smile}];
295 }
296  
297 ## PRIVATE ##
298  
299 sub _calculate_vol_for_delta {
300 my ($self, $args) = @_;
301  
302 my $delta = $args->{delta};
303 my $days = $args->{days};
304 my $smile = $self->_convert_moneyness_smile_to_delta($days);
305  
306 return $smile->{$delta}
307 ? $smile->{$delta}
308 : $self->_interpolate_delta({
309 smile => $smile,
310 sought_point => $delta
311 });
312 }
313  
314 sub _interpolate_delta {
315 my ($self, $args) = @_;
316  
317 my %smile = %{$args->{smile}};
318  
319 die('minimum of three points on a smile')
320 if keys %smile < 3;
321  
322 my @sorted = sort { $a <=> $b } keys %smile;
323 my %new_smile =
324 map { $_ => $smile{$_} } grep { $_ > 1 and $_ < 99 } @sorted;
325  
326 if (keys %new_smile < 5) {
327 my @diff = map { abs($_ - 50) } @sorted;
328 my $atm_index = indexes { min(@diff) == abs($_ - 50) } @sorted;
329 %new_smile =
330 map { $sorted[$_] => $smile{$sorted[$_]} } ($atm_index - 1 .. $atm_index + 1);
331 }
332  
333 $args->{smile} = \%new_smile;
334  
335 return $self->interpolate($args);
336 }
337  
338 sub _convert_moneyness_smile_to_delta {
339 my ($self, $days) = @_;
340  
341 my $moneyness_smile = $self->get_smile($days);
342  
343 my %strikes =
344 map { get_strike_for_moneyness({moneyness => $_ / 100, spot => $self->spot_reference,}) => $moneyness_smile->{$_} } keys %$moneyness_smile;
345  
346 my $tiy = $days / 365;
347 my $r_rate = $self->builder->build_interest_rate->interest_rate_for($tiy);
348 my $q_rate = $self->builder->build_dividend->dividend_rate_for($tiy);
349 my %deltas;
350 foreach my $strike (keys %strikes) {
351 my $vol = $strikes{$strike};
352 my $delta = 100 * get_delta_for_strike({
353 strike => $strike,
354 atm_vol => $vol,
355 t => $tiy,
356 spot => $self->spot_reference,
357 r_rate => $r_rate,
358 q_rate => $q_rate,
359 premium_adjusted => $self->underlying_config->market_convention->{delta_premium_adjusted},
360 });
361 $deltas{$delta} = $vol;
362 }
363  
364 return \%deltas,;
365 }
366  
367 sub _max_allowed_term {
368 return 750;
369 }
370  
371 sub _max_difference_between_smile_points {
372 return 100;
373 }
374  
375 sub _admissible_check {
376 my $self = shift;
377  
378 my $underlying_config = $self->underlying_config;
379 my $builder = $self->builder;
380 my $S = $self->spot_reference;
381 my $premium_adjusted = $underlying_config->{market_convention}->{delta_premium_adjusted};
382 my @expiries = @{$self->get_smile_expiries};
383 my @tenors = @{$self->original_term_for_smile};
384 my $now = Date::Utility->new;
385  
386 for (my $i = 1; $i <= $#expiries; $i++) {
387 my $day = $tenors[$i - 1];
388 my $expiry = $expiries[$i];
389  
390 die("Invalid tenor[$day] with expiry[" . $expiry->date . "] on surface. Current date[" . $now->date . ']')
391 if ($expiry->days_between($now) <= 0);
392  
393 my $adjustment;
394 if ($underlying_config->market_prefer_discrete_dividend) {
395 $adjustment = $builder->build_dividend->dividend_adjustments_for_period({
396 start => $now,
397 end => $expiry,
398 });
399 $S += $adjustment->{spot};
400 }
401  
402 my $t = ($expiry->epoch - $now->epoch) / (365 * 86400);
403 my $r = $builder->build_interest_rate->interest_rate_for($t);
404 my $q = ($underlying_config->market_prefer_discrete_dividend) ? 0 : $builder->build_dividend->dividend_rate_for($t);
405 my $smile = $self->surface->{$day}->{smile};
406  
407 my @volatility_level = sort { $a <=> $b } keys %{$smile};
408 my $first_vol_level = $volatility_level[0];
409 my $last_vol_level = $volatility_level[-1];
410  
411 my %prev;
412  
413 foreach my $vol_level (@volatility_level) {
414 my $vol = $smile->{$vol_level};
415 my $barrier = $vol_level / 100 * $S;
416  
417 if ($underlying_config->market_prefer_discrete_dividend) {
418 $barrier += $adjustment->{barrier};
419 }
420  
421 my $prob = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier, $t, $r, $r - $q, $vol);
422 my $slope;
423  
424 if (exists $prev{prob}) {
425 $slope = ($prob - $prev{prob}) / ($vol_level - $prev{vol_level});
426  
427 # Admissible Check 1.
428 # For moneyness surface, the strike(prob) is increasing(decreasing) across moneyness point, hence the slope is negative
429 if ($slope >= 0.0) {
430 die( "Admissible check 1 failure for symbol["
431 . $self->symbol
432 . "] maturity[$day]. BS digital call price decreases between $prev{vol_level} and "
433 . $vol_level);
434 }
435 }
436  
437 %prev = (
438 slope => $slope,
439 prob => $prob,
440 vol_level => $vol_level,
441 );
442  
443 next
444 if ($vol_level == $first_vol_level
445 || $vol_level == $last_vol_level);
446  
447 $barrier = $vol_level / 100 * $S;
448 my $h = (2.0 / 100) * $S;
449  
450 my %vol_period = (
451 from => $self->recorded_date,
452 to => $expiry,
453 );
454 $vol = $self->get_volatility({
455 moneyness => ($vol_level - 2),
456 %vol_period,
457 });
458 my $bet_minus_h = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier - $h, $t, $r, $r - $q, $vol);
459  
460 $vol = $self->get_volatility({
461 moneyness => ($vol_level),
462 %vol_period,
463 });
464 my $bet = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier, $t, $r, $r - $q, $vol);
465  
466 $vol = $self->get_volatility({
467 moneyness => ($vol_level + 2),
468 %vol_period,
469 });
470 my $bet_plus_h = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier + $h, $t, $r, $r - $q, $vol);
471  
472 ## The actual finite difference formula has a / $h**2, but since we're checking
473 ## for negativity, we don't need it. Also, we introducted an error margin to allow
474 ## surfaces that are close to passing through.
475 my $convexity_flag = $bet_minus_h - 2 * $bet + $bet_plus_h;
476 if ($convexity_flag < -0.009) {
477 die("Admissible check 2 failure for maturity[$day] strike center[$vol_level] convexity value is [$convexity_flag].");
478 }
479 }
480 }
481  
482 return;
483 }
484  
485 sub _validation_methods {
486 return qw(_validate_age _validate_structure _validate_identical_surface _validate_volatility_jumps _admissible_check);
487 }
488  
489 no Moose;
490 __PACKAGE__->meta->make_immutable;
491  
492 1;