Git Product home page Git Product logo

google / tf-quant-finance Goto Github PK

View Code? Open in Web Editor NEW
4.3K 166.0 549.0 17.32 MB

High-performance TensorFlow library for quantitative finance.

License: Apache License 2.0

Python 68.06% Shell 0.04% Jupyter Notebook 29.70% Dockerfile 0.10% Starlark 2.09%
tensorflow quantitative-finance python finance numerical-methods numerical-optimization numerical-integration high-performance high-performance-computing gpu

tf-quant-finance's Introduction

TF Quant Finance: TensorFlow based Quant Finance Library

Build Status

Table of contents

  1. Introduction
  2. Installation
  3. TensorFlow training
  4. Development roadmap
  5. Examples
  6. Contributing
  7. Development
  8. Community
  9. Disclaimers
  10. License

Introduction

This library provides high-performance components leveraging the hardware acceleration support and automatic differentiation of TensorFlow. The library will provide TensorFlow support for foundational mathematical methods, mid-level methods, and specific pricing models. The coverage is being expanded over the next few months.

The library is structured along three tiers:

  1. Foundational methods. Core mathematical methods - optimisation, interpolation, root finders, linear algebra, random and quasi-random number generation, etc.

  2. Mid-level methods. ODE & PDE solvers, Ito process framework, Diffusion Path Generators, Copula samplers etc.

  3. Pricing methods and other quant finance specific utilities. Specific Pricing models (e.g., Local Vol (LV), Stochastic Vol (SV), Stochastic Local Vol (SLV), Hull-White (HW)) and their calibration. Rate curve building, payoff descriptions, and schedule generation.

We aim for the library components to be easily accessible at each level. Each layer will be accompanied by many examples that can run independently of higher-level components.

Installation

The easiest way to get started with the library is via the pip package.

Note that the library requires Python 3.7 and Tensorflow >= 2.7.

First, please install the most recent version of TensorFlow by following the TensorFlow installation instructions. For example, you could install TensorFlow

pip3 install --upgrade tensorflow

Then run

pip3 install --upgrade tf-quant-finance

You maybe also have to use the option --user.

TensorFlow training

If you are not familiar with TensorFlow, an excellent place to get started is with the following self-study introduction to TensorFlow notebooks:

Development roadmap

We are working on expanding the coverage of the library. Areas under active development are:

  • Ito Processes: Framework for defining Ito processes. Includes methods for sampling paths from a process and for solving the associated backward Kolmogorov equation.
  • Implementation of the following specific processes/models:
    • Brownian Motion
    • Geometric Brownian Motion
    • Ornstein-Uhlenbeck
    • One-Factor Hull-White model
    • Heston model
    • Local volatility model.
    • Quadratic Local Vol model.
    • SABR model
  • Copulas: Support for defining and sampling from copulas.
  • Model Calibration:
    • Dupire local vol calibration.
    • SABR model calibration.
  • Rate curve fitting: Hagan-West algorithm for yield curve bootstrapping and the Monotone Convex interpolation scheme.
  • Support for dates, day-count conventions, holidays, etc.

Examples

See tf_quant_finance/examples/ for end-to-end examples. It includes tutorial notebooks such as:

The above links will open Jupyter Notebooks in Colab.

Contributing

We're eager to collaborate with you! See CONTRIBUTING.md for a guide on how to contribute. This project adheres to TensorFlow's code of conduct. By participating, you are expected to uphold this code.

Development

This section is for developers who want to contribute code to the library. If you are only interested in using the library, please follow the instructions in the Installation section.

Development dependencies

This library has the following dependencies:

  1. Bazel
  2. Python 3 (Bazel uses Python 3 by default)
  3. TensorFlow version >= 2.7
  4. TensorFlow Probability version between v0.11.0 and v0.12.1
  5. Numpy version 1.21 or higher
  6. Attrs
  7. Dataclasses (not needed if your Python version >= 3.7)

This library requires the Bazel build system. Please follow the Bazel installation instructions for your platform.

You can install TensorFlow and related dependencies using the pip3 install command:

pip3 install --upgrade tf-nightly tensorflow-probability==0.12.1 numpy==1.21 attrs dataclasses

Commonly used commands

Clone the GitHub repository:

git clone https://github.com/google/tf-quant-finance.git

After you run

cd tf_quant_finance

you can execute tests using the bazel test command. For example,

bazel test tf_quant_finance/math/random_ops/sobol:sobol_test

will run tests in sobol_test.py .

Tests run using Python version 3. Please make sure that you can run import tensorflow in the Python 3 shell. Otherwise, tests might fail.

Building a custom pip package

The following commands will build custom pip package from source and install it:

# sudo apt-get install bazel git python python-pip rsync # For Ubuntu.
git clone https://github.com/google/tf-quant-finance.git
cd tf-quant-finance
bazel build :build_pip_pkg
./bazel-bin/build_pip_pkg artifacts
pip install --user --upgrade artifacts/*.whl

Community

  1. GitHub repository: Report bugs or make feature requests.

  2. TensorFlow Blog: Stay up to date on content from the TensorFlow team and best articles from the community.

  3. [email protected]: Open mailing list for discussion and questions of this library.

  4. TensorFlow Probability: This library will leverage methods from TensorFlow Probability (TFP).

Disclaimers

Google does not officially support this product. This library is under active development, and interfaces may change at any time.

License

This library is licensed under the Apache 2 license (see LICENSE). This library uses Sobol primitive polynomials and initial direction numbers which are licensed under the BSD license.

tf-quant-finance's People

Contributors

alembcke avatar allafterall avatar amitvarshney00 avatar clairecharron avatar clee-yt avatar devarakondav avatar esztermarton avatar fabrice-deschatres avatar fedimser avatar gavincyi avatar hawkinsp avatar jackgillett101 avatar kykosic avatar matejr avatar mcharsley avatar nkjaipuria avatar perezju avatar pshmakov avatar rajflume avatar rickeylev avatar saxena-ashish-g avatar sharnett avatar slowy07 avatar tf-quant-finance-robot avatar tianseng avatar wiesnervos avatar yilei avatar yl7890 avatar yves-gaeremynck avatar zhiqingxiao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tf-quant-finance's Issues

IRS Delta

In
https://github.com/google/tf-quant-finance/tree/master/tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/interest_rate_swap/interest_rate_swap_impl.py

under def ir_delta it says
raise NotImplementedError("Coming soon.")

In ir_delta_parallel_leg, I see that:
if shock_size is None:
bump = tf.constant(0, dtype=self._dtype,
name="bump")
return tff_math.fwd_gradient(price_fn, bump)

So when no shocks are supplied - its just fwd_gradient. Isn't that the AAD equiv of the bump and reval change in PV?

But when a shock size is supplied, you bump the base curve (as a parallel bump) and then:
price_no_bump = leg.price(processed_market_data)
price_with_bump = price_fn(shock_size)
delta = (price_with_bump - price_no_bump) / shock_size
return delta

So in effect, ir_delta_parallel has the potential to supply both delta's? (AAD equiv and parallel shocked

BS vol and greeks

I was wondering if there's an example implementation of BS implied vol estimation for American options and greeks. This tends to be the more commonly needed example than pricing, since the immediate need is to generate vol surfaces or ivol and use in further modelling. Wondering if this is supported, I couldn't see any examples in the American pricing notebook. Thanks!

American options greeks with PDE is slow

I haven't found an example of how to properly calculate the greeks with the PDE pricer or the MC pricer.
Here is my attempt : https://colab.research.google.com/github/arthurpham/google_colab/blob/1f737238f1ba71c8c84c47bb24f55e3a97688d1f/AmericanOption_PDE_Greeks_TQF.ipynb
I checked that the greeks with PDE was close to the BS greeks (BS closed form formula and AD).
But the performance of the greeks with PDE was very low, i'm not sure why.
Also i get memory exhaustion on my Google Colab when i try to run a batch larger than 10 options.

What am i missing ?
Thank you

TQF GPU 10 options
wall time: 26.640211820602417
options per second: 0.3753723907054831

Negative price for barrier option

Hello,
the following setup returns negative prices for european barrier calls:

import tf_quant_finance as tff
import numpy as np

n_points=10
spots = np.linspace(0.01, 0.2, n_points)
strikes = 1.9 * np.ones(n_points)
volatilities = 0.25 * np.ones(n_points)
expiries = 0.5 * np.ones(n_points)
barriers = 0.5 * np.ones(n_points)
is_barrier_down = np.array([True] * n_points)
is_knock_out = np.array([True] * n_points)
is_call_options = np.array([True] * n_points)

args = {
    "volatilities" : volatilities,
    "strikes" : strikes,
    "expiries" : expiries,
    "spots" : spots,
    "barriers" : barriers,
    "is_barrier_down" : is_barrier_down,
    "is_knock_out" : is_knock_out,
    "is_call_options" : is_call_options,
}

    
price = tff.black_scholes.barrier_price(
        **args
    )

>> price
>> <tf.Tensor: shape=(10,), dtype=float64, numpy=
array([-4.62000000e-01, -3.81777778e-01, -3.01555556e-01, -2.21341484e-01,
       -1.41989785e-01, -7.20212532e-02, -2.70513904e-02, -7.63614881e-03,
       -1.71392373e-03, -3.24709866e-04])>

The parameters are obviously contrived, but i wonder whether this is expected behavior in such tails due to numerical instabilities.

HestonModel.sample_paths returns variance converging to zero

I generated sample paths of HestonModel with parameters shown in the documentation.

However, variance eventually converges to zero and accordingly spot prices asymptotic to constant.
I attach the plot and a snippet to reproduce it.

Is this an expected behaviour?
I appreciate it if you could take a look at it.

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tf_quant_finance as tff
from tf_quant_finance.math import random
from tf_quant_finance.math.piecewise import PiecewiseConstantFunc

tf.random.set_seed(42)

epsilon = PiecewiseConstantFunc(jump_locations=[0.5], values=[1, 1.1], dtype=np.float64)
process = tff.models.HestonModel(
    kappa=0.5, theta=0.04, epsilon=epsilon, rho=0.1, dtype=np.float64
)
times = np.linspace(0.0, 1.0, 1000)
num_samples = 10  # number of trajectories
sample_paths = process.sample_paths(
    times,
    time_step=0.01,
    num_samples=num_samples,
    initial_state=np.array([1.0, 0.04]),
    random_type=random.RandomType.SOBOL,
)

s = np.array(sample_paths[..., 0]).T
v = np.array(sample_paths[..., 1]).T

plt.figure(figsize=(24, 6))
plt.plot(s)
plt.title("spot")
plt.show()

plt.figure(figsize=(24, 6))
plt.plot(v)
plt.title("variance")
plt.show()
$ pip show tf-quant-finance
Name: tf-quant-finance
Version: 0.0.1.dev24
Summary: High-performance TensorFlow library for quantitative finance.
Home-page: https://github.com/google/tf-quant-finance
Author: Google Inc.
Author-email: [email protected]
License: Apache 2.0
Location: /usr/local/lib/python3.8/site-packages
Requires: numpy, protobuf, tensorflow-probability, attrs
Required-by: 

s
v

Which precision should I use? float32 or float64

Hi tff team,

Thank you so much for developing this project. My question may be vague. Which precision should I use when doing derivative pricing? Is there any industry standards? Is float32 enough for most cases? Or it depends case by case?

Other quant libraries on CPU, for example QuantLib and QuantLib.jl, they use float64 for almost all scenarios (analytically method, Monte-Carlo or PDE). CPUs usually have float64 support.

I find TFF usually uses tf.float64 when choosing dtype. TFF can run on accelerators: GPUs or TPUs. NVIDIA GPUs have float64 CUDA cores and are capable of handing float64. However, TPUs may not have float64 support. But I find a paper from Google about doing Monte-Carlo on TPUs. They say in most cases, TPUs can do Monte-Carlo. On the hardware side, lower precision usually means faster computing speed. Other academic papers do some experiments on mix-precision.

Is there a simple or quick guide on precision? Like:

  • float32 is enough for most Monte-Carlo cases and black-sholes analytically method?
  • float64 is required for PDE?

If precision is depended by cases. How to measure the precision is enough for my case?

Thanks!

Issue with running Bazel tests

I did try run from tf_quant_finance directory as well, am I missing something here, surely seems like a path/ pythonpath issue.
Did see in bazel that they remove the sys.path[0], not sure if that's the reason. https://github.com/bazelbuild/bazel/blob/master/tools/python/python_bootstrap_template.txt#L19

Tried to add it to the PYTHONPATH variable as well, but didn't have any luck.

C:\GitRepos\tf-quant-finance (master -> origin)
(tqf) ฮป bazel test //tf_quant_finance/math/random_ops/sobol:sobol_test
INFO: Analyzed target //tf_quant_finance/math/random_ops/sobol:sobol_test (1 packages loaded, 2 targets configured).
INFO: Found 1 test target...
FAIL: //tf_quant_finance/math/random_ops/sobol:sobol_test (see C:/users/ch/_bazel_ch/ssh2zpbu/execroot/tf_quant_finance/bazel-out/x64_windows-fastbuild/testlogs/tf_quant_finance/math/random_ops/sobol/sobol_test/test.log)
Target //tf_quant_finance/math/random_ops/sobol:sobol_test up-to-date:
  bazel-bin/tf_quant_finance/math/random_ops/sobol/sobol_test.exe
  bazel-bin/tf_quant_finance/math/random_ops/sobol/sobol_test.zip
INFO: Elapsed time: 7.009s, Critical Path: 6.66s
INFO: 2 processes: 2 local.
INFO: Build completed, 1 test FAILED, 2 total actions
//tf_quant_finance/math/random_ops/sobol:sobol_test                      FAILED in 6.6s
  C:/users/ch/_bazel_ch/ssh2zpbu/execroot/tf_quant_finance/bazel-out/x64_windows-fastbuild/testlogs/tf_quant_finance/math/random_ops/sobol/sobol_test/test.log

Executed 1 out of 1 test: 1 fails locally.

Contains of the log file

-----------------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\ch\AppData\Local\Temp\Bazel.runfiles_ue9zden8\runfiles\tf_quant_finance\tf_quant_finance\math\random_ops\sobol\sobol_test.py", line 22, in <module>
    from tf_quant_finance.math import random
ModuleNotFoundError: No module named 'tf_quant_finance.math'

Asian Option

Hi team,
Is there any plan for the implementation of asian option computation? I would like to contribute if there is anything related in you plan.

I can also contribute to other issues if you have one.

Xiaozhi

Discrete dividens for american options

My goal is to compute american option prices with discrete dividends on a specific date. The example provided for American options does not indicate how could this be done.

# Define the coordinate grid
  s_min = 0.01
  s_max = 300.
  grid = pde.grids.uniform_grid(minimums=[s_min],
                                maximums=[s_max],
                                sizes=[number_grid_points],
                                dtype=dtype)

  # Define the values grid for the final condition
  s = grid[0]
  final_values_grid = tf.nn.relu(s - strike)

  # Define the PDE coefficient functions
  def second_order_coeff_fn(t, grid):
    del t
    s = grid[0]
    return [[volatility ** 2 * s ** 2 / 2]]

  def first_order_coeff_fn(t, grid):
    del t
    s = grid[0]
    return [risk_free_rate * s]

  def zeroth_order_coeff_fn(t, grid):
    del t, grid
    return -risk_free_rate

  # Define the boundary conditions
  @pde.boundary_conditions.dirichlet
  def lower_boundary_fn(t, grid):
    del t, grid
    return tf.constant(0.0, dtype=dtype)

  @pde.boundary_conditions.dirichlet
  def upper_boundary_fn(t, grid):
    del grid
    return tf.squeeze(s_max - strike * tf.exp(-risk_free_rate * (expiry - t)))

  # In order to price American option one needs to set option values to 
  # V(x) := max(V(x), max(x - strike, 0)) after each iteration
  def values_transform_fn(t, grid, values):
    del t
    s = grid[0]
    values_floor = tf.nn.relu(s - strike)
    return grid, tf.maximum(values, values_floor)

Given that discrete options happen at a specific date I thought it would be possible to change the value of spot (s) by the respective dividend after the ex_date occurs. Lets say that expiry = 0.8 and for example ex_date = 0.5, with a dividend of 1.5%, then the code would become:

# Define the coordinate grid
  s_min = 0.01
  s_max = 300.
  grid = pde.grids.uniform_grid(minimums=[s_min],
                                maximums=[s_max],
                                sizes=[number_grid_points],
                                dtype=dtype)

  # Define the values grid for the final condition
  s = grid[0]
  final_values_grid = tf.nn.relu(s - strike)

  # Define the PDE coefficient functions
  def second_order_coeff_fn(t, grid):
    s = grid[0]
    if t.numpy() > 0.5:
        s = s*(1 - 0.015)
    del t
    return [[volatility ** 2 * s ** 2 / 2]]

  def first_order_coeff_fn(t, grid):
    s = grid[0]
    if t.numpy() > 0.5:
        s = s*(1 - 0.015)
    del t
    return [risk_free_rate * s]

  def zeroth_order_coeff_fn(t, grid):
    del t, grid
    return -risk_free_rate

  # Define the boundary conditions
  @pde.boundary_conditions.dirichlet
  def lower_boundary_fn(t, grid):
    del t, grid
    return tf.constant(0.0, dtype=dtype)

  @pde.boundary_conditions.dirichlet
  def upper_boundary_fn(t, grid):
    del grid
    return tf.squeeze(s_max - strike * tf.exp(-risk_free_rate * (expiry - t)))

  # In order to price American option one needs to set option values to 
  # V(x) := max(V(x), max(x - strike, 0)) after each iteration
  def values_transform_fn(t, grid, values):
    s = grid[0]
    if t.numpy() > 0.5:
        s = s*(1 - 0.015)
    del t
    values_floor = tf.nn.relu(s - strike)
    return grid, tf.maximum(values, values_floor)

Unfortunately, this approach does not yield proper results when compared with Quantlib. Does the tff library allow for the computation of option prices using discrete dividends? Ideally the only thing that it is required is to shift all spot prices based on the dividend starting at ex date.

Thank you in advance

Hull White Model - calibration not aligning to input prices

I'm observing an issue when trying to calibrate the hull white model using calibration_from_swaptions function. Specifically, when I try to recalculate the prices using the calibrated parameters, I do not return to my source prices. I've included a demo of the issue below:

import numpy as np
import tensorflow as tf
import tf_quant_finance as tff

notional = 100.
prices = np.array([28.54, 27.63, 26.82, 25.76, 24.26])
expiries = np.array([10, 10, 10, 10, 15])
zero_rate_fn = lambda x: 0.01 * tf.ones_like(x, dtype=tf.float64)
start_times = np.array([
    [10. , 10.5, 11. , 11. , 11. , 11. , 11. , 11. , 11. , 11. ],
    [10. , 10.5, 11. , 11.5, 12. , 12. , 12. , 12. , 12. , 12. ],
    [10. , 10.5, 11. , 11.5, 12. , 12.5, 13. , 13. , 13. , 13. ],
    [10. , 10.5, 11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5],
    [15. , 15.5, 16. , 16. , 16. , 16. , 16. , 16. , 16. , 16. ]])

end_times = np.array([
    [10.5, 11. , 11. , 11. , 11. , 11. , 11. , 11. , 11. , 11. ],
    [10.5, 11. , 11.5, 12. , 12. , 12. , 12. , 12. , 12. , 12. ],
    [10.5, 11. , 11.5, 12. , 12.5, 13. , 13. , 13. , 13. , 13. ],
    [10.5, 11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5, 15. ],
    [15.5, 16. , 16. , 16. , 16. , 16. , 16. , 16. , 16. , 16. ]])

coupons = np.array([
    [0.03057629, 0.03057629, 0.        , 0.        , 0.        ,
    0.        , 0.        , 0.        , 0.        , 0.        ],
    [0.030797  , 0.030797  , 0.030797  , 0.030797  , 0.        ,
     0.        , 0.        , 0.        , 0.        , 0.        ],
    [0.03072953, 0.03072953, 0.03072953, 0.03072953, 0.03072953,
    0.03072953, 0.        , 0.        , 0.        , 0.        ],
    [0.03086061, 0.03086061, 0.03086061, 0.03086061, 0.03086061,
    0.03086061, 0.03086061, 0.03086061, 0.03086061, 0.03086061],
    [0.02808885, 0.02808885, 0.        , 0.        , 0.        ,
    0.        , 0.        , 0.        , 0.        , 0.        ]])
 
init_mr_guess = [0.05]
init_vol_guess = [0.05]

calibrated_params, converged, _ = tff.models.hull_white.calibration_from_swaptions(
    prices=prices,
    expiries=expiries,
    floating_leg_start_times=start_times,
    floating_leg_end_times=end_times,
    fixed_leg_payment_times=end_times,
    floating_leg_daycount_fractions=end_times - start_times,
    fixed_leg_daycount_fractions=end_times - start_times,
    fixed_leg_coupon=coupons,
    reference_rate_fn=zero_rate_fn,
    mean_reversion=init_mr_guess,
    volatility=init_vol_guess,
    maximum_iterations=50,
    notional=notional,
    use_analytic_pricing=True,
    dtype=tf.float64,
)

print("Calibrated params")
print("Vol:", calibrated_params.volatility.values())
print("Mean reversion:", calibrated_params.mean_reversion.values())
print("Is converged:", converged)
print("")`

recalced_prices = tff.models.hull_white.swaption_price(
    expiries=expiries,
    floating_leg_start_times=start_times,
    floating_leg_end_times=end_times,
    fixed_leg_payment_times=end_times,
    floating_leg_daycount_fractions=end_times-start_times,
    fixed_leg_daycount_fractions=end_times-start_times,
    fixed_leg_coupon=coupons,
    reference_rate_fn=zero_rate_fn,
    notional=notional,
    mean_reversion=calibrated_params.mean_reversion,
    volatility=calibrated_params.volatility,
    dtype=tf.float64,
)

print("Source prices: ", prices)
print("Recalculated prices: ", recalced_prices.numpy())

Output I'm seeing:
Source prices: [28.54, 27.63, 26.82, 25.76, 24.26]
Recalculated prices: [10.43644126, 20.46670051, 29.87954086, 46.01337643, 12.38118779]

Thanks in advance!

Numpy version mismatch in the first try

Hi
I have successfully installed tensorflow and tf-quant-finance from source, however, when I want to run an example, I get an error about version mismatch of numpy.

$ python3 American_Option_Black_Scholes.py
2021-04-02 08:52:17.384836: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0
RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd
Traceback (most recent call last):
  File "American_Option_Black_Scholes.py", line 8, in <module>
    import tensorflow as tf
  File "/home/mnaderan/.local/lib/python3.8/site-packages/tensorflow/__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "/home/mnaderan/.local/lib/python3.8/site-packages/tensorflow/python/__init__.py", line 40, in <module>
    from tensorflow.python.eager import context
  File "/home/mnaderan/.local/lib/python3.8/site-packages/tensorflow/python/eager/context.py", line 37, in <module>
    from tensorflow.python.client import pywrap_tf_session
  File "/home/mnaderan/.local/lib/python3.8/site-packages/tensorflow/python/client/pywrap_tf_session.py", line 23, in <module>
    from tensorflow.python._pywrap_tf_session import *
ImportError: SystemError: <built-in method __contains__ of dict object at 0x7f4c43c1d600> returned a result with an error set

The versions are shown below

$ pip3 list | grep numpy
numpy                   1.19.5
$ pip3 list | grep tensor
tensorboard             2.4.1
tensorboard-plugin-wit  1.8.0
tensorflow              2.6.0
tensorflow-estimator    2.4.0
tensorflow-probability  0.12.1
$ pip3 list | grep quant
tf-quant-finance        0.0.1.dev25

How can I fix that?

MonteCarlo Simulation

Team, is there a plan to implement MonteCarlo simulation? I can contribute to one if it is in the works or contribute to any other higher priority items on your list.

Krishna

Euler Sample Path does not work under TensorFlow 2.0 with Higher Dimension

When we specify the SDE with dimension greater than one and simulate under Euler Scheme, we will have the following errors.

~/anaconda/envs/py36dev/lib/python3.6/site-packages/tf_quant_finance/models/ito_process.py in step_fn(i, written_count, current_state, result)
332 dw = random.mv_normal_sample(
333 (num_samples,), mean=wiener_mean, random_type=random_type,
--> 334 seed=seed)
335 dw = dw * sqrt_dt[i]
336 dt_inc = dt[i] * self.drift_fn()(current_time, current_state) # pylint: disable=not-callable

~/anaconda/envs/py36dev/lib/python3.6/site-packages/tf_quant_finance/math/random_ops/multivariate_normal.py in multivariate_normal(sample_shape, mean, covariance_matrix, scale_matrix, random_type, validate_args, seed, dtype, name, **kwargs)
170 name,
171 default_name='multivariate_normal',
--> 172 values=[sample_shape, mean, covariance_matrix, scale_matrix]):
173 if mean is not None:
174 mean = tf.convert_to_tensor(mean, dtype=dtype, name='mean')

TypeError: init() got an unexpected keyword argument 'default_name'

I'm using Tensorflow 2.0

Month.md and month.md collide on case-insensitive filesystem

Hi,

I have just cloned this project and find that Month.md and month.md in api_docs/tf_quant_finance/datetime/ collide on my macOS. I could not pull recent merges. The best solution is to reformat my local APFS filesystem. But I think reformatting filesystem seems not a good choice. I guess api_docs may be generated automatically. However, it would be nice if the api and the markdown file could change to another name. And it would benefit other developers who want to clone the project into their macOS filesystem.

Thanks!

new pip package

Hello,
The lastest pip package was publish on the 13th of April.
Is there any plan to publish a new version of the lib?

build fails

[jw@cn06 tf-quant-finance]$ ./bazel-bin/build_pip_pkg artifacts
++ uname -s
++ tr A-Z a-z

  • PLATFORM=linux
  • PIP_FILE_PREFIX=bazel-bin/build_pip_pkg.runfiles/tf_quant_finance/
  • main artifacts
  • SETUP_FLAGS=--universal
  • [[ ! -z artifacts ]]
  • [[ artifacts == \m\a\k\e ]]
  • [[ artifacts == --\n\i\g\h\t\l\y ]]
  • DEST=artifacts
  • shift
  • [[ ! -z '' ]]
  • [[ -z artifacts ]]
  • mkdir -p artifacts
    ++ readlink -f artifacts
  • DEST=/data/jw/tf-quant-finance/artifacts
  • echo '=== destination directory: /data/jw/tf-quant-finance/artifacts'
    === destination directory: /data/jw/tf-quant-finance/artifacts
    ++ mktemp -d -t tmp.XXXXXXXXXX
  • TMPDIR=/tmp/tmp.IiaeTXyhb0
    ++ date
  • echo Fri Mar 5 17:07:50 CET 2021 : '=== Using tmpdir: /tmp/tmp.IiaeTXyhb0'
    Fri Mar 5 17:07:50 CET 2021 : === Using tmpdir: /tmp/tmp.IiaeTXyhb0
  • echo '=== Copy TF Quant Finance files'
    === Copy TF Quant Finance files
  • cp bazel-bin/build_pip_pkg.runfiles/tf_quant_finance/setup.py /tmp/tmp.IiaeTXyhb0
  • cp bazel-bin/build_pip_pkg.runfiles/tf_quant_finance/MANIFEST.in /tmp/tmp.IiaeTXyhb0
  • cp bazel-bin/build_pip_pkg.runfiles/tf_quant_finance/LICENSE /tmp/tmp.IiaeTXyhb0
  • cp bazel-bin/build_pip_pkg.runfiles/tf_quant_finance/README.md /tmp/tmp.IiaeTXyhb0
  • rsync -avm -L '--exclude=*_test.py' bazel-bin/build_pip_pkg.runfiles/tf_quant_finance/tf_quant_finance /tmp/tmp.IiaeTXyhb0
    building file list ... done
    tf_quant_finance/
    tf_quant_finance/init.py
    tf_quant_finance/black_scholes/
    tf_quant_finance/black_scholes/init.py
    tf_quant_finance/black_scholes/brownian_bridge.py
    tf_quant_finance/black_scholes/crr_binomial_tree.py
    tf_quant_finance/black_scholes/implied_vol_approximation.py
    tf_quant_finance/black_scholes/implied_vol_lib.py
    tf_quant_finance/black_scholes/implied_vol_newton_root.py
    tf_quant_finance/black_scholes/implied_vol_utils.py
    tf_quant_finance/black_scholes/vanilla_prices.py
    tf_quant_finance/black_scholes/approximations/
    tf_quant_finance/black_scholes/approximations/init.py
    tf_quant_finance/black_scholes/approximations/american_option.py
    tf_quant_finance/datetime/
    tf_quant_finance/datetime/init.py
    tf_quant_finance/datetime/bounded_holiday_calendar.py
    tf_quant_finance/datetime/constants.py
    tf_quant_finance/datetime/date_tensor.py
    tf_quant_finance/datetime/date_utils.py
    tf_quant_finance/datetime/daycounts.py
    tf_quant_finance/datetime/holiday_calendar.py
    tf_quant_finance/datetime/holiday_calendar_factory.py
    tf_quant_finance/datetime/holiday_utils.py
    tf_quant_finance/datetime/periods.py
    tf_quant_finance/datetime/schedules.py
    tf_quant_finance/datetime/tensor_wrapper.py
    tf_quant_finance/datetime/unbounded_holiday_calendar.py
    tf_quant_finance/experimental/
    tf_quant_finance/experimental/init.py
    tf_quant_finance/experimental/io.py
    tf_quant_finance/experimental/finite_difference/
    tf_quant_finance/experimental/finite_difference/init.py
    tf_quant_finance/experimental/finite_difference/methods.py
    tf_quant_finance/experimental/instruments/
    tf_quant_finance/experimental/instruments/init.py
    tf_quant_finance/experimental/instruments/bond.py
    tf_quant_finance/experimental/instruments/cap_floor.py
    tf_quant_finance/experimental/instruments/cashflow_stream.py
    tf_quant_finance/experimental/instruments/cms_swap.py
    tf_quant_finance/experimental/instruments/eurodollar_futures.py
    tf_quant_finance/experimental/instruments/floating_rate_note.py
    tf_quant_finance/experimental/instruments/forward_rate_agreement.py
    tf_quant_finance/experimental/instruments/interest_rate_swap.py
    tf_quant_finance/experimental/instruments/overnight_index_linked_futures.py
    tf_quant_finance/experimental/instruments/rate_curve.py
    tf_quant_finance/experimental/instruments/rates_common.py
    tf_quant_finance/experimental/instruments/swaption.py
    tf_quant_finance/experimental/local_stochastic_volatility/
    tf_quant_finance/experimental/local_stochastic_volatility/init.py
    tf_quant_finance/experimental/local_stochastic_volatility/local_stochastic_volatility_model.py
    tf_quant_finance/experimental/local_stochastic_volatility/lsv_variance_model.py
    tf_quant_finance/experimental/local_volatility/
    tf_quant_finance/experimental/local_volatility/init.py
    tf_quant_finance/experimental/local_volatility/local_volatility_model.py
    tf_quant_finance/experimental/lsm_algorithm/
    tf_quant_finance/experimental/lsm_algorithm/init.py
    tf_quant_finance/experimental/lsm_algorithm/lsm.py
    tf_quant_finance/experimental/lsm_algorithm/lsm_v2.py
    tf_quant_finance/experimental/lsm_algorithm/payoff.py
    tf_quant_finance/experimental/pricing_platform/
    tf_quant_finance/experimental/pricing_platform/init.py
    tf_quant_finance/experimental/pricing_platform/framework/
    tf_quant_finance/experimental/pricing_platform/framework/init.py
    tf_quant_finance/experimental/pricing_platform/framework/utils.py
    tf_quant_finance/experimental/pricing_platform/framework/core/
    tf_quant_finance/experimental/pricing_platform/framework/core/init.py
    tf_quant_finance/experimental/pricing_platform/framework/core/business_days.py
    tf_quant_finance/experimental/pricing_platform/framework/core/currencies.py
    tf_quant_finance/experimental/pricing_platform/framework/core/curve_types.py
    tf_quant_finance/experimental/pricing_platform/framework/core/daycount_conventions.py
    tf_quant_finance/experimental/pricing_platform/framework/core/implied_volatility_type.py
    tf_quant_finance/experimental/pricing_platform/framework/core/instrument.py
    tf_quant_finance/experimental/pricing_platform/framework/core/interpolation_method.py
    tf_quant_finance/experimental/pricing_platform/framework/core/models.py
    tf_quant_finance/experimental/pricing_platform/framework/core/processed_market_data.py
    tf_quant_finance/experimental/pricing_platform/framework/core/rate_indices.py
    tf_quant_finance/experimental/pricing_platform/framework/core/types.py
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/init.py
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/utils.py
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/american_option/
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/american_option/init.py
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/american_option/american_option_impl.py
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/american_option/proto_utils.py
    tf_quant_finance/experimental/pricing_platform/framework/equity_instruments/american_option/utils.py
    tf_quant_finance/experimental/pricing_platform/framework/market_data/
    tf_quant_finance/experimental/pricing_platform/framework/market_data/init.py
    tf_quant_finance/experimental/pricing_platform/framework/market_data/market_data_config.py
    tf_quant_finance/experimental/pricing_platform/framework/market_data/market_data_impl.py
    tf_quant_finance/experimental/pricing_platform/framework/market_data/rate_curve.py
    tf_quant_finance/experimental/pricing_platform/framework/market_data/utils.py
    tf_quant_finance/experimental/pricing_platform/framework/market_data/volatility_surface.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/init.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/cashflow_streams.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/coupon_specs.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/utils.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/forward_rate_agreement/
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/forward_rate_agreement/init.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/forward_rate_agreement/forward_rate_agreement_impl.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/forward_rate_agreement/proto_utils.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/interest_rate_swap/
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/interest_rate_swap/init.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/interest_rate_swap/interest_rate_swap_impl.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/interest_rate_swap/proto_utils.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/swaption/
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/swaption/init.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/swaption/proto_utils.py
    tf_quant_finance/experimental/pricing_platform/framework/rate_instruments/swaption/swaption_impl.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/
    tf_quant_finance/experimental/pricing_platform/instrument_protos/init.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/all_instruments_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/american_equity_option_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/business_days_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/currencies_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/date_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/daycount_conventions_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/decimal_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/forward_rate_agreement_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/interest_rate_swap_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/metadata_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/period_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/rate_indices_pb2.py
    tf_quant_finance/experimental/pricing_platform/instrument_protos/swaption_pb2.py
    tf_quant_finance/math/
    tf_quant_finance/math/init.py
    tf_quant_finance/math/custom_loops.py
    tf_quant_finance/math/diff_ops.py
    tf_quant_finance/math/gradient.py
    tf_quant_finance/math/jacobian.py
    tf_quant_finance/math/pad.py
    tf_quant_finance/math/piecewise.py
    tf_quant_finance/math/segment_ops.py
    tf_quant_finance/math/integration/
    tf_quant_finance/math/integration/init.py
    tf_quant_finance/math/integration/integrate.py
    tf_quant_finance/math/integration/simpson.py
    tf_quant_finance/math/interpolation/
    tf_quant_finance/math/interpolation/init.py
    tf_quant_finance/math/interpolation/utils.py
    tf_quant_finance/math/interpolation/cubic/
    tf_quant_finance/math/interpolation/cubic/init.py
    tf_quant_finance/math/interpolation/cubic/cubic_interpolation.py
    tf_quant_finance/math/interpolation/interpolation_2d/
    tf_quant_finance/math/interpolation/interpolation_2d/init.py
    tf_quant_finance/math/interpolation/interpolation_2d/interpolation_2d.py
    tf_quant_finance/math/interpolation/linear/
    tf_quant_finance/math/interpolation/linear/init.py
    tf_quant_finance/math/interpolation/linear/linear_interpolation.py
    tf_quant_finance/math/optimizer/
    tf_quant_finance/math/optimizer/init.py
    tf_quant_finance/math/optimizer/conjugate_gradient.py
    tf_quant_finance/math/pde/
    tf_quant_finance/math/pde/init.py
    tf_quant_finance/math/pde/boundary_conditions.py
    tf_quant_finance/math/pde/fd_solvers.py
    tf_quant_finance/math/pde/grids.py
    tf_quant_finance/math/pde/steppers/
    tf_quant_finance/math/pde/steppers/init.py
    tf_quant_finance/math/pde/steppers/composite_stepper.py
    tf_quant_finance/math/pde/steppers/crank_nicolson.py
    tf_quant_finance/math/pde/steppers/douglas_adi.py
    tf_quant_finance/math/pde/steppers/explicit.py
    tf_quant_finance/math/pde/steppers/extrapolation.py
    tf_quant_finance/math/pde/steppers/implicit.py
    tf_quant_finance/math/pde/steppers/multidim_parabolic_equation_stepper.py
    tf_quant_finance/math/pde/steppers/oscillation_damped_crank_nicolson.py
    tf_quant_finance/math/pde/steppers/parabolic_equation_stepper.py
    tf_quant_finance/math/pde/steppers/weighted_implicit_explicit.py
    tf_quant_finance/math/random_ops/
    tf_quant_finance/math/random_ops/init.py
    tf_quant_finance/math/random_ops/multivariate_normal.py
    tf_quant_finance/math/random_ops/stateless.py
    tf_quant_finance/math/random_ops/uniform.py
    tf_quant_finance/math/random_ops/halton/
    tf_quant_finance/math/random_ops/halton/init.py
    tf_quant_finance/math/random_ops/halton/halton_impl.py
    tf_quant_finance/math/random_ops/sobol/
    tf_quant_finance/math/random_ops/sobol/init.py
    tf_quant_finance/math/random_ops/sobol/sobol_impl.py
    tf_quant_finance/math/root_search/
    tf_quant_finance/math/root_search/init.py
    tf_quant_finance/math/root_search/brent.py
    tf_quant_finance/math/root_search/newton.py
    tf_quant_finance/math/root_search/utils.py
    tf_quant_finance/models/
    tf_quant_finance/models/init.py
    tf_quant_finance/models/euler_sampling.py
    tf_quant_finance/models/generic_ito_process.py
    tf_quant_finance/models/ito_process.py
    tf_quant_finance/models/joined_ito_process.py
    tf_quant_finance/models/milstein_sampling.py
    tf_quant_finance/models/utils.py
    tf_quant_finance/models/geometric_brownian_motion/
    tf_quant_finance/models/geometric_brownian_motion/init.py
    tf_quant_finance/models/geometric_brownian_motion/multivariate_geometric_brownian_motion.py
    tf_quant_finance/models/geometric_brownian_motion/univariate_geometric_brownian_motion.py
    tf_quant_finance/models/heston/
    tf_quant_finance/models/heston/init.py
    tf_quant_finance/models/heston/heston_model.py
    tf_quant_finance/models/heston/approximations/
    tf_quant_finance/models/heston/approximations/init.py
    tf_quant_finance/models/heston/approximations/european_option.py
    tf_quant_finance/models/hjm/
    tf_quant_finance/models/hjm/init.py
    tf_quant_finance/models/hjm/cap_floor.py
    tf_quant_finance/models/hjm/quasi_gaussian_hjm.py
    tf_quant_finance/models/hjm/swaption_pricing.py
    tf_quant_finance/models/hjm/swaption_util.py
    tf_quant_finance/models/hjm/zero_coupon_bond_option.py
    tf_quant_finance/models/hjm/zero_coupon_bond_option_util.py
    tf_quant_finance/models/hull_white/
    tf_quant_finance/models/hull_white/init.py
    tf_quant_finance/models/hull_white/calibration.py
    tf_quant_finance/models/hull_white/cap_floor.py
    tf_quant_finance/models/hull_white/one_factor.py
    tf_quant_finance/models/hull_white/swaption.py
    tf_quant_finance/models/hull_white/vector_hull_white.py
    tf_quant_finance/models/hull_white/zero_coupon_bond_option.py
    tf_quant_finance/models/sabr/
    tf_quant_finance/models/sabr/init.py
    tf_quant_finance/models/sabr/sabr_model.py
    tf_quant_finance/rates/
    tf_quant_finance/rates/init.py
    tf_quant_finance/rates/cashflows.py
    tf_quant_finance/rates/forwards.py
    tf_quant_finance/rates/swap_curve_bootstrap.py
    tf_quant_finance/rates/swap_curve_common.py
    tf_quant_finance/rates/swap_curve_fit.py
    tf_quant_finance/rates/analytics/
    tf_quant_finance/rates/analytics/init.py
    tf_quant_finance/rates/analytics/cashflows.py
    tf_quant_finance/rates/analytics/forwards.py
    tf_quant_finance/rates/analytics/swap.py
    tf_quant_finance/rates/constant_fwd/
    tf_quant_finance/rates/constant_fwd/init.py
    tf_quant_finance/rates/constant_fwd/constant_fwd_interpolation.py
    tf_quant_finance/rates/hagan_west/
    tf_quant_finance/rates/hagan_west/init.py
    tf_quant_finance/rates/hagan_west/bond_curve.py
    tf_quant_finance/rates/hagan_west/monotone_convex.py
    tf_quant_finance/utils/
    tf_quant_finance/utils/init.py
    tf_quant_finance/utils/tf_functions.py

sent 1,990,664 bytes received 3,939 bytes 3,989,206.00 bytes/sec
total size is 1,974,560 speedup is 0.99

  • rsync -avm -L '--exclude=*_test.py' bazel-bin/build_pip_pkg.runfiles/tf_quant_finance/third_party /tmp/tmp.IiaeTXyhb0/tf_quant_finance
    building file list ... done
    third_party/
    third_party/sobol_data/
    third_party/sobol_data/LICENSE
    third_party/sobol_data/new-joe-kuo-6.21201

sent 1,890,131 bytes received 60 bytes 3,780,382.00 bytes/sec
total size is 1,889,431 speedup is 1.00

  • pushd /tmp/tmp.IiaeTXyhb0
    /tmp/tmp.IiaeTXyhb0 /data/jw/tf-quant-finance
    ++ date
  • echo Fri Mar 5 17:07:50 CET 2021 : '=== Building wheel'
    Fri Mar 5 17:07:50 CET 2021 : === Building wheel
  • python3 setup.py bdist_wheel --universal
    usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
    or: setup.py --help [cmd1 cmd2 ...]
    or: setup.py --help-commands
    or: setup.py cmd --help

error: invalid command 'bdist_wheel'
[jw@cn06 tf-quant-finance]$

TF 2.0 Compatibility

Hi!

Thanks for the really cool library! I recently came across this library as I want to learn more about quant finance and ML and this package really interested me :) I understand it's currently pre-Alpha but I am wondering if this package is compatible with TF 2.0, if not, is it somewhere on the roadmap or is that something I can help out with? Thank you so much!

Monte_Carlo_Euler_Scheme.ipynb

There is some problem on the reported time for GPU vs CPU on multiple dimensions 100.
I am using a single GPU and it is slower compared to my CPU multithreading. I am wondering why... The rest of the notebooks work as expected.
I am using a GeForce 1080 not a TESLA v100 GPU, but intuitively i would expect to have a similar speedup...

Any ideas why I get this behaviour ?

Regards,
pb

Time decay of American options

Hello and thanks for the library!

I am working on an integration of TFF into one of my option trading strategies and trying to figure out several practical aspects, such as IV determination and finding greeks. After reading through all issues and discussions I have a working notebook which expands the American option example (using PDE) and includes volatility estimation and (most of) greeks using tff.math.fwd_gradient. There are still some questions about gridding to manage batches with significantly different strikes, but I think I'll manage, maybe even to an extent I can do a PR for that example...

One thing I cannot comprehend yet is the time decay and time aspects overalls. How would you recommend to approach theta estimation? Should I try fwd_gradient on expiry? Related question is how to manage options with significantly different time to expiration? The example states that volatility term has to be adjusted - not sure I understand it.

expiry: A Python float. Expiry date of the options. If the options
      have different expiries, volatility term has to adjusted to
      make expiries the same.

SOFR USD OIS curve

I am currently having issues in matching BBG discount OIS curve using the same SOFR swaps used in the icvs function. I suspect this is due to the different compounding of libor an sofr. Is there any workaround to this issue?

XLA compilation error of a TARF payoff with MC

I'm trying to replicate the TARF payoff from this paper.
So far, i've been able to write a payoff that can be evaluated with MC and GPU, but i get an error with the XLA compilation.
https://colab.research.google.com/github/arthurpham/google_colab/blob/7d5715c2b0f988c8d7d544fea0ff741e63272056/TARF_MC_Performance_TQF.ipynb
I understand that the payoff code style might not be the best, but i wasn't able to find an example of a path-dependent payoff with MC.
Any pointer would be helpful.

image

image

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-7-945d7282d2b1> in <module>()
      1 device = "/gpu:0"
      2 with tf.device(device):
----> 3     tarf_price = price_eu_options_xla(strikes, spot, sigma)
      4     print('price', tarf_price)

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     53     ctx.ensure_initialized()
     54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 55                                         inputs, attrs, num_outputs)
     56   except core._NotOkStatusException as e:
     57     if name is not None:

InvalidArgumentError: Detected unsupported operations when trying to compile graph __inference_price_eu_options_9107[_XlaMustCompile=true,config_proto=6001324581131673121,executor_type=11160318154034397263] on XLA_GPU_JIT: TensorListReserve (No registered 'TensorListReserve' OpKernel for XLA_GPU_JIT devices compatible with node {{function_node __inference_while_fn_9086}}{{node while_init/TensorArrayV2_7}}
	 (OpKernel was found, but attributes didn't match) Requested Attributes: element_dtype=DT_VARIANT, shape_type=DT_INT32){{function_node __inference_while_fn_9086}}{{node while_init/TensorArrayV2_7}}
The op is created at: 
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
  "__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
  exec(code, run_globals)
File "/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py", line 16, in <module>
  app.launch_new_instance()
File "/usr/local/lib/python3.7/dist-packages/traitlets/config/application.py", line 846, in launch_instance
  app.start()
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelapp.py", line 499, in start
  self.io_loop.start()
File "/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py", line 132, in start
  self.asyncio_loop.run_forever()
File "/usr/lib/python3.7/asyncio/base_events.py", line 541, in run_forever
  self._run_once()
File "/usr/lib/python3.7/asyncio/base_events.py", line 1786, in _run_once
  handle._run()
File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run
  self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.7/dist-packages/tornado/ioloop.py", line 758, in _run_callback
  ret = callback()
File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
  return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 536, in <lambda>
  self.io_loop.add_callback(lambda: self._handle_events(self.socket, 0))
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 452, in _handle_events
  self._handle_recv()
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 481, in _handle_recv
  self._run_callback(callback, msg)
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 431, in _run_callback
  callback(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
  return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
  return self.dispatch_shell(stream, msg)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 233, in dispatch_shell
  handler(stream, idents, msg)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
  user_expressions, allow_stdin)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/ipkernel.py", line 208, in do_execute
  res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/zmqshell.py", line 537, in run_cell
  return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
  interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
  if self.run_code(code, result):
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
  exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-7-945d7282d2b1>", line 3, in <module>
  tarf_price = price_eu_options_xla(strikes, spot, sigma)
File "<ipython-input-5-1d20baab715c>", line 89, in price_eu_options
  payoffs = tf.vectorized_map(my_function, reshaped_paths) [Op:__inference_price_eu_options_9107]

Fair performance comparison with QuantLib

Hi guys,

In the "Monte Carlo via Euler Scheme" example you compare TF with QuantLib pricing and conclude that TF finance is x100 times faster(or more).

I want to note that in QL you evolve 100 time steps of Log Normal process, but in TF you work in log space and only apply exp() at the end.
I agree QL may not be very fast, but in this example you compare 100 exponents per path in QL to just 1 exponent in TF...

Thank you!

Interpolation issue with Hagan West Monotone Convex

The following input seems to give bad output with a strange jump,

reference_times = np.array([0.08219178, 0.12328767, 0.16438356, 0.24657534, 0.32876712, 0.4109589, 0.49315068, 0.98630137, 1.02191781], dtype=np.float64)
yields = np.array([2.5e-5, 1.189e-4, 2.151e-4, 4.236e-4, 6.5e-4, 8.905e-4, 1.141e-3, 2.6321e-3, 4.366e-3], dtype=np.float64)
interp_times = np.linspace(0.1, 1.0, 100, dtype=np.float64)
interp_yields = monotone_convex.interpolate_yields(interp_times, reference_times, yields=yields)

Plotting it out gives,

image

Can someone kindly advise?

Regards,

conda-forge package

Are there any plans (or objections) to add this to conda-forge? Given that it's a prue Python library, it should be rather straight-forward to do.

Options at-expiration return `nan`

I am using tf-quant-finance for plotting option values and greeks. When plotting at-expiration (so expiries=0) most of the models return nan for some or all prices. Is this intended behavior, in which case I should wrap my calls to tf-quant-finance with some code to counter this, or is this something that could be changed?

This issue shows up for:

  • Bjerksund-Stensland with modified_boundary=True for all prices on a call, but only out-of-the-money prices on puts
  • Adesi-Whaley for out-of-the-money prices on calls only
  • Binomial for all options (American or European, calls or puts)

Only Black-Scholes-Merton and Bjerksund-Stensland with modified_boundary=False are not affected by this.

I could submit a PR to fix this issue, but before I do the work I want to make sure that this is a bug and not a feature.

ImportError when installing from source code

I installed tf-quant-finance from source cloned on 16-Jun-2021 and get the below error:

>>> import tf_quant_finance as tff
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tf-quant-finance/tf_quant_finance/__init__.py", line 74, in <module>
    from tf_quant_finance import experimental
  File "/tf-quant-finance/tf_quant_finance/experimental/__init__.py", line 19, in <module>
    from tf_quant_finance.experimental import local_stochastic_volatility
  File "/tf-quant-finance/tf_quant_finance/experimental/local_stochastic_volatility/__init__.py", line 17, in <module>
    from tf_quant_finance.experimental.local_stochastic_volatility.local_stochastic_volatility_model import LocalStochasticVolatilityModel
  File "/tf-quant-finance/tf_quant_finance/experimental/local_stochastic_volatility/local_stochastic_volatility_model.py", line 25, in <module>
    from tf_quant_finance.experimental import local_volatility as lvm
  File "/tf-quant-finance/tf_quant_finance/experimental/local_volatility/__init__.py", line 18, in <module>
    from tf_quant_finance.experimental.local_volatility.local_volatility_model import LocalVolatilityModel
  File "/tf-quant-finance/tf_quant_finance/experimental/local_volatility/local_volatility_model.py", line 25, in <module>
    from tf_quant_finance.experimental.pricing_platform.framework.market_data import volatility_surface
  File "/tf-quant-finance/tf_quant_finance/experimental/pricing_platform/__init__.py", line 17, in <module>
    from tf_quant_finance.experimental.pricing_platform import framework
  File "/tf-quant-finance/tf_quant_finance/experimental/pricing_platform/framework/__init__.py", line 17, in <module>
    from tf_quant_finance.experimental.pricing_platform.framework import core
  File "/tf-quant-finance/tf_quant_finance/experimental/pricing_platform/framework/core/__init__.py", line 17, in <module>
    from tf_quant_finance.experimental.pricing_platform.framework.core import business_days
  File "/tf-quant-finance/tf_quant_finance/experimental/pricing_platform/framework/core/business_days.py", line 18, in <module>
    from tf_quant_finance.experimental.pricing_platform.instrument_protos import business_days_pb2
  File "/tf-quant-finance/tf_quant_finance/experimental/pricing_platform/instrument_protos/__init__.py", line 17, in <module>
    from tf_quant_finance.experimental.pricing_platform.instrument_protos import all_instruments_pb2 as instruments
ImportError: cannot import name 'all_instruments_pb2' from partially initialized module 'tf_quant_finance.experimental.pricing_platform.instrument_protos' (most likely due to a circular import)

This looks to be a bug which was introduced recently (last time I installed from source on 18-May-2021 I did not get this error).

I am not familiar with any of the files mentioned here, so would not be the best person to investigate. Is there someone who can investigate this? Do others get the same error when installing from source?

Pricing formulas for Barrier options under Black-Scholes

Formulas for pricing a Barrier option under Black-Scholes model is of interest. (See, e.g., Section 26.9 of Hull(2018), Options, Futures, and Other Derivatives, 9th edition).

The module implementing this method should live under tf_quant_finance/volatility/barrier_option.py. It should support both puts (up-and-in put, down-and-out put) and calls (down-in call, up-and-out call). Tests should be in barrier_option_test.py in the same folder.

Consistent argument names for dividends across option pricing models

Argument names for dividends across different option pricing models appear to be different, with no obvious reason for the difference. For example, tff.black_scholes.option_price takes in continuous_dividends, while tff.black_scholes.option_price_binomial takes in dividend_rates.

If there is no reason for the difference, then I would suggest changing dividend_rates to continuous_dividends, as tff.black_scholes.approximations.adesi_whaley also takes continuous_dividends. This would make it easier to write reusable code independent of the pricing model used.

What do others think of this? If everyone agrees to this change, then I can make it and submit the pull request.

Approximate European option price under SABR model

SABR model has accurate density approximations (see, e.g., here). It is of interest to use the approximations to estimate European option prices.

The module implementing this method should live under tf_quant_finance/volatility/sabr_approximation.py. It should support both European puts and calls approximations. Tests should be in sabr_approximation_test.py in the same folder.

Memory leak with TF.function

https://colab.research.google.com/github/arthurpham/google_colab/blob/e20469359e82ecf96640837e2022f58de0df8314/AmericanOption_MC_MemoryLeak_TQF.ipynb

I've tried to reuse the jupyter notebook that show how to do a MC pricing.

for i in trange(1, 100000):
    strikes = tf.constant(np.random.rand(i) * (0.5*spot) + spot, dtype )
    price_eu_options(strikes, spot, sigma)

The test is slightly silly but if the application that calls the pricing library might chose to send an arbitrary strike size, so the batch size might not be known in advance, so i'm wondering what is the best way to handle that without asking quants to micromanage the shapes of each inputs (as a change in the shape of one input retrigger the graph construction) ?

Thank you

image

The mailing-list is set to Invite Only

Hi!
The main page mentions:
tf-quant-finance: Open mailing list for discussion and questions of this library.
However, the group isn't findable and subscribing via email reveals its settings are "Invite Only".
I would suggest to remedy this by either adjusting the settings or updating the info on the main page to remove the list.
Thank you,

khronos ML summit

Hello,

I am the chair of a working group at Khronos developing standards for graphics and compute hardware accelerators (as well as a representative for Nvidia in those groups).

We are organizing a summit to gather feedback from the ecosystem, and influence the design of the next round of improvements, and I thought that you may be interested in being represented:
https://www.khronos.org/events/2021-invitation-to-the-khronos-machine-learning-summit

This summit is IP free, and will let you present your project and your needs for improvements in the ML ecosystem, as well as hearing from other companies.

regards,

Pierre Boudier
Software architect at Nvidia
chair of the Machine Learning TSG at Khronos

Poor Performance in TensorFlow 2.1

I was refactoring the "American_Option_Black_Sholes.ipynb" to use the new fd_solvers API with TensorFlow 2.1, but it has much worse performance than in the previous version that was pre-TF2.0.

Here is the notebook re-written in eager style and ran on the colab GPU: https://colab.research.google.com/drive/1FVYloxIrSvlSrp1aMPLxN4f4KlvPI8l0

As you can see the CPU and GPU options/sec benchmarks are both around 1/3 what they were in the old notebook saved on the master branch. I've also tried running the same code, but using the tf.compat.v1 Session and graph; this did not improve performance at all. I've also tried to profile the code using tf.summary.trace_on(graph=True, profiler=True), but it doesn't produce any useful information.

Is this performance something I'm doing wrong with my implementation, is there perhaps some better way I can profile the core library for issues, or is this related to some performance issues with TF2.0 itself?

American option price under Cox-Ross-Rubinstein

Binomial options pricing models like Cox-Ross-Rubinstein have been widely used since they are able to handle a variety of conditions for which other models cannot easily be applied proving themselves to be more accurate, particularly for longer-dated options on securities with dividend payments.

Integration/interpolation methods

Hi all, many thanks for this library! As I've seen, there is an integration method and interpolation. The latter are also available in other packages (tf-graphics, tf-addons) in one way or another while the integration is not (AFAIK?).

However, we implemented multiple integration algorithms and plan to put them up/into an existing repository. TFP seems nice but maybe not fully suited. However, this repository also does not seem directly like the place for this methods (as it is a very general used functionality, especially in science). Or what do you think?

Would it make sense to put this somewhere else? If so, where?

Many thanks for all the work!

SABR calibration

Hello,
I'm trying to use the SABR calibration with real BTC option prices but it stops right away without any error message (is_converged is False).
If anyone could help to see what is wrong with this pretty simple code:
Colab notebook (created a wheel with the latest code)

import pandas as pd
import requests
import tf_quant_finance as tff
import time
from datetime import datetime
import numpy

vals = pd.DataFrame(requests.get(
  'https://www.deribit.com/api/v2/public/get_instruments?currency=BTC&expired=false&kind=option').json()['result'])
jul_exp = vals[(vals['expiration_timestamp'] == 1627632000000)]
jul_exp['price'] = [requests.get(f'https://www.deribit.com/api/v2/public/ticker?instrument_name={x}').json()['result']['last_price'] for x in jul_exp['instrument_name']]
jul_exp.dropna(subset=['price'], inplace = True)
underlying = requests.get('https://www.deribit.com/api/v2/public/ticker?instrument_name=BTC-30JUL21').json()['result']
jul_exp['price'] = jul_exp['price'] * underlying['index_price']
is_call = numpy.array([[t == 'call' for t in jul_exp['option_type']]], dtype=numpy.bool)
delta =(( jul_exp.iloc[0]['expiration_timestamp']/1000 - time.time())  / 60 / 60 / 24) / 365
dtype = numpy.float64
models, is_converged, it = tff.models.sabr.approximations.calibration(
    prices=numpy.array([jul_exp['price'].to_numpy()], dtype=dtype),
    strikes=numpy.array([jul_exp['strike'].to_numpy()], dtype=dtype),
    expiries=numpy.array([delta], dtype=dtype),
    forwards=numpy.array([underlying['index_price']], dtype=dtype),
    is_call_options=is_call,
    beta=numpy.array([0.5], dtype=dtype),
    calibrate_beta=True,
    nu=numpy.array([0.1], dtype=dtype),
    nu_lower_bound=0.0,
    nu_upper_bound=10.0,
    rho=numpy.array([0.0], dtype=dtype),
    rho_lower_bound=-0.75,
    rho_upper_bound=0.75,
    maximum_iterations=1000)

case-sensitive paths on a case-insensitive filesystem

when cloning, the following warning pops up:

warning: the following paths have collided (e.g. case-sensitive paths
on a case-insensitive filesystem) and only one from the same
colliding group is in the working tree:

'api_docs/tf_quant_finance/datetime/Month.md'
'api_docs/tf_quant_finance/datetime/month.md'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.