-
Notifications
You must be signed in to change notification settings - Fork 581
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
initial commit #22
Open
Lapsilago
wants to merge
8
commits into
google:master
Choose a base branch
from
Lapsilago:bacheliersabr
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
initial commit #22
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
cdcdaf6
initial commit
Lapsilago 60aa672
changes made after inspection
Lapsilago c828d83
commit after several changes
Lapsilago 338a057
hagan test
Lapsilago 241dc72
cpyright change
Lapsilago bd65833
example bachelier implied vol added
Lapsilago b5cb6c9
deltetions and headers
Lapsilago aee7d84
another header
Lapsilago File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added
BIN
+590 Bytes
tf_quant_finance/math/interpolation/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+695 Bytes
tf_quant_finance/math/interpolation/cubic/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+8.76 KB
tf_quant_finance/math/interpolation/cubic/__pycache__/cubic_interpolation.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+585 Bytes
tf_quant_finance/math/interpolation/linear/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+3.55 KB
tf_quant_finance/math/interpolation/linear/__pycache__/linear_interpolation.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+1010 Bytes
tf_quant_finance/math/optimizer/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+13.7 KB
tf_quant_finance/math/optimizer/__pycache__/conjugate_gradient.cpython-37.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added
BIN
+818 Bytes
tf_quant_finance/math/pde/grids/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+18.9 KB
tf_quant_finance/math/pde/grids/__pycache__/grids_impl.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+194 Bytes
tf_quant_finance/math/pde/internal/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+2.28 KB
...t_finance/math/pde/internal/__pycache__/pde_time_marching_schemes_internal.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+1019 Bytes
tf_quant_finance/math/pde/time_marching_schemes/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+2.76 KB
...inance/math/pde/time_marching_schemes/__pycache__/pde_time_marching_scheme.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+9.43 KB
...nance/math/pde/time_marching_schemes/__pycache__/pde_time_marching_schemes.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+867 Bytes
tf_quant_finance/math/random_ops/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+1.48 KB
tf_quant_finance/math/random_ops/__pycache__/stateless.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+560 Bytes
tf_quant_finance/math/random_ops/halton/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+23 KB
tf_quant_finance/math/random_ops/halton/__pycache__/halton_impl.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+556 Bytes
tf_quant_finance/math/random_ops/sobol/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added
BIN
+6.32 KB
tf_quant_finance/math/random_ops/sobol/__pycache__/sobol_impl.cpython-37.pyc
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,252 @@ | ||
# Lint as: python3 | ||
# Copyright 2020 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import tensorflow.compat.v2 as tf | ||
import numpy as np | ||
|
||
|
||
def _ncdf(x): | ||
return (tf.math.erf(x / _SQRT_2) + 1.) / 2.0 | ||
|
||
def _npdf(x): | ||
return tf.math.exp(-x**2/2)/_SQRT_2/_SQRT_pi | ||
|
||
_SQRT_2 = tf.math.sqrt(tf.constant(2.0,dtype=tf.float64)) #1.4142135623730951 | ||
_SQRT_pi = tf.math.sqrt(tf.constant(np.pi,dtype=tf.float64)) | ||
|
||
# straight fwd implementation of the Bachelier pricing | ||
# there is a version with just one call to exp !! | ||
|
||
|
||
def bachelier_option_price(spots, | ||
strikes, | ||
volatilities, | ||
expiries, | ||
discount_rates = None, | ||
discount_factors = None, | ||
is_call_options=None, | ||
dtype = None, | ||
name = None): | ||
""" computes the Bachelier price for a batch of European options. | ||
We assume a standard Brownian motion of the form | ||
dS = r dt + sigma dW | ||
for the underlying | ||
|
||
## References: | ||
[1] Kienitz, J. "Interest Rate Derivatives Explained I", Palgrave McMillan (2014) p.119 | ||
Link: https://www.palgrave.com/gp/book/9781137360069 | ||
[2] Terakado, Satoshi: On the Option Pricing Formula Based on the Bachelier Model | ||
Link: https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3428994 | ||
|
||
#### Examples | ||
|
||
spots = np.array([0.03, 0.02]) | ||
strikes = np.array([.02, .02]) | ||
volatilities = np.array([.004, .005]) | ||
expiries = 2.0 | ||
discount_rates = [0.02, 0.01] | ||
computed_prices = bachelier_option_price( | ||
spots, | ||
strikes, | ||
volatilities, | ||
expiries, | ||
dtype=tf.float64) | ||
# Expected print output of computed prices: | ||
# <tf.Tensor: id=90474, shape=(2,), dtype=float64, numpy=array([0.01008754, 0.00199471])> | ||
|
||
Args: | ||
|
||
spots : A real `Tensor` of any shape. The current spot prices to | ||
expiry. | ||
strikes : A real `Tensor` of the same shape and dtype as `spots`. The | ||
strikes of the options to be priced. | ||
volatilities : A real `Tensor` of same shape and dtype as `spots`. The | ||
volatility to expiry. | ||
expiries : A real `Tensor` of same shape and dtype as `spots`. | ||
discount_rates : rates from which discount factor via | ||
discount factor = exp(-discount rate * T) are calculated | ||
discountr_factors : A real 'Tensor' of same shape and dtype as 'spots' The | ||
discounting factor; discount_rates = -log(discount factor) * expiries | ||
is_call_options : A boolean `Tensor` of a shape compatible with | ||
`volatilities`. Indicates whether the option is a call (if True) or a put | ||
(if False). If not supplied, call options are assumed. | ||
dtype: supplied dtype but converted to tf.float64 | ||
name: name of the function | ||
|
||
Returns | ||
|
||
option_prices: A `Tensor` of the same shape as `spots`. The Bachelier | ||
price of the options. | ||
|
||
|
||
|
||
""" | ||
with tf.compat.v1.name_scope( | ||
name, | ||
default_name='bachelier_option_price', | ||
values=[ | ||
spots, strikes, volatilities, expiries, discount_rates, | ||
discount_factors, is_call_options | ||
]): | ||
|
||
spots = tf.convert_to_tensor(spots, dtype=tf.float64, name='forwards') | ||
strikes = tf.convert_to_tensor(strikes, dtype=tf.float64, name='strikes') | ||
volatilities = tf.convert_to_tensor(volatilities, tf.float64, name='volatilities') | ||
expiries = tf.convert_to_tensor(expiries, tf.float64, name='expiries') | ||
if (discount_rates != None and discount_factors != None): | ||
raise ValueError('Either discount rates or discount factors have to be used.') | ||
|
||
if (discount_rates != None and discount_factors == None): | ||
rates = tf.convert_to_tensor(discount_rates, tf.float64, name='rates') | ||
df = tf.math.exp(-rates * expiries) | ||
elif (discount_factors != None and discount_rates == None): | ||
rates = -tf.math.log(tf.convert_to_tensor(discount_rates, tf.float64, name='rates')) / expiries | ||
df = discount_factors | ||
else: | ||
rates = 0.0 | ||
df = tf.convert_to_tensor(rates, dtype=tf.float64, name='discount_rates') | ||
|
||
|
||
z = tf.zeros_like(strikes) | ||
|
||
#normal = tfp.distributions.Normal( | ||
# loc=tf.zeros([], dtype=spots.dtype), scale=1) | ||
|
||
vt = volatilities * tf.math.sqrt(expiries) | ||
|
||
z = tf.where(rates == 0., (spots - strikes)/vt, | ||
(spots - strikes * df) / (volatilities | ||
* tf.math.sqrt(0.5 * (1.-tf.math.exp(-2. * rates*expiries)) / rates))) | ||
|
||
n1 = _ncdf(z) | ||
n2 = _npdf(z) | ||
calls = tf.where(rates==0., (spots - strikes) * n1 + vt * n2, | ||
(spots - strikes * df) * n1 | ||
+ volatilities * tf.math.sqrt(0.5 * (1 - tf.math.exp(-2 * rates * expiries)) / rates)) | ||
|
||
|
||
if is_call_options is None: | ||
return calls | ||
|
||
puts = calls - spots + strikes * tf.math.exp(-rates * expiries) | ||
|
||
return tf.where(is_call_options, calls, puts) | ||
|
||
|
||
|
||
def dawson_option_price(forwards, | ||
strikes, | ||
volatilities, | ||
expiries, | ||
discount_rates = None, | ||
discount_factors = None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also, add |
||
is_call_options=None, | ||
dtype = None, | ||
name = None): | ||
|
||
"""Computes the Bachelier price for a batch of European options. | ||
We assume a standard Brownian motion of the form | ||
dS = r dt + sigma dW | ||
for the underlying | ||
|
||
## References: | ||
[1] Dawson, P., Blake, D., Cairns, A. J. G. and Dowd, K.: Options on normal under- | ||
lyings, CRIS Discussion Paper Series – 2007.VII, 2007. | ||
|
||
#### Examples | ||
spots = np.array([0.03, 0.02]) | ||
strikes = np.array([.02, .02]) | ||
volatilities = np.array([.004, .005]) | ||
expiries = 2.0 | ||
expiries = 1.0 | ||
computed_prices = dawson_option_price( | ||
forwards, | ||
strikes, | ||
volatilities, | ||
expiries, | ||
dtype=tf.float64) | ||
# Expected print output of computed prices: | ||
# <tf.Tensor: id=90474, shape=(2,), dtype=float64, numpy=array([0.01008754, 0.00199471])> | ||
|
||
Args: | ||
|
||
forwards: A real `Tensor` of any shape. The current forward prices to | ||
expiry. | ||
strikes: A real `Tensor` of the same shape and dtype as `forwards`. The | ||
strikes of the options to be priced. | ||
volatilities: A real `Tensor` of same shape and dtype as `forwards`. The | ||
volatility to expiry. | ||
expiries : A real `Tensor` of same shape and dtype as `spots`. | ||
discount_rates : rates from which discount factor via | ||
discount factor = exp(-discount rate * T) are calculated | ||
discount_factors : A real 'Tensor' of same shape and dtype as 'spots' The | ||
discounting factor; discount_rates = -log(discount factor) * expiries | ||
is_call_options : A boolean `Tensor` of a shape compatible with | ||
`volatilities`. Indicates whether the option is a call (if True) or a put | ||
(if False). If not supplied, call options are assumed. | ||
dtype: supplied dtype but converted to tf.float64 | ||
name: name of the function | ||
|
||
Returns: | ||
option_prices: A `Tensor` of the same shape as `forwards`. The Bachelier | ||
price of the options. | ||
|
||
|
||
|
||
""" | ||
with tf.compat.v1.name_scope( | ||
name, | ||
default_name='dawson_option_price', | ||
values=[ | ||
forwards, strikes, volatilities, expiries, discount_factors, | ||
discount_rates, is_call_options | ||
]): | ||
|
||
forwards = tf.convert_to_tensor(forwards, dtype=tf.float64, name='forwards') | ||
strikes = tf.convert_to_tensor(strikes, dtype=tf.float64, name='strikes') | ||
volatilities = tf.convert_to_tensor(volatilities, dtype=tf.float64, name='volatilities') | ||
expiries = tf.convert_to_tensor(expiries, dtype=tf.float64, name='expiries') | ||
|
||
# check if discount rates or discount factor version is used | ||
if (discount_rates != None and discount_factors != None): | ||
raise ValueError('Either discount rates or discount factors have to be used.') | ||
|
||
if (discount_rates != None and discount_factors == None): | ||
discount_factors = tf.math.exp(-tf.convert_to_tensor(discount_rates, tf.float64, name='discount factors')*expiries) | ||
else: | ||
if (discount_factors == None and discount_rates == None): | ||
discount_factors = 1.0 | ||
discount_factors = tf.convert_to_tensor(discount_factors, dtype=tf.float64, name='discount_factors') | ||
|
||
vt = volatilities * tf.math.sqrt(expiries) | ||
|
||
z = (forwards - strikes) / vt | ||
|
||
# calculate constituents of Bachelier formula | ||
n1 = _ncdf(z) | ||
n2 = _npdf(z) | ||
undiscounted_calls = (forwards - strikes) * n1 + vt * n2 # Bachelier option price | ||
|
||
# check if calls or puts need to be considered | ||
if is_call_options is None: | ||
return discount_factors * undiscounted_calls | ||
undiscounted_forward = forwards - strikes | ||
undiscounted_puts = undiscounted_calls - undiscounted_forward | ||
|
||
# return call, resp. put prices | ||
return discount_factors * tf.where(is_call_options, undiscounted_calls, | ||
undiscounted_puts) | ||
|
||
|
137 changes: 137 additions & 0 deletions
137
tf_quant_finance/volatility/sabr_approx_hagan_tf_test.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
""" | ||
Created on Fri Nov 22 15:22:13 2019 | ||
|
||
# Copyright 2020 Joerg Kienitz | ||
|
||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
@author: Joerg Kienitz | ||
""" | ||
|
||
import sabr_approx_tf as sabr | ||
import bachelier_tf as vptf | ||
import volbachelier_tf as bvtf | ||
|
||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
|
||
# SABR parameters | ||
# SABR parameters | ||
f = 1.0 #0.00434015 | ||
alpha_org = 0.16575423 | ||
beta_org = .6#0.7#0.16415365 | ||
nu_org = 0.2632859 | ||
rho_org = -0.32978014 | ||
T = 5 | ||
|
||
displacement_org = 0. #0.005 | ||
kmin = -displacement_org | ||
kmax = 10 | ||
kval = np.arange(kmin, kmax, 0.01) | ||
kval[0] = (kval[0] + kval[1])/2 | ||
vol = np.zeros(len(kval)) | ||
|
||
alpha_vec = [0.01, 0.02, 0.05, 0.075, 0.1, 0.15, 0.175, 0.2, 0.25, 0.3, 0.5, 0.75, 1., 1.5] | ||
beta_vec = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] | ||
rho_vec = [-1, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] | ||
nu_vec = [0.001, 0.01, 0.02, 0.05, 0.075, 0.1, 0.15, 0.2, 0.5, 0.75, 1.0, 1.5] | ||
displacement_vec = [0.0, 0.005, 0.01, 0.015, 0.02, 0.025, 0.03, 0.05] | ||
|
||
print('alpha varies') | ||
for alpha in alpha_vec: | ||
print('alpha: ', alpha) | ||
yval = sabr.volsabr_h_n_tf(f, kval, T, displacement_org, alpha, beta_org, rho_org,nu_org) | ||
cval = vptf.bachelier_option_price(f,kval,yval,T,0.) | ||
yval1 = bvtf.volbachelier_tf(1, kval, f, T, cval) | ||
label1 = 'approx ' + str(alpha) | ||
label2 = 'iv ' + str(alpha) | ||
plt.plot(kval,yval,label= label1) | ||
plt.plot(kval, yval1, label=label2) | ||
plt.title('alpha varies') | ||
plt.legend() | ||
plt.show() | ||
|
||
|
||
print('beta varies') | ||
for beta in beta_vec: | ||
print('parameters: ', beta) | ||
yval = sabr.volsabr_h_n_tf(f, kval, T, displacement_org, alpha_org, beta, rho_org,nu_org) | ||
cval = vptf.bachelier_option_price(f,kval,yval,T,0.) | ||
yval1 = bvtf.volbachelier_tf(1, kval, f, T, cval) | ||
label1 = 'approx ' + str(beta) | ||
label2 = 'iv ' + str(beta) | ||
plt.plot(kval,yval,label= label1) | ||
plt.plot(kval, yval1, label=label2) | ||
plt.title('beta varies') | ||
plt.legend() | ||
plt.show() | ||
|
||
print('rho varies') | ||
for rho in rho_vec: | ||
print('parameters: ', rho) | ||
yval = sabr.volsabr_h_n_tf(f, kval, T, displacement_org, alpha_org, beta_org, rho,nu_org) | ||
cval = vptf.bachelier_option_price(f,kval,yval,T,0.) | ||
yval1 = bvtf.volbachelier_tf(1, kval, f, T, cval) | ||
label1 = 'approx ' + str(rho) | ||
label2 = 'iv ' + str(rho) | ||
plt.plot(kval,yval,label= label1) | ||
plt.plot(kval, yval1, label=label2) | ||
plt.title('rho varies') | ||
plt.legend() | ||
plt.show() | ||
|
||
print('nu varies') | ||
for nu in nu_vec: | ||
print('parameters: ', nu) | ||
yval = sabr.volsabr_h_n_tf(f, kval, T, displacement_org, alpha_org, beta_org, rho_org,nu) | ||
cval = vptf.bachelier_option_price(f,kval,yval,T,0.) | ||
yval1 = bvtf.volbachelier_tf(1, kval, f, T, cval) | ||
label1 = 'approx ' + str(nu) | ||
label2 = 'iv ' + str(nu) | ||
plt.plot(kval,yval,label= label1) | ||
plt.plot(kval, yval1, label=label2) | ||
plt.title('nu varies') | ||
plt.legend() | ||
plt.show() | ||
|
||
print('displacement varies') | ||
for displacement in displacement_vec: | ||
print('parameters: ', displacement) | ||
yval = sabr.volsabr_h_n_tf(f, kval, T, displacement_org, alpha_org, beta_org, rho_org,nu_org) | ||
label1 = 'approx ' + str(displacement) | ||
plt.plot(kval,yval,label= label1) | ||
plt.title('displacement varies') | ||
plt.legend() | ||
plt.show() | ||
|
||
# different approximation techniques for SABR and Mean Reverting SABR | ||
kappa = 0.5 | ||
cap = 3. | ||
|
||
yval1 = sabr.volsabr_h_n_tf(f, kval, T, displacement_org, alpha_org, beta_org, rho_org,nu_org) | ||
yval2 = sabr.volsabr_mr_n_tf(f,kval,T,displacement_org, alpha_org, beta_org, rho_org, nu_org, kappa) | ||
yval3 = sabr.volsabr_h_n_cap_tf(f,kval,T,displacement_org, alpha_org, beta_org, rho_org, nu_org, cap) | ||
|
||
label1 = 'Hagan approx ' | ||
label2 = 'MR SABR approx ' | ||
label3 = 'Capped SABR approx ' | ||
|
||
plt.plot(kval,yval1,label= label1) | ||
plt.plot(kval,yval2,label= label2) | ||
plt.plot(kval,yval3,label= label3) | ||
plt.title('different SABR approximation') | ||
plt.legend() | ||
plt.show() | ||
|
||
|
||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please follow the pattern here
spots = tf.convert_to_tensor(spots, dtype=dtype, name='forwards')
dtype = spots.dtype
...