Python tensorflow.compat.v2.name_scope() Examples

The following are 30 code examples of tensorflow.compat.v2.name_scope(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tensorflow.compat.v2 , or try the search function .
Example #1
Source File: univariate_geometric_brownian_motion.py    From tf-quant-finance with Apache License 2.0 6 votes vote down vote up
def __init__(self,
               mu,
               sigma,
               dtype=None,
               name=None):
    """Initializes the Geometric Brownian Motion.

    Args:
      mu: Scalar real `Tensor`. Corresponds to the mean of the Ito process.
      sigma: Scalar real `Tensor` of the same `dtype` as `mu`. Corresponds to
        the volatility of the process.
      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
        'geometric_brownian_motion'.
    """
    self._name = name or "geometric_brownian_motion"
    with tf.name_scope(self._name):
      self._mu = tf.convert_to_tensor(mu, dtype=dtype, name="mu")
      self._dtype = self._mu.dtype
      self._sigma = tf.convert_to_tensor(sigma, dtype=self._dtype, name="sigma")
      self._dim = 1 
Example #2
Source File: pixelcnn.py    From alibi-detect with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 shift,
                 validate_args=False,
                 name='shift'):
        """Instantiates the `Shift` bijector which computes `Y = g(X; shift) = X + shift`
        where `shift` is a numeric `Tensor`.
        Args:
          shift: Floating-point `Tensor`.
          validate_args: Python `bool` indicating whether arguments should be
            checked for correctness.
          name: Python `str` name given to ops managed by this object.
        """
        with tf.name_scope(name) as name:
            dtype = dtype_util.common_dtype([shift], dtype_hint=tf.float32)
            self._shift = tensor_util.convert_nonref_to_tensor(shift, dtype=dtype, name='shift')
            super(Shift, self).__init__(
              forward_min_event_ndims=0,
              is_constant_jacobian=True,
              dtype=dtype,
              validate_args=validate_args,
              name=name
            ) 
Example #3
Source File: __init__.py    From language with Apache License 2.0 6 votes vote down vote up
def weighted_by_sum(
      self, other):
    """Weight elements in some set by the sum of the scores in some other set.

    Args:
      other: A NeuralQueryExpression

    Returns:
      The NeuralQueryExpression that evaluates to the reweighted version of
    the set obtained by evaluating 'self'.
    """
    provenance = NQExprProvenance(
        operation='weighted_by_sum',
        inner=self.provenance,
        other=other.provenance)
    with tf.name_scope('weighted_by_sum'):
      return self.context.as_nql(
          self.tf * tf.reduce_sum(input_tensor=other.tf, axis=1, keepdims=True),
          self._type_name, provenance) 
Example #4
Source File: bond.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def price(self, valuation_date, market, model=None, name=None):
    """Returns the dirty price of the bonds on the valuation date.

    Args:
      valuation_date: A scalar `DateTensor` specifying the date on which
        valuation is being desired.
      market: A namedtuple of type `InterestRateMarket` which contains the
        necessary information for pricing the bonds.
      model: Reserved for future use.
      name: Python str. The name to give to the ops created by this function.
        Default value: `None` which maps to 'price'.

    Returns:
      A Rank 1 `Tensor` of real dtype containing the dirty price of each bond
      based on the input market data.
    """

    name = name or (self._name + '_price')
    with tf.name_scope(name):
      discount_curve = market.discount_curve
      coupon_cf = self._cashflows.price(valuation_date, market, model)
      principal_cf = (
          self._notional * discount_curve.get_discount_factor(
              self._maturity_date)
          )
      return coupon_cf + principal_cf 
Example #5
Source File: early_return_test.py    From autograph with Apache License 2.0 5 votes vote down vote up
def nested_ifs_and_context_managers(x):
  with tf.name_scope(''):
    if x > 0:
      if x < 5:
        with tf.name_scope(''):
          return x
      else:
        return x * x
    else:
      return x * x * x 
Example #6
Source File: early_return_test.py    From autograph with Apache License 2.0 5 votes vote down vote up
def unreachable_return(x):
  with tf.name_scope(''):
    if x > 0:
      if x < 5:
        with tf.name_scope(''):
          return x
      else:
        return x * x
    else:
      return x * x * x
  return x * x * x * x 
Example #7
Source File: daycounts.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def actual_365_fixed(*,
                     start_date,
                     end_date,
                     schedule_info=None,
                     dtype=None,
                     name=None):
  """Computes the year fraction between the specified dates.

  The actual/365 convention specifies the year fraction between the start and
  end date as the actual number of days between the two dates divided by 365.

  Note that the schedule info is not needed for this convention and is ignored
  if supplied.

  For more details see:
  https://en.wikipedia.org/wiki/Day_count_convention#Actual/365_Fixed

  Args:
    start_date: A `DateTensor` object of any shape.
    end_date: A `DateTensor` object of compatible shape with `start_date`.
    schedule_info: The schedule info. Ignored for this convention.
    dtype: The dtype of the result. Either `tf.float32` or `tf.float64`. If not
      supplied, `tf.float32` is returned.
    name: Python `str` name prefixed to ops created by this function. If not
      supplied, `actual_365_fixed` is used.

  Returns:
    A real `Tensor` of supplied `dtype` and shape of `start_date`. The year
    fraction between the start and end date as computed by Actual/365 fixed
    convention.
  """
  del schedule_info
  with tf.name_scope(name or 'actual_365_fixed'):
    end_date = dt.convert_to_date_tensor(end_date)
    start_date = dt.convert_to_date_tensor(start_date)
    dtype = dtype or tf.constant(0.).dtype
    actual_days = tf.cast(start_date.days_until(end_date), dtype=dtype)
    return actual_days / 365 
Example #8
Source File: early_return_test.py    From autograph with Apache License 2.0 5 votes vote down vote up
def return_with_default_in_contexmanager(x):
  with tf.name_scope(''):
    if x > 0:
      return 1
    return 0 
Example #9
Source File: __init__.py    From language with Apache License 2.0 5 votes vote down vote up
def follow(self,
             rel_specification,
             inverted = +1):
    """Follow a relation, or relation group, in the knowledge graph.

    Specifically, if x evaluates to a set of knowledge graph entities, then
    x.follow('foo') evaluates to the set of all entities which are related to x
    via the relation 'foo'.

    When rel_specification is a string naming a relation - ie it is a relation
    named in the expression's context - then follow only that relation in the
    knowledge graph. If inverted == -1, then follow the inverse of the relation.

    When rel_specification is an expression that evaluates to a a type
    associated with a relation group, then follow all the relations in that
    group, and return an appropriately weighted mixture of the results. If
    inverted == -1, then do the same for the inverses of the relation.

    Args:
      rel_specification: a string or NeuralQueryExpression for what to follow.
      inverted: +1 to follow the relations normally, -1 to use inverses

    Returns:
      A NeuralQueryExpression from following the relation.

    Raises:
      RelationNameError: If the relation cannot be found.
    """
    if inverted != +1 and inverted != -1:
      raise ValueError('Inverted (%d) is neither +1 nor -1' % inverted)
    if (isinstance(rel_specification, str) and
        self.context.is_relation(rel_specification)):
      what_to_follow = rel_specification + ('_inverse' if inverted < 0 else '')
      with tf.name_scope('follow_%s' % what_to_follow):
        return self._follow_named_rel(rel_specification, inverted)
    elif isinstance(rel_specification, NeuralQueryExpression):
      return self._follow_relation_set(rel_specification, inverted)
    else:
      raise RelationNameError(
          str(rel_specification), 'Illegal rel_specification.') 
Example #10
Source File: payoff.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def _put_valuer(sample_paths, time_index, strike_price, dtype=None, name=None):
  """Produces a callable from samples to payoff of a simple basket put option.

  Args:
    sample_paths: A `Tensor` of either `flaot32` or `float64` dtype and of
      shape `[num_samples, num_times, dim]`.
    time_index: An integer scalar `Tensor` that corresponds to the time
      coordinate at which the basis function is computed.
    strike_price: A `Tensor` of the same `dtype` as `sample_paths` and shape
      `[num_samples, num_strikes]`.
    dtype: Optional `dtype`. Either `tf.float32` or `tf.float64`. The `dtype`
      If supplied, represents the `dtype` for the 'strike_price' as well as
      for the input argument of the output payoff callable.
      Default value: `None`, which means that the `dtype` inferred by TensorFlow
      is used.
    name: Python `str` name prefixed to Ops created by the callable created
      by this function.
      Default value: `None` which is mapped to the default name 'put_valuer'

  Returns:
    A callable from `Tensor` of shape `[num_samples, num_exercise_times, dim]`
    and a scalar `Tensor` representing current time to a `Tensor` of shape
    `[num_samples, num_strikes]`.
  """
  name = name or "put_valuer"
  with tf.name_scope(name):
    strike_price = tf.convert_to_tensor(strike_price, dtype=dtype,
                                        name="strike_price")
    sample_paths = tf.convert_to_tensor(sample_paths, dtype=dtype,
                                        name="sample_paths")
    num_samples, _, dim = sample_paths.shape.as_list()

    slice_sample_paths = tf.slice(sample_paths, [0, time_index, 0],
                                  [num_samples, 1, dim])
    slice_sample_paths = tf.squeeze(slice_sample_paths, 1)
    average = tf.math.reduce_mean(slice_sample_paths, axis=-1, keepdims=True)
    return tf.nn.relu(strike_price - average) 
Example #11
Source File: __init__.py    From language with Apache License 2.0 5 votes vote down vote up
def _follow_relation_set(self, rel_expr,
                           inverted):
    """Follow a relation group.

    Args:
      rel_expr: A NeuralQueryExpression for what to follow.
      inverted: +1 to follow the relations normally, -1 to use inverses  This is
        a macro, which expands to an expression that computes a weighted set of
        objects obtained by following the relations associated with rel_expr, or
        their inverses if inverted == -1.

    Returns:
      A NeuralQueryExpression

    Raises:
      RelationNameError: If the type of the expression is not a relation group.
    """
    if not self.context.is_group(rel_expr.type_name):
      raise RelationNameError(rel_expr.type_name,
                              'Expression type is not a relation group.')
    g = self.context.get_group(rel_expr.type_name)
    if inverted == +1:
      with tf.name_scope('follow_group_%s' % rel_expr.type_name):
        return (self.follow(g.subject_rel, -1) * \
                rel_expr.follow(g.relation_rel, -1)).follow(g.object_rel)
    else:
      with tf.name_scope('follow_group_%s_inverse' % rel_expr.type_name):
        return (self.follow(g.object_rel, -1) * \
                rel_expr.follow(g.relation_rel, -1)).follow(g.subject_rel) 
Example #12
Source File: cap_floor.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def price(self, valuation_date, market, model=None, pricing_context=None,
            name=None):
    """Returns the present value of the Cap/Floor on the valuation date.

    Args:
      valuation_date: A scalar `DateTensor` specifying the date on which
        valuation is being desired.
      market: A namedtuple of type `InterestRateMarket` which contains the
        necessary information for pricing the Cap/Floor.
      model: An optional input of type `InterestRateModelType` to specify which
        model to use for pricing.
        Default value: `None` in which case `LOGNORMAL_RATE` model is used.
      pricing_context: An optional input to provide additional parameters (such
        as model parameters) relevant for pricing.
      name: Python str. The name to give to the ops created by this function.
        Default value: `None` which maps to `"price"`.

    Returns:
      A Rank 1 `Tensor` of real type containing the modeled price of each cap
      (or floor) based on the input market data.

    Raises:
      ValueError: If an unsupported model is supplied to the function.
    """

    model = model or rc.InterestRateModelType.LOGNORMAL_RATE
    name = name or (self._name + '_price')
    with tf.name_scope(name):
      valuation_date = dates.convert_to_date_tensor(valuation_date)
      if model == rc.InterestRateModelType.LOGNORMAL_RATE:
        caplet_prices = self._price_lognormal_rate(valuation_date, market,
                                                   pricing_context)
      else:
        raise ValueError(f'Unsupported model {model}.')

      return tf.math.segment_sum(caplet_prices, self._contract_index) 
Example #13
Source File: overnight_index_linked_futures.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def price(self, valuation_date, market, model=None, name=None):
    """Returns the price of the contract on the valuation date.

    Args:
      valuation_date: A scalar `DateTensor` specifying the date on which
        valuation is being desired.
      market: An object of type `InterestRateMarket` which contains the
        necessary information for pricing the FRA instrument.
      model: Reserved for future use.
      name: Python string. The name to give this op.
        Default value: `None` which maps to `price`.

    Returns:
      A Rank 1 `Tensor` of real type containing the modeled price of each
      futures contract based on the input market data.
    """

    del model, valuation_date

    name = name or (self._name + '_price')
    with tf.name_scope(name):
      reference_curve = market.reference_curve

      df1 = reference_curve.get_discount_factor(self._accrual_start_dates)
      df2 = reference_curve.get_discount_factor(self._accrual_end_dates)

      fwd_rates = (df1 / df2 - 1.) / self._accrual_daycount

      total_accrual = tf.math.segment_sum(self._daycount_fractions,
                                          self._contract_idx)
      if self._averaging_type == rc.AverageType.ARITHMETIC_AVERAGE:

        settlement_rate = tf.math.segment_sum(
            fwd_rates * self._daycount_fractions,
            self._contract_idx) / total_accrual
      else:
        settlement_rate = (tf.math.segment_prod(
            1. + fwd_rates * self._daycount_fractions, self._contract_idx) -
                           1.) / total_accrual

      return 100. * (1. - settlement_rate) 
Example #14
Source File: __init__.py    From language with Apache License 2.0 5 votes vote down vote up
def weighted_by(self, weight_rel_name,
                  category_name):
    """Weight elements in set by confidence in some relationship holding.

    Specifically, weight all elements x in a set by the confidence
    given to the trip weight_rel_name(x,category_name).
    is equivalent to

    x * x.jump_to(category_name,category_type).follow(weight_rel_name,-1)

    where category_type is the appropriate type for, is determined by the
    declaration for weight_rel_name.

    Args:
      weight_rel_name: a string naming a declared KG relation
      category_name: an entity name in the KG

    Returns:
      A NeuralQueryExpression
    """
    self._check_type_compatibility(
        self.context.get_domain(weight_rel_name), self._type_name,
        'weighted_by')
    category_type = self.context.get_range(weight_rel_name)
    with tf.name_scope('weighted_by_%s_%s' % (weight_rel_name, category_name)):
      weight_vector = self.context.one(category_name, category_type).follow(
          weight_rel_name, -1)
      return self.__mul__(weight_vector) 
Example #15
Source File: cashflow_stream.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def price(self, valuation_date, market, model=None, pricing_context=None,
            name=None):
    """Returns the present value of the stream on the valuation date.

    Args:
      valuation_date: A scalar `DateTensor` specifying the date on which
        valuation is being desired.
      market: A namedtuple of type `InterestRateMarket` which contains the
        necessary information for pricing the cashflow stream.
      model: Reserved for future use.
      pricing_context: Additional context relevant for pricing.
      name: Python str. The name to give to the ops created by this function.
        Default value: `None` which maps to 'price'.

    Returns:
      A Rank 1 `Tensor` of real type containing the modeled price of each stream
      based on the input market data.
    """

    del model, pricing_context
    name = name or (self._name + '_price')
    with tf.name_scope(name):
      discount_curve = market.discount_curve
      discount_factors = discount_curve.get_discount_factor(
          self._payment_dates)
      future_cashflows = tf.cast(self._payment_dates >= valuation_date,
                                 dtype=self._dtype)
      cashflow_pvs = self._notional * (
          future_cashflows * self._daycount_fractions * self._coupon_rate *
          discount_factors)
      return tf.math.reduce_sum(
          tf.reshape(cashflow_pvs, (self._batch_size, self._num_cashflows)),
          axis=1) 
Example #16
Source File: cms_swap.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def price(self, valuation_date, market, model=None, pricing_context=None,
            name=None):
    """Returns the present value of the instrument on the valuation date.

    Args:
      valuation_date: A scalar `DateTensor` specifying the date on which
        valuation is being desired.
      market: A namedtuple of type `InterestRateMarket` which contains the
        necessary information for pricing the interest rate swap.
      model: An optional input of type `InterestRateModelType` to specify the
        model to use for `convexity correction` while pricing individual
        swaplets of the cms swap. When `model` is
        `InterestRateModelType.LOGNORMAL_SMILE_CONSISTENT_REPLICATION` or
        `InterestRateModelType.NORMAL_SMILE_CONSISTENT_REPLICATION`, the
        function uses static replication (from lognormal and normal swaption
        implied volatility data respectively) as described in [1]. When `model`
        is `InterestRateModelType.LOGNORMAL_RATE` or
        `InterestRateModelType.NORMAL_RATE`, the function uses analytic
        approximations for the convexity adjustment based on lognormal and
        normal swaption rate dyanmics respectively [1].
        Default value: `None` in which case convexity correction is not used.
      pricing_context: Additional context relevant for pricing.
      name: Python str. The name to give to the ops created by this function.
        Default value: `None` which maps to 'price'.

    Returns:
      A Rank 1 `Tensor` of real type containing the modeled price of each IRS
      contract based on the input market data.

    #### References:
    [1]: Patrick S. Hagan. Convexity conundrums: Pricing cms swaps, caps and
    floors. WILMOTT magazine.
    """

    name = name or (self._name + '_price')
    with tf.name_scope(name):
      return super(CMSSwap, self).price(valuation_date, market, model,
                                        pricing_context, name) 
Example #17
Source File: __init__.py    From language with Apache License 2.0 5 votes vote down vote up
def tf_op(
      self, py_fun):
    """Apply any shape-preserving function to the underlying expression."""
    with tf.name_scope('tf_op'):
      return self.context.as_nql(py_fun(self.tf), self._type_name) 
Example #18
Source File: cms_swap.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def __init__(self,
               start_date,
               end_date,
               coupon_spec,
               dtype=None,
               name=None):
    """Initialize a batch of CMS cashflow streams.

    Args:
      start_date: A rank 1 `DateTensor` specifying the starting dates of the
        accrual of the first coupon of the cashflow stream. The shape of the
        input correspond to the numbercof streams being created.
      end_date: A rank 1 `DateTensor` specifying the end dates for accrual of
        the last coupon in each cashflow stream. The shape of the input should
        be the same as that of `start_date`.
      coupon_spec: A list of `CMSCouponSpecs` specifying the details of the
        coupon payment for the cashflow stream. The length of the list should
        be the same as the number of streams being created. Each coupon within
        the list must have the same daycount_convention and businessday_rule.
      dtype: `tf.Dtype`. If supplied the dtype for the real variables or ops
        either supplied to the FloatingCashflowStream object or created by the
        object.
        Default value: None which maps to the default dtype inferred by
        TensorFlow.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'floating_cashflow_stream'.
    """

    super(CMSCashflowStream, self).__init__()
    self._name = name or 'cms_cashflow_stream'

    with tf.name_scope(self._name):
      self._start_date = dates.convert_to_date_tensor(start_date)
      self._end_date = dates.convert_to_date_tensor(end_date)
      self._batch_size = self._start_date.shape[0]
      self._first_coupon_date = None
      self._penultimate_coupon_date = None
      self._dtype = dtype

      self._setup(coupon_spec) 
Example #19
Source File: swaption.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def __init__(self,
               swap,
               expiry_date=None,
               dtype=None,
               name=None):
    """Initialize a batch of European swaptions.

    Args:
      swap: An instance of `InterestRateSwap` specifying the interest rate
        swaps underlying the swaptions. The batch size of the swaptions being
        created would be the same as the batch size of the `swap`.
      expiry_date: An optional rank 1 `DateTensor` specifying the expiry dates
        for each swaption. The shape of the input should be the same as the
        batch size of the `swap` input.
        Default value: None in which case the option expity date is the same as
        the start date of each underlying swap.
      dtype: `tf.Dtype`. If supplied the dtype for the real variables or ops
        either supplied to the Swaption object or created by the Swaption
        object.
        Default value: None which maps to the default dtype inferred by
        TensorFlow.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'swaption'.
    """
    self._name = name or 'swaption'

    with tf.name_scope(self._name):
      self._dtype = dtype
      self._expiry_date = dates.convert_to_date_tensor(expiry_date)
      self._swap = swap 
Example #20
Source File: interest_rate_swap.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def price(self, valuation_date, market, model=None, pricing_context=None,
            name=None):
    """Returns the present value of the instrument on the valuation date.

    Args:
      valuation_date: A scalar `DateTensor` specifying the date on which
        valuation is being desired.
      market: A namedtuple of type `InterestRateMarket` which contains the
        necessary information for pricing the interest rate swap.
      model: Reserved for future use.
      pricing_context: Additional context relevant for pricing.
      name: Python str. The name to give to the ops created by this function.
        Default value: `None` which maps to 'price'.

    Returns:
      A Rank 1 `Tensor` of real type containing the modeled price of each IRS
      contract based on the input market data.
    """

    name = name or (self._name + '_price')
    with tf.name_scope(name):
      valuation_date = dates.convert_to_date_tensor(valuation_date)
      pay_cf = self._pay_leg.price(valuation_date, market, model,
                                   pricing_context)
      receive_cf = self._receive_leg.price(valuation_date, market, model,
                                           pricing_context)
      return receive_cf - pay_cf 
Example #21
Source File: uniform_noise.py    From compression with Apache License 2.0 5 votes vote down vote up
def _logsum_expbig_minus_expsmall(big, small):
  """Numerically stable evaluation of `log(exp(big) - exp(small))`.

  This assumes `small <= big` and arguments that can be broadcast against each
  other.

  Arguments:
    big: Floating-point `tf.Tensor`.
    small: Floating-point `tf.Tensor`.

  Returns:
    `tf.Tensor` containing the result.
  """
  with tf.name_scope("logsum_expbig_minus_expsmall"):
    return tf.math.log1p(-tf.exp(small - big)) + big 
Example #22
Source File: uniform_noise.py    From compression with Apache License 2.0 5 votes vote down vote up
def _sample_n(self, n, seed=None):
    with tf.name_scope("transform"):
      n = tf.convert_to_tensor(n, name="n")
      samples = self.base.sample(n, seed=seed)
      return samples + tf.random.uniform(
          tf.shape(samples), minval=-.5, maxval=.5, dtype=samples.dtype) 
Example #23
Source File: multivariate_geometric_brownian_motion.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
def __init__(self,
               dim,
               means=0.0,
               volatilities=1.0,
               corr_matrix=None,
               dtype=None,
               name=None):
    """Initializes the Multivariate Geometric Brownian Motion.

    Args:
      dim: A Python scalar. The dimensionality of the process
      means:  A real `Tensor` of shape broadcastable to `[dim]`.
        Corresponds to the vector of means of the GBM components `X_i`.
      Default value: 0.0.
      volatilities: A `Tensor` of the same `dtype` as `means` and of shape
        broadcastable to `[dim]`. Corresponds to the volatilities of the GBM
        components `X_i`.
        Default value: 1.0.
      corr_matrix: An optional `Tensor` of the same `dtype` as `means` and of
        shape `[dim, dim]`. Correlation of the GBM components `W_i`.
        Default value: `None` which maps to a process with
        independent GBM components `X_i`.
      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
        'multivariate_geometric_brownian_motion'.
    Raises:
      ValueError: If `corr_matrix` is supplied and is not of shape `[dim, dim]`
    """
    self._name = name or "multivariate_geometric_brownian_motion"
    with tf.name_scope(self._name):
      self._means = tf.convert_to_tensor(means, dtype=dtype,
                                         name="means")
      self._dtype = self._means.dtype
      self._vols = tf.convert_to_tensor(volatilities, dtype=self._dtype,
                                        name="volatilities")
      self._dim = dim
      if corr_matrix is None:
        self._corr_matrix = None
      else:
        self._corr_matrix = tf.convert_to_tensor(corr_matrix, dtype=self._dtype,
                                                 name="corr_matrix")
        if self._corr_matrix.shape.as_list() != [dim, dim]:
          raise ValueError("`corr_matrix` must be of shape [{0}, {0}] but is "
                           "of shape {1}".format(
                               dim, self._corr_matrix.shape.as_list())) 
Example #24
Source File: helpers.py    From compression with Apache License 2.0 4 votes vote down vote up
def estimate_tails(func, target, shape, dtype):
  """Estimates approximate tail quantiles.

  This runs a simple Adam iteration to determine tail quantiles. The
  objective is to find an `x` such that:
  ```
  func(x) == target
  ```
  For instance, if `func` is a CDF and the target is a quantile value, this
  would find the approximate location of that quantile. Note that `func` is
  assumed to be monotonic. When each tail estimate has passed the optimal value
  of `x`, the algorithm does 10 additional iterations and then stops.

  This operation is vectorized. The tensor shape of `x` is given by `shape`, and
  `target` must have a shape that is broadcastable to the output of `func(x)`.

  Arguments:
    func: A callable that computes cumulative distribution function, survival
      function, or similar.
    target: The desired target value.
    shape: The shape of the `tf.Tensor` representing `x`.
    dtype: The `tf.dtypes.Dtype` of the computation (and the return value).

  Returns:
    A `tf.Tensor` representing the solution (`x`).
  """
  with tf.name_scope("estimate_tails"):
    dtype = tf.as_dtype(dtype)
    shape = tf.convert_to_tensor(shape, tf.int32)
    target = tf.convert_to_tensor(target, dtype)

    def loop_cond(tails, m, v, count):
      del tails, m, v  # unused
      return tf.reduce_min(count) < 10

    def loop_body(tails, m, v, count):
      with tf.GradientTape(watch_accessed_variables=False) as tape:
        tape.watch(tails)
        loss = abs(func(tails) - target)
      grad = tape.gradient(loss, tails)
      m = .5 * m + .5 * grad  # Adam mean estimate.
      v = .9 * v + .1 * tf.square(grad)  # Adam variance estimate.
      tails -= .5 * m / (tf.sqrt(v) + 1e-7)
      # Start counting when the gradient flips sign (note that this assumes
      # `tails` is initialized to zero).
      count = tf.where(
          tf.math.logical_or(count > 0, tails * grad > 0),
          count + 1, count)
      return tails, m, v, count

    init_tails = tf.zeros(shape, dtype=dtype)
    init_m = tf.zeros(shape, dtype=dtype)
    init_v = tf.ones(shape, dtype=dtype)
    init_count = tf.zeros(shape, dtype=tf.int32)
    return tf.while_loop(
        loop_cond, loop_body, (init_tails, init_m, init_v, init_count),
        back_prop=False)[0] 
Example #25
Source File: daycounts.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
def actual_actual_isda(*,
                       start_date,
                       end_date,
                       schedule_info=None,
                       dtype=None,
                       name=None):
  """Computes the year fraction between the specified dates.

  Computes the year fraction between the dates by dividing the actual number of
  days in a leap year by 366 and the actual number of days in a standard year by
  365.

  When determining whether a leap day is contained in the date range,
  'start_date' is excluded and 'end_date' is included.

  Note that the schedule info is not needed for this convention and is ignored
  if supplied.

  https://en.wikipedia.org/wiki/Day_count_convention#Actual/Actual_ISDA

  Args:
    start_date: A `DateTensor` object of any shape.
    end_date: A `DateTensor` object of compatible shape with `start_date`.
    schedule_info: The schedule info. Ignored for this convention.
    dtype: The dtype of the result. Either `tf.float32` or `tf.float64`. If not
      supplied, `tf.float32` is returned.
    name: Python `str` name prefixed to ops created by this function. If not
      supplied, `actual_actual_isda` is used.

  Returns:
    A real `Tensor` of supplied `dtype` and shape of `start_date`. The year
    fraction between the start and end date as computed by Actual/Actual ISDA
    convention.
  """
  del schedule_info
  with tf.name_scope(name or 'actual_actual_isda'):
    end_date = dt.convert_to_date_tensor(end_date)
    start_date = dt.convert_to_date_tensor(start_date)
    dtype = dtype or tf.float32
    (
        days_in_leap_years,
        days_in_nonleap_years
    ) = du.days_in_leap_and_nonleap_years_between(start_date, end_date)
    # Cast to the target dtype
    days_in_leap_years = tf.cast(days_in_leap_years, dtype=dtype)
    days_in_nonleap_years = tf.cast(days_in_nonleap_years, dtype=dtype)
    return days_in_leap_years / 366 + days_in_nonleap_years / 365 
Example #26
Source File: daycounts.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
def actual_365_actual(*,
                      start_date,
                      end_date,
                      schedule_info=None,
                      dtype=None,
                      name=None):
  """Computes the year fraction between the specified dates.

  The actual/365 actual convention specifies the year fraction between the
  start and end date as the actual number of days between the two dates divided
  365 if no leap day is contained in the date range and 366 otherwise.

  When determining whether a leap day is contained in the date range,
  `start_date` is excluded and `end_date` is included.

  Note that the schedule info is not needed for this convention and is ignored
  if supplied.

  Args:
    start_date: A `DateTensor` object of any shape.
    end_date: A `DateTensor` object of compatible shape with `start_date`.
    schedule_info: The schedule info. Ignored for this convention.
    dtype: The dtype of the result. Either `tf.float32` or `tf.float64`. If not
      supplied, `tf.float32` is returned.
    name: Python `str` name prefixed to ops created by this function. If not
      supplied, `actual_365_actual` is used.

  Returns:
    A real `Tensor` of supplied `dtype` and shape of `start_date`. The year
    fraction between the start and end date as computed by Actual/365 Actual
    convention.
  """
  del schedule_info
  with tf.name_scope(name or 'actual_365_actual'):
    end_date = dt.convert_to_date_tensor(end_date)
    start_date = dt.convert_to_date_tensor(start_date)
    dtype = dtype or tf.constant(0.).dtype
    actual_days = tf.cast(start_date.days_until(end_date), dtype=dtype)
    # Add a day to start_date and end_date so that start_date is excluded and
    # end_date is included.
    day = periods.day()
    leap_days_between = du.leap_days_between(
        start_date=start_date + day, end_date=end_date + day)
    denominator = tf.cast(tf.where(leap_days_between > 0, 366, 365),
                          dtype=dtype)
    return actual_days / denominator 
Example #27
Source File: univariate_geometric_brownian_motion.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
def sample_paths(self,
                   times,
                   initial_state=None,
                   num_samples=1,
                   random_type=None,
                   seed=None,
                   skip=0,
                   name=None):
    """Returns a sample of paths from the process.

    Args:
      times: Rank 1 `Tensor` of positive real values. The times at which the
        path points are to be evaluated.
      initial_state: A `Tensor` of the same `dtype` as `times` and of shape
        broadcastable with `[num_samples]`. Represents the initial state of the
        Ito process.
      Default value: `None` which maps to a initial state of ones.
      num_samples: Positive scalar `int`. The number of paths to draw.
      random_type: Enum value of `RandomType`. The type of (quasi)-random
        number generator to use to generate the paths.
        Default value: None which maps to the standard pseudo-random numbers.
      seed: Seed for the random number generator. The seed is
        only relevant if `random_type` is one of
        `[STATELESS, PSEUDO, HALTON_RANDOMIZED, PSEUDO_ANTITHETIC,
          STATELESS_ANTITHETIC]`. For `PSEUDO`, `PSEUDO_ANTITHETIC` and
        `HALTON_RANDOMIZED` the seed should be an Python integer. For
        `STATELESS` and  `STATELESS_ANTITHETIC `must be supplied as an integer
        `Tensor` of shape `[2]`.
        Default value: `None` which means no seed is set.
      skip: `int32` 0-d `Tensor`. The number of initial points of the Sobol or
        Halton sequence to skip. Used only when `random_type` is 'SOBOL',
        'HALTON', or 'HALTON_RANDOMIZED', otherwise ignored.
        Default value: 0.
      name: Str. The name to give this op.
        Default value: `sample_paths`.

    Returns:
      A `Tensor`s of shape [num_samples, k, 1] where `k` is the size
      of the `times`.
    """
    name = name or (self._name + "_sample_path")
    with tf.name_scope(name):
      times = tf.convert_to_tensor(times, self._dtype)
      if initial_state is None:
        initial_state = tf.zeros([num_samples, 1], dtype=self._dtype,
                                 name="initial_state")
      else:
        initial_state = (
            tf.convert_to_tensor(initial_state, dtype=self._dtype,
                                 name="initial_state")
            + tf.zeros([num_samples, 1], dtype=self._dtype))
      num_requested_times = times.shape[0]
      return self._sample_paths(
          times=times, num_requested_times=num_requested_times,
          initial_state=initial_state,
          num_samples=num_samples, random_type=random_type,
          seed=seed, skip=skip) 
Example #28
Source File: multivariate_geometric_brownian_motion.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
def sample_paths(self,
                   times,
                   initial_state=None,
                   num_samples=1,
                   random_type=None,
                   seed=None,
                   skip=0,
                   name=None):
    """Returns a sample of paths from the process.

    Args:
      times: Rank 1 `Tensor` of positive real values. The times at which the
        path points are to be evaluated.
      initial_state: A `Tensor` of the same `dtype` as `times` and of shape
        broadcastable with `[num_samples, dim]`. Represents the initial state of
        the Ito process.
      Default value: `None` which maps to a initial state of ones.
      num_samples: Positive scalar `int`. The number of paths to draw.
      random_type: Enum value of `RandomType`. The type of (quasi)-random
        number generator to use to generate the paths.
        Default value: None which maps to the standard pseudo-random numbers.
      seed: Seed for the random number generator. The seed is
        only relevant if `random_type` is one of
        `[STATELESS, PSEUDO, HALTON_RANDOMIZED, PSEUDO_ANTITHETIC,
          STATELESS_ANTITHETIC]`. For `PSEUDO`, `PSEUDO_ANTITHETIC` and
        `HALTON_RANDOMIZED` the seed should be an Python integer. For
        `STATELESS` and  `STATELESS_ANTITHETIC `must be supplied as an integer
        `Tensor` of shape `[2]`.
        Default value: `None` which means no seed is set.
      skip: `int32` 0-d `Tensor`. The number of initial points of the Sobol or
        Halton sequence to skip. Used only when `random_type` is 'SOBOL',
        'HALTON', or 'HALTON_RANDOMIZED', otherwise ignored.
        Default value: 0.
      name: Str. The name to give this op.
        Default value: `sample_paths`.

    Returns:
      A `Tensor`s of shape [num_samples, k, dim] where `k` is the size
      of the `times`.
    """
    name = name or (self._name + "_sample_path")
    with tf.name_scope(name):
      times = tf.convert_to_tensor(times, self._dtype)
      if initial_state is None:
        initial_state = tf.ones([num_samples, self._dim], dtype=self._dtype,
                                name="initial_state")
      else:
        initial_state = (
            tf.convert_to_tensor(initial_state, dtype=self._dtype,
                                 name="initial_state")
            + tf.zeros([num_samples, 1], dtype=self._dtype))
      # Shape [num_samples, 1, dim]
      initial_state = tf.expand_dims(initial_state, axis=1)
      num_requested_times = times.shape[0]
      return self._sample_paths(
          times=times, num_requested_times=num_requested_times,
          initial_state=initial_state,
          num_samples=num_samples, random_type=random_type,
          seed=seed, skip=skip) 
Example #29
Source File: floating_rate_note.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
def __init__(self,
               settlement_date,
               maturity_date,
               coupon_spec,
               start_date=None,
               first_coupon_date=None,
               penultimate_coupon_date=None,
               holiday_calendar=None,
               dtype=None,
               name=None):
    """Initialize a batch of floating rate notes (FRNs).

    Args:
      settlement_date: A rank 1 `DateTensor` specifying the settlement date of
        the FRNs.
      maturity_date: A rank 1 `DateTensor` specifying the maturity dates of the
        FRNs. The shape of the input should be the same as that of
        `settlement_date`.
      coupon_spec: A list of `FloatCouponSpecs` specifying the coupon payments.
        The length of the list should be the same as the number of FRNs
        being created.
      start_date: An optional `DateTensor` specifying the dates when the
        interest starts to accrue for the coupons. The input can be used to
        specify a forward start date for the coupons. The shape of the input
        correspond to the numbercof instruments being created.
        Default value: None in which case the coupons start to accrue from the
        `settlement_date`.
      first_coupon_date: An optional rank 1 `DateTensor` specifying the dates
        when first coupon will be paid for FRNs with irregular first coupon.
      penultimate_coupon_date: An optional rank 1 `DateTensor` specifying the
        dates when the penultimate coupon (or last regular coupon) will be paid
        for FRNs with irregular last coupon.
      holiday_calendar: An instance of `dates.HolidayCalendar` to specify
        weekends and holidays.
        Default value: None in which case a holiday calendar would be created
        with Saturday and Sunday being the holidays.
      dtype: `tf.Dtype`. If supplied the dtype for the real variables or ops
        either supplied to the bond object or created by the bond object.
        Default value: None which maps to the default dtype inferred by
        TensorFlow.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'floating_rate_note'.
    """
    self._name = name or 'floating_rate_note'

    if holiday_calendar is None:
      holiday_calendar = dates.create_holiday_calendar(
          weekend_mask=dates.WeekendMask.SATURDAY_SUNDAY)

    with tf.name_scope(self._name):
      self._dtype = dtype
      self._settlement_date = dates.convert_to_date_tensor(settlement_date)
      self._maturity_date = dates.convert_to_date_tensor(maturity_date)
      self._holiday_calendar = holiday_calendar
      self._setup(coupon_spec, start_date, first_coupon_date,
                  penultimate_coupon_date) 
Example #30
Source File: bond.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
def __init__(self,
               settlement_date,
               maturity_date,
               coupon_spec,
               start_date=None,
               first_coupon_date=None,
               penultimate_coupon_date=None,
               holiday_calendar=None,
               dtype=None,
               name=None):
    """Initialize a batch of fixed coupon bonds.

    Args:
      settlement_date: A rank 1 `DateTensor` specifying the settlement date of
        the bonds.
      maturity_date: A rank 1 `DateTensor` specifying the maturity dates of the
        bonds. The shape of the input should be the same as that of
        `settlement_date`.
      coupon_spec: A list of `FixedCouponSpecs` specifying the coupon payments.
        The length of the list should be the same as the number of bonds
        being created.
      start_date: An optional `DateTensor` specifying the dates when the
        interest starts to accrue for the coupons. The input can be used to
        specify a forward start date for the coupons. The shape of the input
        correspond to the numbercof instruments being created.
        Default value: None in which case the coupons start to accrue from the
        `settlement_date`.
      first_coupon_date: An optional rank 1 `DateTensor` specifying the dates
        when first coupon will be paid for bonds with irregular first coupon.
      penultimate_coupon_date: An optional rank 1 `DateTensor` specifying the
        dates when the penultimate coupon (or last regular coupon) will be paid
        for bonds with irregular last coupon.
      holiday_calendar: An instance of `dates.HolidayCalendar` to specify
        weekends and holidays.
        Default value: None in which case a holiday calendar would be created
        with Saturday and Sunday being the holidays.
      dtype: `tf.Dtype`. If supplied the dtype for the real variables or ops
        either supplied to the bond object or created by the bond object.
        Default value: None which maps to the default dtype inferred by
        TensorFlow.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'bond'.
    """
    self._name = name or 'bond'

    if holiday_calendar is None:
      holiday_calendar = dates.create_holiday_calendar(
          weekend_mask=dates.WeekendMask.SATURDAY_SUNDAY)

    with tf.name_scope(self._name):
      self._dtype = dtype
      self._settlement_date = dates.convert_to_date_tensor(settlement_date)
      self._maturity_date = dates.convert_to_date_tensor(maturity_date)
      self._holiday_calendar = holiday_calendar
      self._setup(coupon_spec, start_date, first_coupon_date,
                  penultimate_coupon_date)