Framework/VolSurface/Validator.pm untested

filter: Statementstmt 0.0% 0 / 279 Branchbran 0.0% 0 / 88 Conditioncond 0.0% 0 / 31 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 429 CC 45 SCAR 49.6
CC
45
Cov
0%
_admissible_check
306.0
_check_structure
240.0
_check_identical_surface
30.0
CRAP 142.9
1 package Quant::Framework::VolSurface::Validator;
2  
3 =head1 NAME
4  
5 Quant::Framework::VolSurface::Validator
6  
7 =head1 DESCRIPTION
8  
9 Provides subroutines that can perform various
10 validation checks on Quant::Framework::VolSurface objects.
11  
12 =head1 SYNOPSIS
13  
14 use Quant::Framework::VolSurface::Validator;
15  
16 my $validator = Quant::Framework::VolSurface::Validator->new;
17  
18 try {
19 $validator->validate_surface($surface);
20 }
21 catch {
22 # handle as necessary...
23 };
24  
25 =cut
26  
27 use Moose;
28 use 5.010;
29  
30 use Format::Util::Numbers qw(roundnear);
31 use List::Util qw( min reduce );
32 use Date::Utility;
33 use Math::Business::BlackScholes::Binaries;
34 use List::MoreUtils qw(indexes any);
35 use VolSurface::Utils qw( get_strike_for_spot_delta );
36  
37 =head1 METHODS
38  
39 =head2 validate_surface
40  
41 This method validates a given surface.
42  
43 For certain errors, exceptions will be thrown. For others,
44 smile_flags will be set on the surface.
45  
46 =cut
47  
48 sub validate_surface {
49 my ($self, $surface) = @_;
50  
51 return 1 if ($surface->type eq 'flat');
52  
53 # Throws exceptions if unsuccessful
54 $self->_do_raw_validation_on($surface);
55  
56 return 1;
57 }
58  
59 # Performs all checks implemented in this package on the given surface.
60 sub _do_raw_validation_on {
61 my ($self, $surface) = @_;
62  
63 _check_structure($surface);
64 _check_identical_surface($surface);
65 _check_volatility_jump($surface);
66 _check_spot_reference($surface) if $surface->type eq 'moneyness';
67 _check_age($surface);
68  
69 $self->check_smiles($surface);
70  
71 _check_termstructure_for_calendar_arbitrage($surface);
72 _admissible_check($surface);
73  
74 return 1;
75 }
76  
77 sub _check_identical_surface {
78 my $surface = shift;
79  
80 my $existing = $surface->get_existing_surface;
81 my @points = @{$existing->smile_points};
82 my @existing_terms = @{$existing->original_term_for_smile};
83 my @new_terms = @{$surface->original_term_for_smile};
84  
85 # we return if it is not identical
86 return 1 if $#existing_terms != $#new_terms;
87 return 1 if grep { $existing_terms[$_] != $new_terms[$_] } (0 .. $#existing_terms);
88  
89 foreach my $term (@existing_terms) {
90 foreach my $point (@points) {
91 return 1 if $existing->surface->{$term}->{smile}->{$point} != $surface->surface->{$term}->{smile}->{$point};
92 }
93 }
94 if (time - $existing->recorded_date->epoch > 15000 and not $surface->{underlying_config}->quanto_only) {
95 die('Surface data has not changed since last update [' . $existing->recorded_date->epoch . '].');
96 }
97 return;
98 }
99  
100 sub _check_volatility_jump {
101 my $surface = shift;
102  
103 my $existing = $surface->get_existing_surface;
104 my @terms = @{$surface->original_term_for_smile};
105 my @points = @{$surface->smile_points};
106 my $type = $surface->type;
107  
108 for (my $i = 0; $i < $#terms; $i++) {
109 my $days = $terms[$i];
110 for (my $j = 0; $j < $#points; $j++) {
111 my $sought_point = $points[$j];
112 my $new_vol = $surface->get_volatility({
113 $type => $sought_point,
114 days => $days,
115 });
116 my $existing_vol = $existing->get_volatility({
117 $type => $sought_point,
118 days => $days,
119 });
120 my $diff = abs($new_vol - $existing_vol);
121 my $percentage_diff = $diff / $existing_vol * 100;
122 if ($diff > 0.03 and $percentage_diff > 100) {
123 die( 'Big difference found on term['
124 . $days
125 . '] for point ['
126 . $sought_point
127 . '] with absolute diff ['
128 . $diff
129 . '] percentage diff ['
130 . $percentage_diff
131 . ']');
132 }
133 }
134 }
135  
136 return 1;
137 }
138  
139 sub _admissible_check {
140 my $surface = shift;
141  
142 my $underlying_config = $surface->underlying_config;
143 my $builder = $surface->builder;
144 my $calendar = $surface->calendar;
145 my $surface_type = $surface->type;
146 my $S = ($surface_type eq 'delta') ? $underlying_config->spot : $surface->spot_reference;
147 my $premium_adjusted = $underlying_config->{market_convention}->{delta_premium_adjusted};
148 my $now = Date::Utility->new;
149  
150 my $utils = Quant::Framework::VolSurface::Utils->new;
151 foreach my $day (@{$surface->_days_with_smiles}) {
152 my $date_expiry = Date::Utility->new(time + $day * 86400);
153 $date_expiry = $calendar->trades_on($date_expiry) ? $date_expiry : $calendar->trade_date_after($date_expiry);
154 my $adjustment;
155 if ($underlying_config->market_prefer_discrete_dividend) {
156 $adjustment = $builder->dividend_adjustments_for_period({
157 start => $now,
158 end => $date_expiry,
159 });
160 $S += $adjustment->{spot};
161 }
162 my $atid = $utils->effective_date_for($date_expiry)->days_between($utils->effective_date_for($now));
163 # If intraday or not FX, then use the exact duration with fractions of a day.
164 die("Invalid tenor[$atid] on surface") if ($atid == 0);
165 my $t = $atid / 365;
166 my $r = $builder->build_interest_rate->interest_rate_for($t);
167 my $q = ($underlying_config->market_prefer_discrete_dividend) ? 0 : $builder->build_dividend->dividend_rate_for($t);
168 my $smile = $surface->surface->{$day}->{smile};
169  
170 my @volatility_level = sort { $a <=> $b } keys %{$smile};
171 my $first_vol_level = $volatility_level[0];
172 my $last_vol_level = $volatility_level[-1];
173  
174 my %prev;
175  
176 foreach my $vol_level (@volatility_level) {
177 my $vol = $smile->{$vol_level};
178 my $barrier;
179 # Temporarily get the Call strike via the Put side of the algorithm,
180 # as it seems not to go crazy at the extremities. Should give the same barrier.
181 if ($surface_type eq 'delta') {
182 my $conversion_args = {
183 atm_vol => $vol,
184 t => $t,
185 r_rate => $r,
186 q_rate => $q,
187 spot => $S,
188 premium_adjusted => $premium_adjusted
189 };
190  
191 if ($vol_level > 50) {
192 $conversion_args->{delta} = exp(-$r * $t) - $vol_level / 100;
193 $conversion_args->{option_type} = 'VANILLA_PUT';
194 } else {
195 $conversion_args->{delta} = $vol_level / 100;
196 $conversion_args->{option_type} = 'VANILLA_CALL';
197 }
198 $barrier = get_strike_for_spot_delta($conversion_args);
199 } elsif ($surface_type eq 'moneyness') {
200 $barrier = $vol_level / 100 * $S;
201 }
202  
203 if ($underlying_config->market_prefer_discrete_dividend) {
204  
205 $barrier += $adjustment->{barrier};
206 }
207 my $prob = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier, $t, $r, $r - $q, $vol);
208 my $slope;
209  
210 if (exists $prev{prob}) {
211 $slope = ($prob - $prev{prob}) / ($vol_level - $prev{vol_level});
212  
213 # Admissible Check 1.
214 # For delta surface, the strike(prob) is decreasing(increasing) across delta point, hence the slope is positive
215 # For moneyness surface, the strike(prob) is increasing(decreasing) across moneyness point, hence the slope is negative
216 if ($surface_type eq 'delta' and $slope <= 0) {
217 die("Admissible check 1 failure for maturity[$day]. BS digital call price decreases between $prev{vol_level} and " . $vol_level);
218 }
219  
220 if ($surface_type eq 'moneyness' and $slope >= 0.0) {
221 die("Admissible check 1 failure for maturity[$day]. BS digital call price decreases between $prev{vol_level} and " . $vol_level);
222 }
223 }
224  
225 # Admissible Check 4.
226 # The actual check is that when K = 0, BS call price = e^(-rt)S.
227 # What we've implemented is largely equivalent, and easier to check:
228 # digital call prob = 1 for very small K.
229 $barrier = 0.00000001;
230 my $bs_theo = Math::Business::BlackScholes::Binaries::call($S, $barrier, $t, $r, $r - $q, $vol);
231 my $bs_theo_before_discounted = $bs_theo / (exp(-$r * $t));
232  
233 if ($bs_theo_before_discounted < 0.95) {
234 die(
235 "Admissible check 4 failure for maturity[$day] vol at level [$vol_level]. BS digital call theo prob[$bs_theo] not 1 when barrier -> zero."
236 );
237  
238 }
239  
240 # Admissible Check 5.
241 # The call price of an infinity strike should be zero.
242 $barrier = $S * 10000;
243 my $call_prob_for_inf_strike = Math::Business::BlackScholes::Binaries::call($S, $barrier, $t, $r, $r - $q, $vol);
244 if ($call_prob_for_inf_strike > 1e-10) {
245 die( "Admissible check 5 failure for maturity[$day] vol at level[$vol_level].BS digital call price not -> 0 ["
246 . $call_prob_for_inf_strike
247 . "] as barrier -> 'infinity'.");
248 }
249  
250 %prev = (
251 slope => $slope,
252 prob => $prob,
253 vol_level => $vol_level,
254 );
255  
256 next
257 if ($vol_level == $first_vol_level
258 || $vol_level == $last_vol_level
259 || $surface_type eq 'delta');
260  
261 $barrier = $vol_level / 100 * $S;
262 my $h = (2.0 / 100) * $S;
263  
264 $vol = $surface->get_volatility({
265 moneyness => ($vol_level - 2),
266 days => $day
267 });
268 my $bet_minus_h = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier - $h, $t, $r, $r - $q, $vol);
269  
270 $vol = $surface->get_volatility({
271 moneyness => ($vol_level),
272 days => $day
273 });
274 my $bet = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier, $t, $r, $r - $q, $vol);
275  
276 $vol = $surface->get_volatility({
277 moneyness => ($vol_level + 2),
278 days => $day
279 });
280 my $bet_plus_h = Math::Business::BlackScholes::Binaries::vanilla_call($S, $barrier + $h, $t, $r, $r - $q, $vol);
281  
282 ## The actual finite difference formula has a / $h**2, but since we're checking
283 ## for negativity, we don't need it. Also, we introducted an error margin to allow
284 ## surfaces that are close to passing through.
285 my $convexity_flag = $bet_minus_h - 2 * $bet + $bet_plus_h;
286 if ($convexity_flag < -0.009) {
287 die("Admissible check 2 failure for maturity[$day] strike center[$vol_level] convexity value is [$convexity_flag].");
288 }
289 }
290 }
291  
292 return 1;
293 }
294  
295 sub _check_spot_reference {
296 my $surface = shift;
297  
298 die('spot_reference is undef during volupdate for underlying [' . $surface->symbol . ']')
299 unless $surface->spot_reference;
300  
301 return 1;
302 }
303  
304 sub _check_age {
305 my $surface = shift;
306  
307 my $market = $surface->underlying_config->market_name;
308 my $delay = $market eq 'forex' ? 7200 : 12 * 3600;
309  
310 die('VolSurface is more than 2 hours old')
311 if time - $surface->recorded_date->epoch > $delay;
312  
313 return 1;
314 }
315  
316 # Make sure given surface seems reasonable.
317 sub _check_structure {
318 my $surface = shift;
319  
320 my $surface_hashref = $surface->surface;
321 my $system_symbol = $surface->underlying_config->system_symbol;
322  
323 # Somehow I do not know why there is a limit of term on delta surface, but
324 # for moneyness we might need at least up to 2 years to get the spread.
325 my $type = $surface->type;
326 my ($max_term, $diff_smile_point) = $type eq 'delta' ? (380, 30) : (750, 100);
327  
328 my $extra_allowed = $surface->underlying_config->extra_vol_diff_by_delta || 0;
329 my $max_vol_change_by_delta = 0.4 + $extra_allowed;
330  
331 my @days = keys %{$surface_hashref};
332 die('Must be at least two maturities on vol surface.') if scalar @days < 2;
333  
334 foreach my $day (@days) {
335 if ($day !~ /^\d+$/) {
336 $DB::single = 1;
337 die("Invalid day[$day] in volsurface for underlying[$system_symbol]. Not a positive integer.");
338 } elsif ($day > $max_term) {
339 die("Day[$day] in volsurface for underlying[$system_symbol] greater than allowed.");
340 }
341  
342 if (not grep { exists $surface_hashref->{$day}->{$_} } qw(smile vol_spread)) {
343 die("Missing both smile and atm_spread (must have at least one) for day [$day] on underlying [$system_symbol]");
344 }
345 }
346  
347 my $min_day = min @days;
348 my $market = $surface->underlying_config->market_name;
349  
350 if ($market eq 'forex' and $min_day > 7) {
351 die("ON term is missing in volsurface for underlying $system_symbol, the minimum term is $min_day");
352 }
353  
354 @days = sort { $a <=> $b } @days;
355 my @volatility_level;
356  
357 if ($type eq 'delta') {
358 @volatility_level = sort { $a <=> $b } @{$surface->deltas};
359 } else {
360 @volatility_level = sort { $a <=> $b } @{$surface->moneynesses};
361 }
362  
363 foreach my $vol_level (@volatility_level) {
364 if ($vol_level !~ /^\d+\.?\d+$/) {
365 die("Invalid vol_point[$vol_level] for underlying[$system_symbol]");
366 }
367 }
368  
369 reduce {
370 abs($a - $b) <= $diff_smile_point
371 ? $b
372 : die("Difference between point $a and $b too great.");
373 }
374 @volatility_level;
375  
376 foreach my $day (@days) {
377  
378 if (exists $surface_hashref->{$day}->{smile}) {
379 my $smile = $surface_hashref->{$day}->{smile};
380 my @vol_levels_for_smile = sort { $a <=> $b } keys %{$smile};
381  
382 if ($type eq 'delta') {
383 my $levels_mismatch = (@volatility_level != @vol_levels_for_smile)
384 || (any { $volatility_level[$_] != $vol_levels_for_smile[$_] } (0 .. @volatility_level - 1));
385 if ($levels_mismatch) {
386 die( 'Deltas['
387 . join(',', @vol_levels_for_smile)
388 . "] for maturity[$day], underlying["
389 . $system_symbol
390 . '] are not the same as deltas for rest of surface['
391 . join(',', @volatility_level)
392 . '].');
393 }
394 }
395  
396 reduce {
397 return $a if (not defined $b);
398 abs($smile->{$a} - $smile->{$b}) <= $max_vol_change_by_delta * $smile->{$a}
399 ? $b
400 : die("Invalid volatility points: too big jump from "
401 . "$a:$smile->{$a} to $b:$smile->{$b}"
402 . "for maturity[$day], underlying[$system_symbol]");
403 }
404 @volatility_level;
405  
406 }
407 }
408  
409 return 1;
410 }
411  
412 =head2 check_smiles
413  
414 Performs error checking on multiple smilesof a given surface.
415  
416 =cut
417  
418 sub check_smiles {
419 my ($self, $surface) = @_;
420  
421 foreach my $day (@{$surface->original_term_for_smile}) {
422 $self->check_smile($day, $surface->surface->{$day}->{smile}, $surface->underlying_config->system_symbol);
423 }
424  
425 return 1;
426 }
427  
428 =head2 check_smile
429  
430 Performs error checking on an individual smile of a given surface.
431  
432 =cut
433  
434 sub check_smile {
435 my ($self, $day, $smile, $system_symbol) = @_;
436  
437 $system_symbol ||= 'unknown symbol';
438  
439 foreach my $vol_level (keys %{$smile}) {
440 my $vol = $smile->{$vol_level};
441 if ($vol !~ /^\d?\.?\d*$/ or $vol > 5) {
442 die( 'Invalid smile volatility for '
443 . $day
444 . ' days at volatility level (either delta or moneyness level) '
445 . $vol_level . ' ('
446 . $vol
447 . ') for '
448 . $system_symbol);
449 }
450 }
451  
452 return 1;
453 }
454  
455 #
456 # To ensure that the volatility is arbitrage-free, the total implied variance must be strictly
457 # increasing by forward moneyness.
458 # As proven by Fengler, 2005 "Arbitrage-free smoothing of the implied volatility surface"
459 # p.10, Proposition 2.1
460 #
461 # We check the surface market points. This is usually done at startup when volsurface object is
462 # being created.
463 #
464 # Forward Moneyness = K/F_T
465 sub _check_termstructure_for_calendar_arbitrage {
466 my $surface = shift;
467 my @sorted_expiries = sort { $a <=> $b } @{$surface->original_term_for_smile};
468  
469 my $cloned_surface = $surface->clone;
470 my $surface_type = $surface->type;
471 my $flag = 0;
472 my $error_maturity = 0;
473 my $error_strike = 0;
474 my $message;
475 for (my $i = 1; $i < scalar(@sorted_expiries); $i++) {
476 my $smile = $surface->surface->{$sorted_expiries[$i]}->{smile};
477 my $smile_prev = $surface->surface->{$sorted_expiries[$i - 1]}->{smile};
478  
479 my @volatility_level = sort { $a <=> $b } keys %{$smile};
480 if ($surface_type eq 'delta') {
481 my $vol = $smile->{50};
482 my $vol_prev = $smile_prev->{50};
483 my $T = $sorted_expiries[$i];
484 my $T_prev = $sorted_expiries[$i - 1];
485 if (((($vol)**2) * $T) < (($vol_prev**2) * $T_prev)) {
486 $flag = -1;
487 $error_maturity = $sorted_expiries[$i - 1];
488 $error_strike = 50;
489 $message = 'Variance negative for maturity ' . $error_maturity . ' for ATM';
490 last;
491 }
492 } else {
493 my $atm_level = 100;
494 my $atm_index = indexes { $_ == $atm_level } @volatility_level;
495  
496 my $symbol = $surface->symbol;
497 }
498 }
499 # This check is ad-hoc, just to ensure there are no huge outliers, or calendar arbitrages.
500 if ($flag == -1) {
501 $surface->set_smile_flag($error_maturity, $message);
502 }
503  
504 return 1;
505 }
506  
507 no Moose;
508 __PACKAGE__->meta->make_immutable;
509 1;