class_docstr: Local volatility model for smile modeling.
  
  Local volatility (LV) model specifies that the dynamics of an asset is
  governed by the following stochastic differential equation:
  
  ```None
    dS(t) / S(t) =  mu(t, S(t)) dt + sigma(t, S(t)) * dW(t)
  ```
  where `mu(t, S(t))` is the drift and `sigma(t, S(t))` is the instantaneous
  volatility. The local volatility function `sigma(t, S(t))` is state dependent
  and is computed by calibrating against a given implied volatility surface
  `sigma_iv(T, K)` using the Dupire's formula [1]:
  
  ```
  sigma(T,K)^2 = 2 * (dC(T,K)/dT + (r - q)K dC(T,K)/dK + qC(T,K)) /
                     (K^2 d2C(T,K)/dK2)
  ```
  where the derivatives above are the partial derivatives. The LV model provides
  a flexible framework to model any (arbitrage free) volatility surface.
  
  #### Example: Simulation of local volatility process.
  
  ```python
  import numpy as np
  import tensorflow.compat.v2 as tf
  import tf_quant_finance as tff
  
  dtype = tf.float64
  dim = 2
  year = dim * [[2021, 2022]]
  month = dim * [[1, 1]]
  day = dim * [[1, 1]]
  expiries = tff.datetime.dates_from_year_month_day(year, month, day)
  valuation_date = [(2020, 1, 1)]
  expiry_times = tff.datetime.daycount_actual_365_fixed(
      start_date=valuation_date, end_date=expiries, dtype=dtype)
  strikes = dim * [[[0.1, 0.9, 1.0, 1.1, 3], [0.1, 0.9, 1.0, 1.1, 3]]]
  iv = dim * [[[0.135, 0.13, 0.1, 0.11, 0.13],
               [0.135, 0.13, 0.1, 0.11, 0.13]]]
  spot = dim * [1.0]
  risk_free_rate = [0.02]
  r = tf.convert_to_tensor(risk_free_rate, dtype=dtype)
  df = lambda t: tf.math.exp(-r * t)
  
  lv = tff.models.LocalVolatilityModel.from_market_data(
      dim, val_date, expiries, strikes, iv, spot, df, [0.0], dtype=dtype)
  num_samples = 10000
  paths = lv.sample_paths(
      [1.0, 1.5, 2.0],
      num_samples=num_samples,
      initial_state=spot,
      time_step=0.1,
      random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC,
      seed=[1, 2])
  # paths.shape = (10000, 3, 2)
  
  #### References:
    [1]: Iain J. Clark. Foreign exchange option pricing - A Practitioner's
    guide. Chapter 5, Section 5.3.2. 2011.
docstr: Creates a `LocalVolatilityModel` from market data.
  
  Args:
    dim: A Python scalar which corresponds to the number of underlying assets
      comprising the model.
    valuation_date: A `DateTensor` specifying the valuation (or settlement)
      date for the market data.
    expiry_dates: A `DateTensor` of shape `(dim, num_expiries)` containing the
      expiry dates on which the implied volatilities are specified.
    strikes: A `Tensor` of real dtype and shape `(dim, num_expiries,
      num_strikes)`specifying the strike prices at which implied volatilities
      are specified.
    implied_volatilities: A `Tensor` of real dtype and shape `(dim,
      num_expiries, num_strikes)` specifying the implied volatilities.
    spot: A real `Tensor` of shape `(dim,)` specifying the underlying spot
      price on the valuation date.
    discount_factor_fn: A python callable accepting one real `Tensor` argument
      time t. It should return a `Tensor` specifying the discount factor to
      time t.
    dividend_yield: A real `Tensor` of shape compatible with `spot_price`
      specifying the (continuously compounded) dividend yield. If the
      underlying is an FX rate, then use this input to specify the foreign
      interest rate.
      Default value: `None` in which case the input is set to Zero.
    local_volatility_from_iv: A bool. If True, calculates the Dupire local
      volatility function from implied volatilities. Otherwise, it computes
      the local volatility using option prices.
      Default value: True.
    times_grid: A `Tensor` of shape `[num_time_samples]`. The grid on which to
      do interpolation over time. Must be jointly specified with `spot_grid`
      or `None`.
      Default value: `None`.
    spot_grid: A `Tensor` of shape `[num_spot_samples]`. The grid on which to
      do interpolation over spots. Must be jointly specified with `times_grid`
      or `None`.
      Default value: `None`.
    precompute_iv: A bool. Whether or not to precompute implied volatility
      spline coefficients when using Dupire's formula. This is done by
      precomputing values of implied volatility on the grid
      `times_grid x spot_grid`. The algorithm then steps through `times_grid`
      in `sample_paths`.
      Default value: False.
    dtype: The default dtype to use when converting values to `Tensor`s.
      Default value: `None` which means that default dtypes inferred by
        TensorFlow are used.
    name: Python string. The name to give to the ops created by this class.
      Default value: `None` which maps to the default name `from_market_data`.
  
  Returns:
    An instance of `LocalVolatilityModel` constructed using the input data.
docstr_tok: ["Creates","a","`","LocalVolatilityModel","`","from","market","data",".","Args",":","dim",":","A","Python","scalar","which","corresponds","to","the","number","of","underlying","assets","comprising","the","model",".","valuation_date",":","A","`","DateTensor","`","specifying","the","valuation","(","or","settlement",")","date","for","the","market","data",".","expiry_dates",":","A","`","DateTensor","`","of","shape","`","(","dim",",","num_expiries",")","`","containing","the","expiry","dates","on","which","the","implied","volatilities","are","specified",".","strikes",":","A","`","Tensor","`","of","real","dtype","and","shape","`","(","dim",",","num_expiries",",","num_strikes",")","`","specifying","the","strike","prices","at","which","implied","volatilities","are","specified",".","implied_volatilities",":","A","`","Tensor","`","of","real","dtype","and","shape","`","(","dim",",","num_expiries",",","num_strikes",")","`","specifying","the","implied","volatilities",".","spot",":","A","real","`","Tensor","`","of","shape","`","(","dim",",",")","`","specifying","the","underlying","spot","price","on","the","valuation","date",".","discount_factor_fn",":","A","python","callable","accepting","one","real","`","Tensor","`","argument","time","t.","It","should","return","a","`","Tensor","`","specifying","the","discount","factor","to","time","t.","dividend_yield",":","A","real","`","Tensor","`","of","shape","compatible","with","`","spot_price","`","specifying","the","(","continuously","compounded",")","dividend","yield",".","If","the","underlying","is","an","FX","rate",",","then","use","this","input","to","specify","the","foreign","interest","rate",".","Default","value",":","`","None","`","in","which","case","the","input","is","set","to","Zero",".","local_volatility_from_iv",":","A","bool",".","If","True",",","calculates","the","Dupire","local","volatility","function","from","implied","volatilities",".","Otherwise",",","it","computes","the","local","volatility","using","option","prices",".","Default","value",":","True",".","times_grid",":","A","`","Tensor","`","of","shape","`","[","num_time_samples","]","`",".","The","grid","on","which","to","do","interpolation","over","time",".","Must","be","jointly","specified","with","`","spot_grid","`","or","`","None","`",".","Default","value",":","`","None","`",".","spot_grid",":","A","`","Tensor","`","of","shape","`","[","num_spot_samples","]","`",".","The","grid","on","which","to","do","interpolation","over","spots",".","Must","be","jointly","specified","with","`","times_grid","`","or","`","None","`",".","Default","value",":","`","None","`",".","precompute_iv",":","A","bool",".","Whether","or","not","to","precompute","implied","volatility","spline","coefficients","when","using","Dupire","'s","formula",".","This","is","done","by","precomputing","values","of","implied","volatility","on","the","grid","`","times_grid","x","spot_grid","`",".","The","algorithm","then","steps","through","`","times_grid","`","in","`","sample_paths","`",".","Default","value",":","False",".","dtype",":","The","default","dtype","to","use","when","converting","values","to","`","Tensor","`","s",".","Default","value",":","`","None","`","which","means","that","default","dtypes","inferred","by","TensorFlow","are","used",".","name",":","Python","string",".","The","name","to","give","to","the","ops","created","by","this","class",".","Default","value",":","`","None","`","which","maps","to","the","default","name","`","from_market_data","`",".","Returns",":","An","instance","of","`","LocalVolatilityModel","`","constructed","using","the","input","data","."]
code: def from_market_data(
      cls,
      dim: int,
      valuation_date: types.DateTensor,
      expiry_dates: types.DateTensor,
      strikes: types.RealTensor,
      implied_volatilities: types.RealTensor,
      spot: types.RealTensor,
      discount_factor_fn: Callable[..., types.RealTensor],
      dividend_yield: Optional[Callable[..., types.RealTensor]] = None,
      local_volatility_from_iv: Optional[bool] = True,
      times_grid: Optional[types.RealTensor] = None,
      spot_grid: Optional[types.RealTensor] = None,
      precompute_iv: Optional[bool] = False,
      dtype: Optional[tf.DType] = None,
      name: Optional[str] = None,
  ) -> generic_ito_process.GenericItoProcess:
      """Creates a `LocalVolatilityModel` from market data.
  
      Args:
        dim: A Python scalar which corresponds to the number of underlying assets
          comprising the model.
        valuation_date: A `DateTensor` specifying the valuation (or settlement)
          date for the market data.
        expiry_dates: A `DateTensor` of shape `(dim, num_expiries)` containing the
          expiry dates on which the implied volatilities are specified.
        strikes: A `Tensor` of real dtype and shape `(dim, num_expiries,
          num_strikes)`specifying the strike prices at which implied volatilities
          are specified.
        implied_volatilities: A `Tensor` of real dtype and shape `(dim,
          num_expiries, num_strikes)` specifying the implied volatilities.
        spot: A real `Tensor` of shape `(dim,)` specifying the underlying spot
          price on the valuation date.
        discount_factor_fn: A python callable accepting one real `Tensor` argument
          time t. It should return a `Tensor` specifying the discount factor to
          time t.
        dividend_yield: A real `Tensor` of shape compatible with `spot_price`
          specifying the (continuously compounded) dividend yield. If the
          underlying is an FX rate, then use this input to specify the foreign
          interest rate.
          Default value: `None` in which case the input is set to Zero.
        local_volatility_from_iv: A bool. If True, calculates the Dupire local
          volatility function from implied volatilities. Otherwise, it computes
          the local volatility using option prices.
          Default value: True.
        times_grid: A `Tensor` of shape `[num_time_samples]`. The grid on which to
          do interpolation over time. Must be jointly specified with `spot_grid`
          or `None`.
          Default value: `None`.
        spot_grid: A `Tensor` of shape `[num_spot_samples]`. The grid on which to
          do interpolation over spots. Must be jointly specified with `times_grid`
          or `None`.
          Default value: `None`.
        precompute_iv: A bool. Whether or not to precompute implied volatility
          spline coefficients when using Dupire's formula. This is done by
          precomputing values of implied volatility on the grid
          `times_grid x spot_grid`. The algorithm then steps through `times_grid`
          in `sample_paths`.
          Default value: False.
        dtype: The default dtype to use when converting values to `Tensor`s.
          Default value: `None` which means that default dtypes inferred by
            TensorFlow are used.
        name: Python string. The name to give to the ops created by this class.
          Default value: `None` which maps to the default name `from_market_data`.
  
      Returns:
        An instance of `LocalVolatilityModel` constructed using the input data.
      """
      name = name or "from_market_data"
      if precompute_iv and (times_grid is None or spot_grid is None):
          raise ValueError(
              "When `precompute_iv` is True, both `times_grid` and `spot_grid` must"
              " be supplied"
          )
      with tf.name_scope(name):
          spot = tf.convert_to_tensor(spot, dtype=dtype)
          dtype = dtype or spot.dtype
          dividend_yield = (
              [0.0] if dividend_yield is None else dividend_yield
          )
          dividend_yield = tf.convert_to_tensor(
              dividend_yield, dtype=dtype
          )
  
          risk_free_rate_fn = _get_risk_free_rate_from_discount_factor(
              discount_factor_fn
          )
  
          valuation_date = datetime.convert_to_date_tensor(
              valuation_date
          )
          expiry_dates = datetime.convert_to_date_tensor(expiry_dates)
          expiry_times = (
              tf.cast(
                  valuation_date.days_until(expiry_dates), dtype=dtype
              )
              / 365.0
          )
          strikes = tf.convert_to_tensor(strikes, dtype=dtype)
          implied_volatilities = tf.convert_to_tensor(
              implied_volatilities, dtype=dtype
          )
  
          def _log_forward_moneyness(times, strikes):
              # log_fwd_moneyness = log(strike/(spot*exp((r-d)*times)))
              risk_free_rate = tf.squeeze(risk_free_rate_fn(times))
              log_forward_moneyness = tf.math.log(
                  tf.math.divide_no_nan(
                      strikes, tf.reshape(spot, [dim, 1, 1])
                  )
              ) - tf.expand_dims(
                  (risk_free_rate - dividend_yield) * times, axis=-1
              )
              return log_forward_moneyness
  
          interpolator = interpolation_2d.Interpolation2D(
              expiry_times,
              _log_forward_moneyness(expiry_times, strikes),
              implied_volatilities,
              dtype=dtype,
          )
  
          def _log_moneyness_2d_interpolator(times, strikes):
              risk_free_rate = risk_free_rate_fn(times)
              log_forward_moneyness = (
                  tf.math.log(strikes / spot)
                  - (risk_free_rate - dividend_yield) * times
              )
              moneyness_transposed = tf.transpose(log_forward_moneyness)
  
              times = tf.broadcast_to(times, moneyness_transposed.shape)
              return tf.transpose(
                  interpolator.interpolate(times, moneyness_transposed)
              )
  
          vs = volatility_surface.VolatilitySurface(
              valuation_date,
              expiry_dates,
              strikes,
              implied_volatilities,
              interpolator=_log_moneyness_2d_interpolator,
              dtype=dtype,
          )
  
          if precompute_iv:
              local_volatility_fn = (
                  _dupire_local_volatility_iv_precomputed(
                      initial_spot_price=spot,
                      discount_factor_fn=discount_factor_fn,
                      dividend_yield=dividend_yield,
                      implied_volatility_surface=vs.volatility,
                      times_grid=times_grid,
                      spot_grid=spot_grid,
                      dim=dim,
                      dtype=dtype,
                  )
              )
          else:
              local_volatility_fn = functools.partial(
                  _dupire_local_volatility_iv
                  if local_volatility_from_iv
                  else _dupire_local_volatility_prices,
                  initial_spot_price=spot,
                  discount_factor_fn=discount_factor_fn,
                  dividend_yield=dividend_yield,
                  implied_volatility_surface=vs.volatility,
              )
  
          return LocalVolatilityModel(
              dim,
              risk_free_rate=risk_free_rate_fn,
              dividend_yield=dividend_yield,
              local_volatility_fn=local_volatility_fn,
              times_grid=times_grid,
              spot_grid=spot_grid,
              precompute_iv=precompute_iv,
              dtype=dtype,
          )
  
imports: import functools
  from typing import Any, Callable, List, Optional, Union
  import tensorflow.compat.v2
  from tf_quant_finance import black_scholes
  from tf_quant_finance import datetime
  from tf_quant_finance import math
  from tf_quant_finance import types
  from tf_quant_finance.experimental.pricing_platform.framework.market_data import volatility_surface
  from tf_quant_finance.math import interpolation
  from tf_quant_finance.math import piecewise
  from tf_quant_finance.math import random
  from tf_quant_finance.models import generic_ito_process
label_desc: Use image node_id 5 for calling the LocalVolatilityModel obj's underlying member method code with example usage: obj.from_market_data(cls, dim, valuation_date, expiry_dates, strikes, implied_volatilities, spot, discount_factor_fn, dividend_yield, local_volatility_from_iv, times_grid, spot_grid, precompute_iv, dtype, name) and returns: LocalVolatilityModel, log_forward_moneyness, tf