Framework/VolSurface/Moneyness.pm untested

filter: Statementstmt 0.0% 0 / 159 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 248 CC 20 SCAR 31.7
CC
20
Cov
0%
clone
90.0
get_volatility
20.0
_calculate_vol_for_delta
12.0
CRAP 23.7
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 Try::Tiny;
19 use Math::Function::Interpolator;
20 use List::MoreUtils qw(indexes);
21 use List::Util qw(min first);
22 use Storable qw( dclone );
23 use JSON qw(from_json);
24  
25 =head2 for_date
26  
27 The date for which we wish data
28  
29 =cut
30  
31 has for_date => (
32 is => 'ro',
33 isa => 'Maybe[Date::Utility]',
34 default => undef,
35 );
36  
37 has document => (
38 is => 'rw',
39 lazy_build => 1,
40 );
41  
42 sub _build_document {
43 my $self = shift;
44  
45 my $document = $self->chronicle_reader->get('volatility_surfaces', $self->symbol);
46  
47 if ($self->for_date and $self->for_date->epoch < Date::Utility->new($document->{date})->epoch) {
48 $document = $self->chronicle_reader->get_for('volatility_surfaces', $self->symbol, $self->for_date->epoch);
49  
50 # This works around a problem with Volatility surfaces and negative dates to expiry.
51 # We have to use the oldest available surface.. and we don't really know when it
52 # was relative to where we are now.. so just say it's from the requested day.
53 # We do not allow saving of historical surfaces, so this should be fine.
54 $document //= {};
55 }
56  
57 return $document;
58 }
59  
60 =head2 save
61  
62 Saves current surface using chronicle writer
63  
64 =cut
65  
66 sub save {
67 my $self = shift;
68  
69 #if chronicle does not have this document, first create it because in document_content we will need it
70 if (not defined $self->chronicle_reader->get('volatility_surfaces', $self->symbol)) {
71 #Due to some strange coding of retrieval for recorded_date, there MUST be an existing document (even empty)
72 #before one can save a document. As a result, upon the very first storage of an instance of the document, we need to create an empty one.
73 $self->chronicle_writer->set('volatility_surfaces', $self->symbol, {});
74 }
75  
76 return $self->chronicle_writer->set('volatility_surfaces', $self->symbol, $self->_document_content, $self->recorded_date);
77 }
78  
79 sub _document_content {
80 my $self = shift;
81  
82 my %structure = (
83 surfaces => {$self->cutoff->code => $self->surface},
84 date => $self->recorded_date->datetime_iso8601,
85 master_cutoff => $self->cutoff->code,
86 symbol => $self->symbol,
87 type => $self->type,
88 spot_reference => $self->spot_reference,
89 );
90  
91 return \%structure;
92 }
93  
94 =head2 type
95  
96 Return the surface type
97  
98 =cut
99  
100 has '+type' => (
101 default => 'moneyness',
102 );
103  
104 =head2 min_vol_spread
105  
106 minimum volatility spread that we can accept for this volatility surface.
107  
108 =cut
109  
110 has min_vol_spread => (
111 is => 'ro',
112 isa => 'Num',
113 default => 3.1 / 100,
114 );
115  
116 has atm_spread_point => (
117 is => 'ro',
118 isa => 'Num',
119 default => 100,
120 );
121  
122 =head2 moneynesses
123  
124 Returns the moneyness points on the surface
125  
126 =cut
127  
128 has moneynesses => (
129 is => 'ro',
130 isa => 'ArrayRef',
131 lazy_build => 1,
132 );
133  
134 sub _build_moneynesses {
135 my $self = shift;
136 return $self->smile_points;
137 }
138  
139 =head2 corresponding_deltas
140  
141 Stores the corresponding moneyness smile in terms on delta.
142 This is aimed to reduced computation time.
143  
144 =cut
145  
146 has corresponding_deltas => (
147 is => 'rw',
148 isa => 'HashRef',
149 default => sub { {} },
150 );
151  
152 =head2 spot_reference
153  
154 Get the spot reference used to calculate the surface.
155 We should always use reference spot of the surface for any moneyness-related vol calculation
156  
157 =cut
158  
159 has spot_reference => (
160 is => 'rw',
161 isa => 'Num',
162 lazy_build => 1,
163 );
164  
165 sub _build_spot_reference {
166 my $self = shift;
167  
168 return $self->document->{spot_reference};
169 }
170  
171 =head2 get_volatility
172  
173 USAGE:
174  
175 my $vol = $s->get_volatility({moneyness => 96, days => 7});
176 my $vol = $s->get_volatility({strike => $bet->barrier, tenor => '1M'});
177 my $vol = $s->get_volatility({moneyness => 90, expiry_date => Date::Utility->new});
178  
179 =cut
180  
181 sub get_volatility {
182 my ($self, $args) = @_;
183  
184 if (scalar(grep { defined $args->{$_} } qw(delta moneyness strike)) != 1) {
185 die("Must pass exactly one of [delta, moneyness, strike] to get_volatility.");
186 }
187  
188 $args->{days} = $self->underlying_config->default_volatility_duration // $self->_convert_expiry_to_day($args);
189  
190 my $vol;
191 if ($args->{delta}) {
192  
193 # we are handling delta seperately because it involves
194 # a lot more steps to calculate vol for a delta point
195 # on a moneyness surface
196 $vol = $self->_calculate_vol_for_delta({
197 delta => $args->{delta},
198 days => $args->{days},
199 });
200 } else {
201 my $sought_point =
202 $args->{strike}
203 ? $args->{strike} / $self->spot_reference * 100
204 : $args->{moneyness};
205  
206 my $calc_args = {
207 sought_point => $sought_point,
208 days => $args->{days}};
209 $vol = $self->SUPER::get_volatility($calc_args);
210 }
211  
212 return $vol;
213 }
214  
215 =head2 interpolate
216  
217 This is how you could interpolate across smile.
218 This uses the default interpolation method of the surface.
219  
220 $surface->interpolate({smile => $smile, sought_point => $sought_point});
221 =cut
222  
223 sub interpolate {
224 my ($self, $args) = @_;
225  
226 my $method = keys %{$args->{smile}} < 5 ? 'quadratic' : 'cubic';
227 my $interpolator = Math::Function::Interpolator->new(points => $args->{smile});
228  
229 return $interpolator->$method($args->{sought_point});
230 }
231  
232 =head2 set_corresponding_deltas
233  
234 Since we allow getting volatility for a particular delta point
235 on a moneyness surface, here is how you could cache it.
236  
237 $moneyness->set_corresponding_deltas(7, {25 => 0.1, 50 => 0.2, 75 => 0.3});
238  
239 =cut
240  
241 sub set_corresponding_deltas {
242 my ($self, $days, $smile) = @_;
243  
244 my $deltas = $self->corresponding_deltas;
245 $deltas->{$days} = $smile;
246  
247 return;
248 }
249  
250 # rr and bf only make sense in delta term. Here we convert the smile to a delta smile.
251 override get_market_rr_bf => sub {
252 my ($self, $day) = @_;
253  
254 my %smile = map { $_ => $self->_calculate_vol_for_delta({delta => $_, days => $day}) } qw(25 50 75);
255  
256 return $self->get_rr_bf_for_smile(\%smile);
257 };
258  
259 ## PRIVATE ##
260  
261 sub _calculate_vol_for_delta {
262 my ($self, $args) = @_;
263  
264 my $delta = $args->{delta};
265 my $days = $args->{days};
266 my $smile;
267  
268 if (exists $self->corresponding_deltas->{$days}) {
269 $smile = $self->corresponding_deltas->{$days};
270 } else {
271 $smile = $self->_convert_moneyness_smile_to_delta($days);
272 $self->set_corresponding_deltas($days, $smile);
273 }
274  
275 return $smile->{$delta}
276 ? $smile->{$delta}
277 : $self->_interpolate_delta({
278 smile => $smile,
279 sought_point => $delta
280 });
281 }
282  
283 sub _interpolate_delta {
284 my ($self, $args) = @_;
285  
286 my %smile = %{$args->{smile}};
287  
288 die('minimum of three points on a smile')
289 if keys %smile < 3;
290  
291 my @sorted = sort { $a <=> $b } keys %smile;
292 my %new_smile =
293 map { $_ => $smile{$_} } grep { $_ > 1 and $_ < 99 } @sorted;
294  
295 if (keys %new_smile < 5) {
296 my @diff = map { abs($_ - 50) } @sorted;
297 my $atm_index = indexes { min(@diff) == abs($_ - 50) } @sorted;
298 %new_smile =
299 map { $sorted[$_] => $smile{$sorted[$_]} } ($atm_index - 1 .. $atm_index + 1);
300 }
301  
302 $args->{smile} = \%new_smile;
303  
304 return $self->interpolate($args);
305 }
306  
307 sub _convert_moneyness_smile_to_delta {
308 my ($self, $days) = @_;
309  
310 my $moneyness_smile = $self->get_smile($days);
311  
312 my %strikes =
313 map { get_strike_for_moneyness({moneyness => $_ / 100, spot => $self->spot_reference,}) => $moneyness_smile->{$_} } keys %$moneyness_smile;
314 my %deltas;
315 foreach my $strike (keys %strikes) {
316 my $vol = $strikes{$strike};
317 my $delta = $self->_convert_strike_to_delta({
318 strike => $strike,
319 days => $days,
320 vol => $vol
321 });
322 $deltas{$delta} = $vol;
323 }
324  
325 return \%deltas,;
326 }
327  
328 sub _convert_strike_to_delta {
329 my ($self, $args) = @_;
330 my ($days, $vol, $strike) = @{$args}{'days', 'vol', 'strike'};
331 my $tiy = $days / 365;
332 my $builder = $self->builder;
333  
334 return 100 * get_delta_for_strike({
335 strike => $strike,
336 atm_vol => $vol,
337 t => $tiy,
338 spot => $self->spot_reference,
339 r_rate => $builder->build_interest_rate->interest_rate_for($tiy),
340 q_rate => $builder->build_dividend->dividend_rate_for($tiy),
341 premium_adjusted => $self->underlying_config->market_convention->{delta_premium_adjusted},
342 });
343 }
344  
345 sub _extrapolate_smile_down {
346 my $self = shift;
347  
348 my $first_market_point = $self->original_term_for_smile->[0];
349  
350 return $self->surface->{$first_market_point}->{smile};
351 }
352  
353 =head2 clone
354  
355 USAGE:
356  
357 my $clone = $s->clone({
358 surface => $my_new_surface,
359 cutoff => $my_new_cutoff,
360 });
361  
362 Returns a new Quant::Framework::VolSurface instance. You can pass overrides to override an attribute value as it is on the original surface.
363  
364 =cut
365  
366 sub clone {
367 my ($self, $args) = @_;
368  
369 my %clone_args;
370 %clone_args = %$args if $args;
371  
372 $clone_args{spot_reference} = $self->spot_reference
373 if (not exists $clone_args{spot_reference});
374 $clone_args{underlying_config} = $self->underlying_config
375 if (not exists $clone_args{underlying_config});
376 $clone_args{cutoff} = $self->cutoff
377 if (not exists $clone_args{cutoff});
378  
379 if (not exists $clone_args{surface}) {
380 my $orig_surface = dclone($self->surface);
381 my %surface_to_clone = map { $_ => $orig_surface->{$_} } @{$self->original_term_for_smile};
382 $clone_args{surface} = \%surface_to_clone;
383 }
384  
385 $clone_args{recorded_date} = $self->recorded_date
386 if (not exists $clone_args{recorded_date});
387 $clone_args{print_precision} = $self->print_precision
388 if (not exists $clone_args{print_precision});
389 $clone_args{original_term} = dclone($self->original_term)
390 if (not exists $clone_args{original_term});
391  
392 $clone_args{chronicle_reader} = $self->chronicle_reader;
393 $clone_args{chronicle_writer} = $self->chronicle_writer;
394  
395 return $self->meta->name->new(\%clone_args);
396 }
397  
398 =head2 cutoff
399  
400 default to closing on the underlying.
401  
402 =cut
403  
404 has cutoff => (
405 is => 'ro',
406 isa => 'qf_cutoff_helper',
407 lazy_build => 1,
408 coerce => 1,
409 );
410  
411 sub _build_cutoff {
412 my $self = shift;
413  
414 my $date = $self->for_date ? $self->for_date : Date::Utility->new;
415  
416 return Quant::Framework::VolSurface::Cutoff->new('UTC ' . $self->calendar->standard_closing_on($date)->time_hhmm);
417 }
418  
419 no Moose;
420 __PACKAGE__->meta->make_immutable;
421  
422 1;