예제 #1
0
def tensor_repr(fra_data, dtype=None):
    """Creates a tensor representation of the FRA."""
    dtype = dtype or tf.float64
    res = dict()
    res["fixing_date"] = tf.convert_to_tensor(fra_data["fixing_date"],
                                              dtype=tf.int32)
    res["fixed_rate"] = tf.convert_to_tensor(fra_data["fixed_rate"],
                                             dtype=dtype)
    config = fra_data["config"]
    res["config"] = config
    res["batch_names"] = fra_data["batch_names"]
    currency_list = cashflow_streams.to_list(fra_data["currency"])
    discount_curve_type = []
    for currency in currency_list:
        if config is not None:
            if currency in config.discounting_curve:
                discount_curve = config.discounting_curve[currency]
                discount_curve_type.append(discount_curve)
            else:
                risk_free = curve_types_lib.RiskFreeCurve(currency=currency)
                discount_curve_type.append(risk_free)
        else:
            # Default discounting is the risk free curve
            risk_free = curve_types_lib.RiskFreeCurve(currency=currency)
            discount_curve_type.append(risk_free)
    discount_curve_type, mask = cashflow_streams.process_curve_types(
        discount_curve_type)
    res["discount_curve_mask"] = tf.convert_to_tensor(mask, dtype=tf.int32)
    res["discount_curve_type"] = discount_curve_type
    # Get reset frequency
    reset_frequency = tf.convert_to_tensor(fra_data["rate_term"][1], tf.int32)
    res["rate_term"] = {
        "type": fra_data["rate_term"][0],
        "frequency": reset_frequency
    }
    rate_index = cashflow_streams.to_list(fra_data["rate_index"])
    rate_index_curves = []
    for currency, r_ind in zip(currency_list, rate_index):
        rate_index_curves.append(
            curve_types_lib.RateIndexCurve(currency=currency, index=r_ind))
    [rate_index_curves,
     reference_mask] = cashflow_streams.process_curve_types(rate_index_curves)
    res["reference_mask"] = tf.convert_to_tensor(reference_mask, tf.int32)
    res["rate_index_curves"] = rate_index_curves
    # Extract unique rate indices
    res["rate_index"] = [curve.index for curve in rate_index_curves]
    res["notional_amount"] = tf.convert_to_tensor(fra_data["notional_amount"],
                                                  dtype=dtype)
    res["settlement_days"] = tf.convert_to_tensor(fra_data["settlement_days"],
                                                  dtype=tf.int32,
                                                  name="settlement_days")
    res["calendar"] = fra_data["calendar"]
    # Extract unique currencies
    res["currency"] = [curve.currency for curve in discount_curve_type]
    res["daycount_convention"] = fra_data["daycount_convention"]
    res["business_day_convention"] = fra_data["business_day_convention"]
    res["short_position"] = tf.convert_to_tensor(fra_data["short_position"],
                                                 dtype=tf.bool)
    return res
예제 #2
0
def floating_leg_tensor_repr(leg, config, dtype):
    """Creates tensor representation for a floating leg of a swap."""
    res = {}
    coupon_spec = {}
    currency_list = cashflow_streams.to_list(leg.currency)
    discount_curve_type = []
    for currency in currency_list:
        if config is not None:
            if currency in config.discounting_curve:
                discount_curve = config.discounting_curve[currency]
                discount_curve_type.append(discount_curve)
            else:
                risk_free = curve_types_lib.RiskFreeCurve(currency=currency)
                discount_curve_type.append(risk_free)
        else:
            # Default discounting is the risk free curve
            risk_free = curve_types_lib.RiskFreeCurve(currency=currency)
            discount_curve_type.append(risk_free)
    discount_curve_type, mask = cashflow_streams.process_curve_types(
        discount_curve_type)
    res["discount_curve_mask"] = tf.convert_to_tensor(mask, dtype=tf.int32)
    res["discount_curve_type"] = discount_curve_type
    # Get coupon frequency
    coupon_frequency = tf.convert_to_tensor(leg.coupon_frequency[1],
                                            tf.int32,
                                            name="floating_coupon_frequency")
    coupon_spec["coupon_frequency"] = {
        "type": leg.coupon_frequency[0],
        "frequency": coupon_frequency
    }
    # Get reset frequency
    reset_frequency = tf.convert_to_tensor(leg.reset_frequency[1], tf.int32)
    coupon_spec["reset_frequency"] = {
        "type": leg.reset_frequency[0],
        "frequency": reset_frequency
    }
    floating_rate_type = cashflow_streams.to_list(leg.floating_rate_type)
    rate_index_curves = []
    for currency, floating_rate_type in zip(currency_list, floating_rate_type):
        rate_index_curves.append(
            curve_types_lib.RateIndexCurve(currency=currency,
                                           index=floating_rate_type))
    [rate_index_curves,
     reference_mask] = cashflow_streams.process_curve_types(rate_index_curves)
    res["reference_mask"] = tf.convert_to_tensor(reference_mask, tf.int32)
    res["rate_index_curves"] = rate_index_curves
    coupon_spec["notional_amount"] = tf.convert_to_tensor(leg.notional_amount,
                                                          dtype=dtype)
    coupon_spec["settlement_days"] = tf.convert_to_tensor(
        leg.settlement_days, dtype=tf.int32, name="settlement_days")
    coupon_spec["calendar"] = leg.calendar
    coupon_spec["currency"] = [curve.currency for curve in discount_curve_type]
    coupon_spec["daycount_convention"] = leg.daycount_convention
    coupon_spec["businessday_rule"] = leg.businessday_rule
    coupon_spec["floating_rate_type"] = floating_rate_type
    coupon_spec["spread"] = tf.convert_to_tensor(leg.spread, dtype=dtype)
    res["coupon_spec"] = coupon_spec
    return res
예제 #3
0
def tensor_repr(am_option_data: Dict[str, Any],
                dtype: Optional[types.Dtype] = None):
    """Creates a tensor representation of an American option."""
    dtype = dtype or tf.float64
    res = dict()
    res["expiry_date"] = tf.convert_to_tensor(am_option_data["expiry_date"],
                                              dtype=tf.int32,
                                              name="expiry_date")
    am_option_config = am_option_data["config"]
    res["config"] = None
    if am_option_config is not None:
        res["config"] = config_to_dict(am_option_config)
    res["batch_names"] = am_option_data["batch_names"]
    res["is_call_option"] = tf.convert_to_tensor(
        am_option_data["is_call_option"],
        dtype=tf.bool,
        name="is_call_options")
    currency = am_option_data["currency"]
    if not isinstance(currency, (list, tuple)):
        currency = [currency]
    discount_curve_type = []
    for cur in currency:
        if res["config"] is not None:
            if cur in res["config"]["discounting_curve"]:
                discount_curve = res["config"]["discounting_curve"][cur]
                discount_curve_type.append(discount_curve)
            else:
                risk_free = curve_types_lib.RiskFreeCurve(currency=cur)
                discount_curve_type.append(risk_free)
        else:
            # Default discounting is the risk free curve
            risk_free = curve_types_lib.RiskFreeCurve(currency=cur)
            discount_curve_type.append(risk_free)
    discount_curve_type, mask = cashflow_streams.process_curve_types(
        discount_curve_type)
    res["discount_curve_mask"] = tf.convert_to_tensor(mask, dtype=tf.int32)
    res["discount_curve_type"] = discount_curve_type
    # Get equity mask
    equity_list = cashflow_streams.to_list(am_option_data["equity"])
    [
        equity,
        equity_mask,
    ] = equity_utils.process_equities(equity_list)
    res["equity_mask"] = tf.convert_to_tensor(equity_mask, tf.int32)
    res["equity"] = equity
    res["contract_amount"] = tf.convert_to_tensor(
        am_option_data["contract_amount"], dtype=dtype)
    res["strike"] = tf.convert_to_tensor(am_option_data["strike"], dtype=dtype)
    res["calendar"] = am_option_data["calendar"]
    res["currency"] = [curve.currency for curve in discount_curve_type]
    res["business_day_convention"] = am_option_data["business_day_convention"]
    res["short_position"] = tf.convert_to_tensor(
        am_option_data["short_position"], dtype=tf.bool)
    return res
예제 #4
0
def fixed_leg_tensor_repr(leg, config, dtype):
    """Creates tensor representation for a fixed leg of a swap."""
    res = {}
    coupon_spec = {}
    currency_list = cashflow_streams.to_list(leg.currency)
    discount_curve_type = []
    for currency in currency_list:
        if config is not None:
            if currency in config.discounting_curve:
                discount_curve = config.discounting_curve[currency]
                discount_curve_type.append(discount_curve)
            else:
                risk_free = curve_types_lib.RiskFreeCurve(currency=currency)
                discount_curve_type.append(risk_free)
        else:
            # Default discounting is the risk free curve
            risk_free = curve_types_lib.RiskFreeCurve(currency=currency)
            discount_curve_type.append(risk_free)
    discount_curve_type, mask = cashflow_streams.process_curve_types(
        discount_curve_type)
    res["discount_curve_mask"] = tf.convert_to_tensor(mask, dtype=tf.int32)
    res["discount_curve_type"] = discount_curve_type
    coupon_frequency = tf.convert_to_tensor(leg.coupon_frequency[1], tf.int32)
    coupon_spec["coupon_frequency"] = {
        "type": leg.coupon_frequency[0],
        "frequency": coupon_frequency
    }
    coupon_spec["fixed_rate"] = tf.convert_to_tensor(leg.fixed_rate,
                                                     dtype=dtype)
    coupon_spec["notional_amount"] = tf.convert_to_tensor(leg.notional_amount,
                                                          dtype=dtype)
    coupon_spec["settlement_days"] = tf.convert_to_tensor(leg.settlement_days,
                                                          dtype=tf.int32)
    coupon_spec["calendar"] = leg.calendar
    coupon_spec["currency"] = [curve.currency for curve in discount_curve_type]
    coupon_spec["daycount_convention"] = leg.daycount_convention
    coupon_spec["businessday_rule"] = leg.businessday_rule
    res["coupon_spec"] = coupon_spec
    return res
예제 #5
0
    def __init__(self,
                 start_date: Union[dateslib.DateTensor, List[List[int]]],
                 maturity_date: Union[dateslib.DateTensor, List[List[int]]],
                 pay_leg: Union[coupon_specs.FixedCouponSpecs,
                                coupon_specs.FloatCouponSpecs],
                 receive_leg: Union[coupon_specs.FixedCouponSpecs,
                                    coupon_specs.FloatCouponSpecs],
                 pay_leg_schedule_fn=None,
                 pay_leg_schedule=None,
                 receive_leg_schedule_fn=None,
                 receive_leg_schedule=None,
                 config: Union[InterestRateSwapConfig, Dict[str, Any]] = None,
                 batch_names: Optional[tf.Tensor] = None,
                 dtype: Optional[types.Dtype] = None,
                 name: Optional[str] = None):
        """Initializes a batch of IRS contracts.

    Args:
      start_date: A `DateTensor` of `batch_shape` specifying the dates for the
        inception (start of the accrual) of the swap contracts. `batch_shape`
        corresponds to the number of instruments being created.
      maturity_date: A `DateTensor` broadcastable with `start_date` specifying
        the maturity dates for each contract.
      pay_leg: An instance of `FixedCouponSpecs` or `FloatCouponSpecs`
        specifying the coupon payments for the payment leg of the swap.
      receive_leg: An instance of `FixedCouponSpecs` or `FloatCouponSpecs`
        specifying the coupon payments for the receiving leg of the swap.
      pay_leg_schedule_fn:  A callable that accepts `start_date`, `end_date`,
        `coupon_frequency`, `settlement_days`, `first_coupon_date`, and
        `penultimate_coupon_date` as `Tensor`s and returns coupon payment
        days. Constructs schedule for the pay leg of the swap.
        Default value: `None`.
      pay_leg_schedule: A `DateTensor` of coupon payment dates for the pay leg.
      receive_leg_schedule_fn:  A callable that accepts `start_date`,
        `end_date`, `coupon_frequency`, `settlement_days`, `first_coupon_date`,
        and `penultimate_coupon_date` as `Tensor`s and returns coupon payment
        days. Constructs schedule for the receive leg of the swap.
        Default value: `None`.
      receive_leg_schedule: A `DateTensor` of coupon payment dates for the
        receive leg.
      config: Optional `InterestRateSwapConfig` or a dictionary.
        If dictionary, then the keys should be the same as the field names of
        `InterestRateSwapConfig`.
      batch_names: A string `Tensor` of instrument names. Should be of shape
        `batch_shape + [2]` specying name and instrument type. This is useful
        when the `from_protos` method is used and the user needs to identify
        which instruments got batched together.
      dtype: `tf.Dtype` of the input and output real `Tensor`s.
        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 'interest_rate_swap'.
    """
        self._name = name or "interest_rate_swap"

        with tf.name_scope(self._name):
            if batch_names is not None:
                self._names = tf.convert_to_tensor(batch_names,
                                                   name="batch_names")
            else:
                self._names = None
            self._dtype = dtype or tf.float64
            self._model = None  # Ignore

            self._config = _process_config(config)
            if isinstance(pay_leg, dict):
                self._discount_curve_type = pay_leg["discount_curve_type"]
                self._start_date = start_date
            else:
                currencies = cashflow_streams.to_list(pay_leg.currency)
                self._discount_curve_type = []
                if pay_leg.currency != receive_leg.currency:
                    raise ValueError(
                        "Pay and receive legs should have the same currency")
                for currency in currencies:
                    if currency in self._config.discounting_curve:
                        discount_curve = self._config.discounting_curve[
                            currency]
                        self._discount_curve_type.append(discount_curve)
                    else:
                        # Default discounting is the risk free curve
                        risk_free = curve_types_lib.RiskFreeCurve(
                            currency=currency)
                        self._discount_curve_type.append(risk_free)
            if isinstance(start_date, tf.Tensor):
                self._start_date = dateslib.dates_from_tensor(start_date)
            else:
                self._start_date = dateslib.convert_to_date_tensor(start_date)
            if isinstance(start_date, tf.Tensor):
                self._maturity_date = dateslib.dates_from_tensor(maturity_date)
            else:
                self._maturity_date = dateslib.convert_to_date_tensor(
                    maturity_date)
            self._pay_leg_schedule_fn = pay_leg_schedule_fn
            self._receive_leg_schedule_fn = receive_leg_schedule_fn
            self._pay_leg_schedule = pay_leg_schedule
            self._receive_leg_schedule = receive_leg_schedule
            self._pay_leg = _setup_leg(self._start_date, self._maturity_date,
                                       self._discount_curve_type, pay_leg,
                                       self._pay_leg_schedule_fn,
                                       self._pay_leg_schedule)
            self._receive_leg = _setup_leg(self._start_date,
                                           self._maturity_date,
                                           self._discount_curve_type,
                                           receive_leg,
                                           self._receive_leg_schedule_fn,
                                           self._receive_leg_schedule)
            self._batch_shape = self._pay_leg.batch_shape
    def __init__(self,
                 short_position: types.BoolTensor,
                 currency: types.CurrencyProtoType,
                 expiry_date: types.DateTensor,
                 equity: List[str],
                 contract_amount: types.FloatTensor,
                 strike: types.FloatTensor,
                 is_call_option: List[bool],
                 business_day_convention: types.BusinessDayConventionProtoType,
                 calendar: types.BankHolidaysProtoType,
                 settlement_days: Optional[types.IntTensor] = 0,
                 american_option_config: AmericanOptionConfig = None,
                 batch_names: Optional[types.StringTensor] = None,
                 dtype: Optional[types.Dtype] = None,
                 name: Optional[str] = None):
        """Initializes the batch of American Equity Options.

    Args:
      short_position: Whether the price is computed for the contract holder.
        Default value: `True` which means that the price is for the contract
        holder.
      currency: The denominated currency.
      expiry_date: A `DateTensor` specifying the dates on which the options
        expire.
      equity: A string name of the underlyings.
      contract_amount: A `Tensor` of real dtype and shape compatible with
        with `short_position`.
      strike: `Tensor` of real dtype and shape compatible with
        with `short_position`. Option strikes.
      is_call_option: A bool `Tensor` of shape compatible with with
        `short_position`. Indicates which options are of call type.
      business_day_convention: A business count convention.
      calendar: A calendar to specify the weekend mask and bank holidays.
      settlement_days: An integer `Tensor` of the shape broadcastable with the
        shape of `fixing_date`.
      american_option_config: Optional `AmericanOptionConfig`.
      batch_names: A string `Tensor` of instrument names. Should be of shape
        `batch_shape + [2]` specying name and instrument type. This is useful
        when the `from_protos` method is used and the user needs to identify
        which instruments got batched together.
      dtype: `tf.Dtype` of the input and output real `Tensor`s.
        Default value: `None` which maps to `float64`.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'AmericanOption'.
    """
        self._name = name or "AmericanOption"
        with tf.name_scope(self._name):
            if batch_names is not None:
                self._names = tf.convert_to_tensor(batch_names,
                                                   name="batch_names")
            else:
                self._names = None
            self._dtype = dtype or tf.float64
            ones = tf.constant(1, dtype=self._dtype)
            self._short_position = tf.where(short_position,
                                            ones,
                                            -ones,
                                            name="short_position")
            self._contract_amount = tf.convert_to_tensor(
                contract_amount, dtype=self._dtype, name="contract_amount")
            self._strike = tf.convert_to_tensor(strike,
                                                dtype=self._dtype,
                                                name="strike")
            self._is_call_option = tf.convert_to_tensor(is_call_option,
                                                        dtype=tf.bool,
                                                        name="strike")
            settlement_days = tf.convert_to_tensor(settlement_days)
            # Business day roll convention and the end of month flag
            roll_convention, eom = market_data_utils.get_business_day_convention(
                business_day_convention)
            # TODO(b/160446193): Calendar is ignored at the moment
            calendar = dateslib.create_holiday_calendar(
                weekend_mask=dateslib.WeekendMask.SATURDAY_SUNDAY)
            self._expiry_date = dateslib.convert_to_date_tensor(expiry_date)
            self._settlement_days = settlement_days
            self._roll_convention = roll_convention
            # Get discount and reference curves
            self._currency = cashflow_streams.to_list(currency)
            self._equity = cashflow_streams.to_list(equity)
            if len(self._currency) != len(self._equity):
                if len(self._currency) > 1 and len(self._equity) > 1:
                    raise ValueError(
                        "Number of currencies and equities should be the same "
                        "but it is {0} and {1}".format(len(self._currency),
                                                       len(self._equity)))
            self._discount_curve_type = []
            self._model = "BS-LSM"  # default pricing model is LSM under Black-Scholes
            self._num_exercise_times = 100
            self._num_samples = 96000
            self._seed = [42, 42]
            if american_option_config is not None:
                self._model = american_option_config.model
                self._seed = american_option_config.seed
                self._num_calibration_samples = None
            for currency in self._currency:
                if american_option_config is not None:
                    [
                        self._num_samples, self._num_exercise_times,
                        self._num_calibration_samples
                    ] = [
                        american_option_config.num_samples,
                        american_option_config.num_exercise_times,
                        american_option_config.num_calibration_samples
                    ]
                    try:
                        discount_curve_type = american_option_config.discounting_curve[
                            currency]
                    except (KeyError, TypeError):
                        discount_curve_type = curve_types.RiskFreeCurve(
                            currency=currency)
                    self._discount_curve_type.append(discount_curve_type)
                else:
                    # Default discounting is the risk free curve
                    risk_free = curve_types.RiskFreeCurve(currency=currency)
                    self._discount_curve_type.append(risk_free)

            # Get masks for discount curves and vol surfaces
            [self._discount_curve_type,
             self._discount_curve_mask] = cashflow_streams.process_curve_types(
                 self._discount_curve_type)

            [
                self._equity,
                self._equity_mask,
            ] = equity_utils.process_equities(self._equity)

            # Get batch shape
            self._batch_shape = tf.shape(strike)
예제 #7
0
    def __init__(self,
                 short_position: types.BoolTensor,
                 currency: types.CurrencyProtoType,
                 fixing_date: types.DateTensor,
                 fixed_rate: types.FloatTensor,
                 notional_amount: types.FloatTensor,
                 daycount_convention: types.DayCountConventionsProtoType,
                 business_day_convention: types.BusinessDayConventionProtoType,
                 calendar: types.BankHolidaysProtoType,
                 rate_term: period_pb2.Period,
                 rate_index: rate_indices.RateIndex,
                 settlement_days: Optional[types.IntTensor] = 0,
                 fra_config: ForwardRateAgreementConfig = None,
                 batch_names: Optional[types.StringTensor] = None,
                 dtype: Optional[types.Dtype] = None,
                 name: Optional[str] = None):
        """Initializes the batch of FRA contracts.

    Args:
      short_position: Whether the contract holder lends or borrows the money.
        Default value: `True` which means that the contract holder lends the
        money at the fixed rate.
      currency: The denominated currency.
      fixing_date: A `DateTensor` specifying the dates on which forward
        rate will be fixed.
      fixed_rate: A `Tensor` of real dtype specifying the fixed rate
        payment agreed at the initiation of the individual contracts. The shape
        should be broadcastable with `fixed_rate`.
      notional_amount: A `Tensor` of real dtype broadcastable with fixed_rate
        specifying the notional amount for each contract. When the notional is
        specified as a scalar, it is assumed that all contracts have the same
        notional.
      daycount_convention: A `DayCountConvention` to determine how cashflows
        are accrued for each contract. Daycount is assumed to be the same for
        all contracts in a given batch.
      business_day_convention: A business count convention.
      calendar: A calendar to specify the weekend mask and bank holidays.
      rate_term: A tenor of the rate (usually Libor) that determines the
        floating cashflow.
      rate_index: A type of the floating leg. An instance of
        `core.rate_indices.RateIndex`.
      settlement_days: An integer `Tensor` of the shape broadcastable with the
        shape of `fixing_date`.
      fra_config: Optional `ForwardRateAgreementConfig`.
      batch_names: A string `Tensor` of instrument names. Should be of shape
        `batch_shape + [2]` specying name and instrument type. This is useful
        when the `from_protos` method is used and the user needs to identify
        which instruments got batched together.
      dtype: `tf.Dtype` of the input and output real `Tensor`s.
        Default value: `None` which maps to `float64`.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'forward_rate_agreement'.
    """
        self._name = name or "forward_rate_agreement"
        with tf.name_scope(self._name):
            if batch_names is not None:
                self._names = tf.convert_to_tensor(batch_names,
                                                   name="batch_names")
            else:
                self._names = None
            self._dtype = dtype or tf.float64
            ones = tf.constant(1, dtype=self._dtype)
            self._short_position = tf.where(short_position,
                                            ones,
                                            -ones,
                                            name="short_position")
            self._notional_amount = tf.convert_to_tensor(
                notional_amount, dtype=self._dtype, name="notional_amount")
            self._fixed_rate = tf.convert_to_tensor(fixed_rate,
                                                    dtype=self._dtype,
                                                    name="fixed_rate")
            settlement_days = tf.convert_to_tensor(settlement_days)
            # Business day roll convention and the end of month flag
            roll_convention, eom = market_data_utils.get_business_day_convention(
                business_day_convention)
            # TODO(b/160446193): Calendar is ignored at the moment
            calendar = dateslib.create_holiday_calendar(
                weekend_mask=dateslib.WeekendMask.SATURDAY_SUNDAY)
            self._fixing_date = dateslib.convert_to_date_tensor(fixing_date)
            self._accrual_start_date = calendar.add_business_days(
                self._fixing_date,
                settlement_days,
                roll_convention=roll_convention)

            self._day_count_fn = market_data_utils.get_daycount_fn(
                daycount_convention)
            period = market_data_utils.get_period(rate_term)
            self._accrual_end_date = calendar.add_period_and_roll(
                self._accrual_start_date,
                period,
                roll_convention=roll_convention)
            if eom:
                self._accrual_end_date = self._accrual_end_date.to_end_of_month(
                )
            self._daycount_fractions = self._day_count_fn(
                start_date=self._accrual_start_date,
                end_date=self._accrual_end_date,
                dtype=self._dtype)
            self._settlement_days = settlement_days
            self._roll_convention = roll_convention
            # Get discount and reference curves
            rate_index_curve = curve_types.RateIndexCurve(currency=currency,
                                                          index=rate_index)
            reference_curve_type = rate_index_curve
            if fra_config is not None:
                try:
                    self._discount_curve_type = fra_config.discounting_index[
                        currency]
                except KeyError:
                    risk_free = curve_types.RiskFreeCurve(currency=currency)
                    self._discount_curve_type = curve_types.CurveType(
                        type=risk_free)
            else:
                # Default discounting is the risk free curve
                risk_free = curve_types.RiskFreeCurve(currency=currency)
                self._discount_curve_type = risk_free
            self._reference_curve_type = reference_curve_type
            self._batch_shape = self._daycount_fractions.shape.as_list()[:-1]
예제 #8
0
    def __init__(self,
                 short_position: types.BoolTensor,
                 currency: types.CurrencyProtoType,
                 fixing_date: types.DateTensor,
                 fixed_rate: types.FloatTensor,
                 notional_amount: types.FloatTensor,
                 daycount_convention: types.DayCountConventionsProtoType,
                 business_day_convention: types.BusinessDayConventionProtoType,
                 calendar: types.BankHolidaysProtoType,
                 rate_term: period_pb2.Period,
                 rate_index: rate_indices.RateIndex,
                 settlement_days: Optional[types.IntTensor] = 0,
                 discount_curve_type: curve_types_lib.CurveType = None,
                 discount_curve_mask: types.IntTensor = None,
                 rate_index_curves: curve_types_lib.RateIndexCurve = None,
                 reference_mask: types.IntTensor = None,
                 config: Union[ForwardRateAgreementConfig, Dict[str,
                                                                Any]] = None,
                 batch_names: Optional[types.StringTensor] = None,
                 dtype: Optional[types.Dtype] = None,
                 name: Optional[str] = None):
        """Initializes the batch of FRA contracts.

    Args:
      short_position: Whether the contract holder lends or borrows the money.
        Default value: `True` which means that the contract holder lends the
        money at the fixed rate.
      currency: The denominated currency.
      fixing_date: A `DateTensor` specifying the dates on which forward
        rate will be fixed.
      fixed_rate: A `Tensor` of real dtype specifying the fixed rate
        payment agreed at the initiation of the individual contracts. The shape
        should be broadcastable with `fixed_rate`.
      notional_amount: A `Tensor` of real dtype broadcastable with fixed_rate
        specifying the notional amount for each contract. When the notional is
        specified as a scalar, it is assumed that all contracts have the same
        notional.
      daycount_convention: A `DayCountConvention` to determine how cashflows
        are accrued for each contract. Daycount is assumed to be the same for
        all contracts in a given batch.
      business_day_convention: A business count convention.
      calendar: A calendar to specify the weekend mask and bank holidays.
      rate_term: A tenor of the rate (usually Libor) that determines the
        floating cashflow.
      rate_index: A type of the floating leg. An instance of
        `core.rate_indices.RateIndex`.
      settlement_days: An integer `Tensor` of the shape broadcastable with the
        shape of `fixing_date`.
      discount_curve_type: An optional instance of `CurveType` or a list of
        those. If supplied as a list and `discount_curve_mask` is not supplied,
        the size of the list should be the same as the number of priced
        instruments. Defines discount curves for the instruments.
        Default value: `None`, meaning that discount curves are inferred
        from `currency` and `config`.
      discount_curve_mask: An optional integer `Tensor` of values ranging from
        `0` to `len(discount_curve_type) - 1` and of shape `batch_shape`.
        Identifies a mapping between `discount_curve_type` list and the
        underlying instruments.
        Default value: `None`.
      rate_index_curves: An instance of `RateIndexCurve` or a list of those.
        If supplied as a list and `reference_mask` is not supplid,
        the size of the list should be the same as the number of priced
        instruments. Defines the index curves for each instrument. If not
        supplied, `coupon_spec.floating_rate_type` is used to identify the
        curves.
        Default value: `None`.
      reference_mask: An optional integer `Tensor` of values ranging from
        `0` to `len(rate_index_curves) - 1` and of shape `batch_shape`.
        Identifies a mapping between `rate_index_curves` list and the underlying
        instruments.
        Default value: `None`.
      config: Optional `ForwardRateAgreementConfig` or a dictionary.
        If dictionary, then the keys should be the same as the field names of
        `ForwardRateAgreementConfig`.
      batch_names: A string `Tensor` of instrument names. Should be of shape
        `batch_shape + [2]` specying name and instrument type. This is useful
        when the `from_protos` method is used and the user needs to identify
        which instruments got batched together.
      dtype: `tf.Dtype` of the input and output real `Tensor`s.
        Default value: `None` which maps to `float64`.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'forward_rate_agreement'.
    """
        self._name = name or "forward_rate_agreement"
        with tf.name_scope(self._name):
            if batch_names is not None:
                self._names = tf.convert_to_tensor(batch_names,
                                                   name="batch_names")
            else:
                self._names = None
            self._dtype = dtype or tf.float64
            ones = tf.constant(1, dtype=self._dtype)
            self._short_position = tf.where(short_position,
                                            ones,
                                            -ones,
                                            name="short_position")
            self._notional_amount = tf.convert_to_tensor(
                notional_amount, dtype=self._dtype, name="notional_amount")
            self._fixed_rate = tf.convert_to_tensor(fixed_rate,
                                                    dtype=self._dtype,
                                                    name="fixed_rate")
            settlement_days = tf.convert_to_tensor(settlement_days)
            # Business day roll convention and the end of month flag
            roll_convention, eom = market_data_utils.get_business_day_convention(
                business_day_convention)
            # TODO(b/160446193): Calendar is ignored at the moment
            calendar = dateslib.create_holiday_calendar(
                weekend_mask=dateslib.WeekendMask.SATURDAY_SUNDAY)
            if isinstance(fixing_date, types.IntTensor):
                self._fixing_date = dateslib.dates_from_tensor(fixing_date)
            else:
                self._fixing_date = dateslib.convert_to_date_tensor(
                    fixing_date)
            self._accrual_start_date = calendar.add_business_days(
                self._fixing_date,
                settlement_days,
                roll_convention=roll_convention)

            self._day_count_fn = market_data_utils.get_daycount_fn(
                daycount_convention)
            period = rate_term
            if isinstance(rate_term, period_pb2.Period):
                period = market_data_utils.get_period(rate_term)
            if isinstance(rate_term, dict):
                period = market_data_utils.period_from_dict(rate_term)
            self._accrual_end_date = calendar.add_period_and_roll(
                self._accrual_start_date,
                period,
                roll_convention=roll_convention)
            if eom:
                self._accrual_end_date = self._accrual_end_date.to_end_of_month(
                )
            self._daycount_fractions = self._day_count_fn(
                start_date=self._accrual_start_date,
                end_date=self._accrual_end_date,
                dtype=self._dtype)
            self._settlement_days = settlement_days
            self._roll_convention = roll_convention
            # Get discount and reference curves
            self._currency = cashflow_streams.to_list(currency)
            self._rate_index = cashflow_streams.to_list(rate_index)
            # Get a mask for the reference curves
            if rate_index_curves is None:
                rate_index_curves = []
                if len(self._currency) != len(self._rate_index):
                    raise ValueError(
                        "When rate_index_curves` is not supplied, number of currencies "
                        "and rate indices should be the same `but it is {0} and "
                        "{1}".format(len(self._currency),
                                     len(self._rate_index)))

                for currency, rate_index in zip(self._currency,
                                                self._rate_index):
                    rate_index_curves.append(
                        curve_types_lib.RateIndexCurve(currency=currency,
                                                       index=rate_index))
            [self._reference_curve_type, self._reference_mask
             ] = cashflow_streams.process_curve_types(rate_index_curves,
                                                      reference_mask)
            # Get a mask for the discount curves
            self._config = _process_config(config)
            if discount_curve_type is None:
                curve_list = []
                for currency in self._currency:
                    if currency in self._config.discounting_curve:
                        discount_curve_type = self._config.discounting_curve[
                            currency]
                    else:
                        # Default discounting is the risk free curve
                        discount_curve_type = curve_types_lib.RiskFreeCurve(
                            currency=currency)
                    curve_list.append(discount_curve_type)
            else:
                curve_list = cashflow_streams.to_list(discount_curve_type)

            # Get masks for discount and reference curves
            [self._discount_curve_type, self._mask
             ] = cashflow_streams.process_curve_types(curve_list,
                                                      discount_curve_mask)

            # Get batch shape
            self._batch_shape = self._daycount_fractions.shape.as_list()[:-1]
예제 #9
0
    def __init__(self,
                 start_date: Union[dateslib.DateTensor, List[List[int]]],
                 maturity_date: Union[dateslib.DateTensor, List[List[int]]],
                 pay_leg: Union[coupon_specs.FixedCouponSpecs,
                                coupon_specs.FloatCouponSpecs],
                 receive_leg: Union[coupon_specs.FixedCouponSpecs,
                                    coupon_specs.FloatCouponSpecs],
                 swap_config: InterestRateSwapConfig = None,
                 batch_names: Optional[tf.Tensor] = None,
                 dtype: Optional[types.Dtype] = None,
                 name: Optional[str] = None):
        """Initializes a batch of IRS contracts.

    Args:
      start_date: A `DateTensor` of `batch_shape` specifying the dates for the
        inception (start of the accrual) of the swap contracts. `batch_shape`
        corresponds to the number of instruments being created.
      maturity_date: A `DateTensor` broadcastable with `start_date` specifying
        the maturity dates for each contract.
      pay_leg: An instance of `FixedCouponSpecs` or `FloatCouponSpecs`
        specifying the coupon payments for the payment leg of the swap.
      receive_leg: An instance of `FixedCouponSpecs` or `FloatCouponSpecs`
        specifying the coupon payments for the receiving leg of the swap.
      swap_config: Optional `InterestRateSwapConfig`.
      batch_names: A string `Tensor` of instrument names. Should be of shape
        `batch_shape + [2]` specying name and instrument type. This is useful
        when the `from_protos` method is used and the user needs to identify
        which instruments got batched together.
      dtype: `tf.Dtype` of the input and output real `Tensor`s.
        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 'interest_rate_swap'.
    """
        self._name = name or "interest_rate_swap"

        with tf.name_scope(self._name):
            if batch_names is not None:
                self._names = tf.convert_to_tensor(batch_names,
                                                   name="batch_names")
            else:
                self._names = None
            self._dtype = dtype or tf.float64
            self._model = None  # Ignore

            currencies = cashflow_streams.to_list(pay_leg.currency)
            self._discount_curve_type = []
            if pay_leg.currency != receive_leg.currency:
                raise ValueError(
                    "Pay and receive legs should have the same currency")
            for currency in currencies:
                if swap_config is not None:
                    try:
                        discount_curve = swap_config.discounting_curve[
                            currency]
                        self._discount_curve_type.append(discount_curve)
                    except KeyError:
                        risk_free = curve_types_lib.RiskFreeCurve(
                            currency=currency)
                        self._discount_curve_type.append(risk_free)
                else:
                    # Default discounting is the risk free curve
                    risk_free = curve_types_lib.RiskFreeCurve(
                        currency=currency)
                    self._discount_curve_type.append(risk_free)
            self._start_date = dateslib.convert_to_date_tensor(start_date)
            self._maturity_date = dateslib.convert_to_date_tensor(
                maturity_date)
            self._pay_leg = self._setup_leg(pay_leg)
            self._receive_leg = self._setup_leg(receive_leg)
            if self._receive_leg.batch_shape != self._pay_leg.batch_shape:
                raise ValueError(
                    "Batch shapes of pay and receive legs should be the "
                    "same.")
            self._batch_shape = self._pay_leg.batch_shape
  def __init__(self,
               short_position: types.BoolTensor,
               currency: Union[types.CurrencyProtoType,
                               List[types.CurrencyProtoType]],
               expiry_date: types.DateTensor,
               equity: List[str],
               contract_amount: types.FloatTensor,
               strike: types.FloatTensor,
               is_call_option: List[bool],
               business_day_convention: types.BusinessDayConventionProtoType,
               calendar: types.BankHolidaysProtoType,
               settlement_days: Optional[types.IntTensor] = 0,
               discount_curve_type: curve_types_lib.CurveType = None,
               discount_curve_mask: types.IntTensor = None,
               equity_mask: types.IntTensor = None,
               config: Union[AmericanOptionConfig, Dict[str, Any]] = None,
               batch_names: Optional[types.StringTensor] = None,
               dtype: Optional[types.Dtype] = None,
               name: Optional[str] = None):
    """Initializes the batch of American Equity Options.

    Args:
      short_position: Whether the price is computed for the contract holder.
        Default value: `True` which means that the price is for the contract
        holder.
      currency: The denominated currency.
      expiry_date: A `DateTensor` specifying the dates on which the options
        expire.
      equity: A string name of the underlyings.
      contract_amount: A `Tensor` of real dtype and shape compatible with
        with `short_position`.
      strike: `Tensor` of real dtype and shape compatible with
        with `short_position`. Option strikes.
      is_call_option: A bool `Tensor` of shape compatible with with
        `short_position`. Indicates which options are of call type.
      business_day_convention: A business count convention.
      calendar: A calendar to specify the weekend mask and bank holidays.
      settlement_days: An integer `Tensor` of the shape broadcastable with the
        shape of `fixing_date`.
      discount_curve_type: An optional instance of `CurveType` or a list of
        those. If supplied as a list and `discount_curve_mask` is not supplied,
        the size of the list should be the same as the number of priced
        instruments. Defines discount curves for the instruments.
        Default value: `None`, meaning that discount curves are inferred
        from `currency` and `config`.
      discount_curve_mask: An optional integer `Tensor` of values ranging from
        `0` to `len(discount_curve_type) - 1` and of shape `batch_shape`.
        Identifies a mapping between `discount_curve_type` list and the
        underlying instruments.
        Default value: `None`.
      equity_mask: An optional integer `Tensor` of values ranging from
        `0` to `len(equity) - 1` and of shape `batch_shape`. Identifies
        a mapping between `equity` list and the underlying instruments.
        Default value: `None`.
      config: Optional `AmericanOptionConfig` or a dictionary. If dictionary,
        then the keys should be the same as the field names of
        `AmericanOptionConfig`.
      batch_names: A string `Tensor` of instrument names. Should be of shape
        `batch_shape + [2]` specying name and instrument type. This is useful
        when the `from_protos` method is used and the user needs to identify
        which instruments got batched together.
      dtype: `tf.Dtype` of the input and output real `Tensor`s.
        Default value: `None` which maps to `float64`.
      name: Python str. The name to give to the ops created by this class.
        Default value: `None` which maps to 'AmericanOption'.
    """
    self._name = name or "AmericanOption"
    with tf.name_scope(self._name):
      if batch_names is not None:
        self._names = tf.convert_to_tensor(batch_names,
                                           name="batch_names")
      else:
        self._names = None
      self._dtype = dtype or tf.float64
      ones = tf.constant(1, dtype=self._dtype)
      self._short_position = tf.where(
          short_position, ones, -ones, name="short_position")
      self._contract_amount = tf.convert_to_tensor(
          contract_amount, dtype=self._dtype, name="contract_amount")
      self._strike = tf.convert_to_tensor(strike, dtype=self._dtype,
                                          name="strike")
      self._is_call_option = tf.convert_to_tensor(
          is_call_option, dtype=tf.bool, name="strike")
      settlement_days = tf.convert_to_tensor(settlement_days)
      # Business day roll convention and the end of month flag
      roll_convention, eom = market_data_utils.get_business_day_convention(
          business_day_convention)
      # TODO(b/160446193): Calendar is ignored at the moment
      calendar = dateslib.create_holiday_calendar(
          weekend_mask=dateslib.WeekendMask.SATURDAY_SUNDAY)
      if isinstance(expiry_date, types.IntTensor):
        self._expiry_date = dateslib.dates_from_tensor(expiry_date)
      else:
        self._expiry_date = dateslib.convert_to_date_tensor(expiry_date)
      self._settlement_days = settlement_days
      self._roll_convention = roll_convention
      # Get discount and reference curves
      self._currency = cashflow_streams.to_list(currency)
      self._equity = cashflow_streams.to_list(equity)
      if len(self._currency) != len(self._equity):
        if len(self._currency) > 1 and len(self._equity) > 1:
          raise ValueError(
              "Number of currencies and equities should be the same "
              "but it is {0} and {1}".format(len(self._currency),
                                             len(self._equity)))

      config = _process_config(config)
      [
          self._model,
          self._num_samples,
          self._seed,
          self._num_exercise_times,
          self._num_calibration_samples
      ] = _get_config_values(config)

      if discount_curve_type is None:
        discount_curve_type = []
        for currency in self._currency:
          if currency in config.discounting_curve:
            curve_type = config.discounting_curve[currency]
          else:
            # Default discounting curve
            curve_type = curve_types_lib.RiskFreeCurve(
                currency=currency)
          discount_curve_type.append(curve_type)

      # Get masks for discount curves and vol surfaces
      [
          self._discount_curve_type,
          self._discount_curve_mask
      ] = cashflow_streams.process_curve_types(discount_curve_type,
                                               discount_curve_mask)
      [
          self._equity,
          self._equity_mask,
      ] = equity_utils.process_equities(self._equity, equity_mask)
      # Get batch shape
      self._batch_shape = tf.shape(strike)