code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
from typing import Optional, List, Union
from ......_types import OptDateTime
from ...._models import InputFlow
from .._base import UnderlyingDefinition
from ..._instrument_definition import InstrumentDefinition
from .._enums import (
BuySell,
CallPut,
ExerciseStyle,
UnderlyingType,
SettlementType,
)
from . import (
FxDualCurrencyDefinition,
FxAverageInfo,
FxBarrierDefinition,
FxBinaryDefinition,
FxDoubleBarrierDefinition,
FxDoubleBinaryDefinition,
FxForwardStart,
FxUnderlyingDefinition,
)
class FxDefinition(InstrumentDefinition):
"""
Parameters
----------
instrument_tag : str, optional
User defined string to identify the instrument.it can be used to link output
results to the instrument definition. only alphabetic, numeric and '- _.#=@'
characters are supported. optional.
start_date : str or date or datetime or timedelta, optional
Start date of the option
end_date : str or date or datetime or timedelta, optional
The maturity or expiry date of the instrument. the value is expressed in iso
8601 format: yyyy-mm-ddt[hh]:[mm]:[ss]z (e.g., '2021-01-01t00:00:00z').
optional. mandatory for otc eti options and fx options(if tenor is not defined).
if instrumentcode of listed eti option is defined, the value comes from the
instrument reference data.
tenor : str, optional
The code indicating the period between startdate and enddate of the instrument
(e.g. '6m', '1y')
notional_ccy : str, optional
The currency of the instrument's notional amount. the value is expressed in iso
4217 alphabetical format (e.g. 'usd'). if the option is a eurgbp call option,
notionalccy can be expressed in eur or gbp mandatory for fx options.
notional_amount : float, optional
The notional amount of the instrument. if the option is a eurgbp call option,
amount of eur or gbp of the contract
asian_definition : FxOptionAverageInfo, optional
barrier_definition : FxOptionBarrierDefinition, optional
binary_definition : FxOptionBinaryDefinition, optional
buy_sell : BuySell or str, optional
The indicator of the deal side.
call_put : CallPu or strt, optional
The indicator if the option is a call or a put.
The default value is 'call' for otc eti options and fx options.
double_barrier_definition : FxOptionDoubleBarrierDefinition, optional
double_binary_definition : FxOptionDoubleBinaryDefinition, optional
dual_currency_definition : FxDualCurrencyDefinition, optional
exercise_style : ExerciseStyle or str, optional
The option style based on its exercise restrictions.
The default value is 'euro' for otc
eti options and fx options.
forward_start_definition : FxOptionForwardStart, optional
payments : InputFlow, optional
An array of payments
settlement_type : SettlementType or str, optional
The settlement method for options when exercised.
underlying_definition : FxUnderlyingDefinition, optional
underlying_type : UnderlyingType or str, optional
The type of the option based on the underlying asset. Mandatory. No default value applies.
delivery_date : str or date or datetime or timedelta, optional
The date when the underlylng asset is delivered. the value is expressed in iso
8601 format: yyyy-mm-ddt[hh]:[mm]:[ss]z (e.g. '2021-01-01t00:00:00z').
settlement_ccy : str, optional
The currency of the instrument's settlement. the value is expressed in iso 4217
alphabetical format (e.g. 'usd'). if the option is a eurgbp call option,
settlementccy can be expressed in eur or gbp
strike : float, optional
The set price at which the owner of the option can buy or sell the underlying
asset. the value is expressed according to the market convention linked to the
underlying asset. optional. mandatory for otc eti options and fx options. if
instrumentcode of listed eti option is defined, the value comes from the
instrument reference data.
"""
def __init__(
self,
instrument_tag: Optional[str] = None,
start_date: "OptDateTime" = None,
end_date: "OptDateTime" = None,
tenor: Optional[str] = None,
notional_ccy: Optional[str] = None,
notional_amount: Optional[float] = None,
asian_definition: Optional[FxAverageInfo] = None,
barrier_definition: Optional[FxBarrierDefinition] = None,
binary_definition: Optional[FxBinaryDefinition] = None,
buy_sell: Union[BuySell, str] = None,
call_put: Union[CallPut, str] = None,
double_barrier_definition: Optional[FxDoubleBarrierDefinition] = None,
double_binary_definition: Optional[FxDoubleBinaryDefinition] = None,
dual_currency_definition: Optional[FxDualCurrencyDefinition] = None,
exercise_style: Union[ExerciseStyle, str] = None,
forward_start_definition: Optional[FxForwardStart] = None,
payments: Optional[List[InputFlow]] = None,
settlement_type: Union[SettlementType, str] = None,
underlying_definition: Optional[FxUnderlyingDefinition] = None,
underlying_type: Union[UnderlyingType, str] = None,
delivery_date: "OptDateTime" = None,
settlement_ccy: Optional[str] = None,
strike: Optional[float] = None,
**kwargs,
) -> None:
super().__init__(instrument_tag, **kwargs)
self.instrument_tag = instrument_tag
self.start_date = start_date
self.end_date = end_date
self.tenor = tenor
self.notional_ccy = notional_ccy
self.notional_amount = notional_amount
self.asian_definition = asian_definition
self.barrier_definition = barrier_definition
self.binary_definition = binary_definition
self.buy_sell = buy_sell
self.call_put = call_put
self.double_barrier_definition = double_barrier_definition
self.double_binary_definition = double_binary_definition
self.dual_currency_definition = dual_currency_definition
self.exercise_style = exercise_style
self.forward_start_definition = forward_start_definition
self.payments = payments
self.settlement_type = settlement_type
self.underlying_definition = underlying_definition
self.underlying_type = underlying_type
self.delivery_date = delivery_date
self.settlement_ccy = settlement_ccy
self.strike = strike
@property
def asian_definition(self):
"""
:return: object FxOptionAverageInfo
"""
return self._get_object_parameter(FxAverageInfo, "asianDefinition")
@asian_definition.setter
def asian_definition(self, value):
self._set_object_parameter(FxAverageInfo, "asianDefinition", value)
@property
def barrier_definition(self):
"""
:return: object FxOptionBarrierDefinition
"""
return self._get_object_parameter(FxBarrierDefinition, "barrierDefinition")
@barrier_definition.setter
def barrier_definition(self, value):
self._set_object_parameter(FxBarrierDefinition, "barrierDefinition", value)
@property
def binary_definition(self):
"""
:return: object FxOptionBinaryDefinition
"""
return self._get_object_parameter(FxBinaryDefinition, "binaryDefinition")
@binary_definition.setter
def binary_definition(self, value):
self._set_object_parameter(FxBinaryDefinition, "binaryDefinition", value)
@property
def buy_sell(self):
"""
The indicator of the deal side. the possible values are:
- buy: buying the option,
- sell: selling/writing the option. the output amounts calculated with taking
buysell into consideration are returned with a reversed sign when the value
'sell' is used. optional. the default value is 'buy'.
:return: enum BuySell
"""
return self._get_enum_parameter(BuySell, "buySell")
@buy_sell.setter
def buy_sell(self, value):
self._set_enum_parameter(BuySell, "buySell", value)
@property
def call_put(self):
"""
The indicator if the option is a call or a put. the possible values are:
- call: the right to buy the underlying asset,
- put: the right to sell the underlying asset. optional. if instrumentcode of
listed eti option is defined, the value comes from the instrument reference
data.the default value is 'call' for otc eti options and fx options.
:return: enum CallPut
"""
return self._get_enum_parameter(CallPut, "callPut")
@call_put.setter
def call_put(self, value):
self._set_enum_parameter(CallPut, "callPut", value)
@property
def double_barrier_definition(self):
"""
:return: object FxOptionDoubleBarrierDefinition
"""
return self._get_object_parameter(FxDoubleBarrierDefinition, "doubleBarrierDefinition")
@double_barrier_definition.setter
def double_barrier_definition(self, value):
self._set_object_parameter(FxDoubleBarrierDefinition, "doubleBarrierDefinition", value)
@property
def double_binary_definition(self):
"""
:return: object FxOptionDoubleBinaryDefinition
"""
return self._get_object_parameter(FxDoubleBinaryDefinition, "doubleBinaryDefinition")
@double_binary_definition.setter
def double_binary_definition(self, value):
self._set_object_parameter(FxDoubleBinaryDefinition, "doubleBinaryDefinition", value)
@property
def dual_currency_definition(self):
"""
:return: object FxDualCurrencyDefinition
"""
return self._get_object_parameter(FxDualCurrencyDefinition, "dualCurrencyDefinition")
@dual_currency_definition.setter
def dual_currency_definition(self, value):
self._set_object_parameter(FxDualCurrencyDefinition, "dualCurrencyDefinition", value)
@property
def exercise_style(self):
"""
The option style based on its exercise restrictions. the possible values are:
- amer: the owner has the right to exercise on any date before the option
expires,
- euro: the owner has the right to exercise only on enddate,
- berm: the owner has the right to exercise on any of several specified dates
before the option expires. all exercise styles may not apply to certain option
types. optional. if instrumentcode of listed eti option is defined, the value
comes from the instrument reference data. the default value is 'euro' for otc
eti options and fx options.
:return: enum ExerciseStyle
"""
return self._get_enum_parameter(ExerciseStyle, "exerciseStyle")
@exercise_style.setter
def exercise_style(self, value):
self._set_enum_parameter(ExerciseStyle, "exerciseStyle", value)
@property
def forward_start_definition(self):
"""
:return: object FxOptionForwardStart
"""
return self._get_object_parameter(FxForwardStart, "forwardStartDefinition")
@forward_start_definition.setter
def forward_start_definition(self, value):
self._set_object_parameter(FxForwardStart, "forwardStartDefinition", value)
@property
def payments(self):
"""
An array of payments
:return: list InputFlow
"""
return self._get_list_parameter(InputFlow, "payments")
@payments.setter
def payments(self, value):
self._set_list_parameter(InputFlow, "payments", value)
@property
def settlement_type(self):
"""
The settlement method for options when exercised. the possible values are:
- physical(asset): delivering the underlying asset.
- cash: paying out in cash.
:return: enum SettlementType
"""
return self._get_enum_parameter(SettlementType, "settlementType")
@settlement_type.setter
def settlement_type(self, value):
self._set_enum_parameter(SettlementType, "settlementType", value)
@property
def underlying_definition(self):
"""
:return: object FxUnderlyingDefinition
"""
return self._get_object_parameter(UnderlyingDefinition, "underlyingDefinition")
@underlying_definition.setter
def underlying_definition(self, value):
self._set_object_parameter(UnderlyingDefinition, "underlyingDefinition", value)
@property
def underlying_type(self):
"""
The type of the option based on the underlying asset. the possible values are:
- eti: eti(exchanged traded instruments) options,
- fx: fx options. mandatory. no default value applies.
:return: enum UnderlyingType
"""
return self._get_enum_parameter(UnderlyingType, "underlyingType")
@underlying_type.setter
def underlying_type(self, value):
self._set_enum_parameter(UnderlyingType, "underlyingType", value)
@property
def delivery_date(self):
"""
The date when the underlylng asset is delivered. the value is expressed in iso
8601 format: yyyy-mm-ddt[hh]:[mm]:[ss]z (e.g. '2021-01-01t00:00:00z').
:return: str
"""
return self._get_parameter("deliveryDate")
@delivery_date.setter
def delivery_date(self, value):
self._set_datetime_parameter("deliveryDate", value)
@property
def end_date(self):
"""
The maturity or expiry date of the instrument. the value is expressed in iso
8601 format: yyyy-mm-ddt[hh]:[mm]:[ss]z (e.g., '2021-01-01t00:00:00z').
optional. mandatory for otc eti options and fx options(if tenor is not defined).
if instrumentcode of listed eti option is defined, the value comes from the
instrument reference data.
:return: str
"""
return self._get_parameter("endDate")
@end_date.setter
def end_date(self, value):
self._set_datetime_parameter("endDate", value)
@property
def instrument_tag(self):
"""
User defined string to identify the instrument.it can be used to link output
results to the instrument definition. only alphabetic, numeric and '- _.#=@'
characters are supported. optional.
:return: str
"""
return self._get_parameter("instrumentTag")
@instrument_tag.setter
def instrument_tag(self, value):
self._set_parameter("instrumentTag", value)
@property
def notional_amount(self):
"""
The notional amount of the instrument. if the option is a eurgbp call option,
amount of eur or gbp of the contract
:return: float
"""
return self._get_parameter("notionalAmount")
@notional_amount.setter
def notional_amount(self, value):
self._set_parameter("notionalAmount", value)
@property
def notional_ccy(self):
"""
The currency of the instrument's notional amount. the value is expressed in iso
4217 alphabetical format (e.g. 'usd'). if the option is a eurgbp call option,
notionalccy can be expressed in eur or gbp mandatory for fx options.
:return: str
"""
return self._get_parameter("notionalCcy")
@notional_ccy.setter
def notional_ccy(self, value):
self._set_parameter("notionalCcy", value)
@property
def settlement_ccy(self):
"""
The currency of the instrument's settlement. the value is expressed in iso 4217
alphabetical format (e.g. 'usd'). if the option is a eurgbp call option,
settlementccy can be expressed in eur or gbp
:return: str
"""
return self._get_parameter("settlementCcy")
@settlement_ccy.setter
def settlement_ccy(self, value):
self._set_parameter("settlementCcy", value)
@property
def start_date(self):
"""
Start date of the option
:return: str
"""
return self._get_parameter("startDate")
@start_date.setter
def start_date(self, value):
self._set_datetime_parameter("startDate", value)
@property
def strike(self):
"""
The set price at which the owner of the option can buy or sell the underlying
asset. the value is expressed according to the market convention linked to the
underlying asset. optional. mandatory for otc eti options and fx options. if
instrumentcode of listed eti option is defined, the value comes from the
instrument reference data.
:return: float
"""
return self._get_parameter("strike")
@strike.setter
def strike(self, value):
self._set_parameter("strike", value)
@property
def tenor(self):
"""
The code indicating the period between startdate and enddate of the instrument
(e.g. '6m', '1y')
:return: str
"""
return self._get_parameter("tenor")
@tenor.setter
def tenor(self, value):
self._set_parameter("tenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/financial_contracts/option/_fx/_fx_definition.py | 0.940715 | 0.520435 | _fx_definition.py | pypi |
from typing import Optional, Union
from .._enums import DoubleBinaryType
from ..._instrument_definition import ObjectDefinition
class FxDoubleBinaryDefinition(ObjectDefinition):
"""
API endpoint for Financial Contract analytics,
that returns calculations relevant to each contract type.
Parameters
----------
double_binary_type : DoubleBinaryType or str, optional
The type of a double binary option.
payout_amount : float, optional
The payout amount of the option. the default value is '1,000,000'.
payout_ccy : str, optional
The trade currency, which is either a domestic or foreign currency. either
payoutccy or settlementtype can be used at a time. payoutccy="foreign currency"
is equivalent to settlementtype ="physical", and payoutccy="domestic currency"
is equivalent to settlementtype ="cash". the value is expressed in iso 4217
alphabetical format (e.g. 'usd').
trigger_down : float, optional
The lower trigger of the binary option.
trigger_up : float, optional
The upper trigger of the binary option.
"""
def __init__(
self,
double_binary_type: Union[DoubleBinaryType, str] = None,
payout_amount: Optional[float] = None,
payout_ccy: Optional[str] = None,
trigger_down: Optional[float] = None,
trigger_up: Optional[float] = None,
) -> None:
super().__init__()
self.double_binary_type = double_binary_type
self.payout_amount = payout_amount
self.payout_ccy = payout_ccy
self.trigger_down = trigger_down
self.trigger_up = trigger_up
@property
def double_binary_type(self):
"""
The type of a double binary option. the possible values are:
- doublenotouch: the option expires in-the-money if the price of the underlying
asset fails to breach either the lower trigger or the upper trigger at any
time prior to option expiration.
:return: enum DoubleBinaryType
"""
return self._get_enum_parameter(DoubleBinaryType, "doubleBinaryType")
@double_binary_type.setter
def double_binary_type(self, value):
self._set_enum_parameter(DoubleBinaryType, "doubleBinaryType", value)
@property
def payout_amount(self):
"""
The payout amount of the option. the default value is '1,000,000'.
:return: float
"""
return self._get_parameter("payoutAmount")
@payout_amount.setter
def payout_amount(self, value):
self._set_parameter("payoutAmount", value)
@property
def payout_ccy(self):
"""
The trade currency, which is either a domestic or foreign currency. either
payoutccy or settlementtype can be used at a time. payoutccy="foreign currency"
is equivalent to settlementtype ="physical", and payoutccy="domestic currency"
is equivalent to settlementtype ="cash". the value is expressed in iso 4217
alphabetical format (e.g. 'usd').
:return: str
"""
return self._get_parameter("payoutCcy")
@payout_ccy.setter
def payout_ccy(self, value):
self._set_parameter("payoutCcy", value)
@property
def trigger_down(self):
"""
The lower trigger of the binary option.
:return: float
"""
return self._get_parameter("triggerDown")
@trigger_down.setter
def trigger_down(self, value):
self._set_parameter("triggerDown", value)
@property
def trigger_up(self):
"""
The upper trigger of the binary option.
:return: float
"""
return self._get_parameter("triggerUp")
@trigger_up.setter
def trigger_up(self, value):
self._set_parameter("triggerUp", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/financial_contracts/option/_fx/_fx_double_binary_definition.py | 0.954963 | 0.44065 | _fx_double_binary_definition.py | pypi |
from typing import Optional, Union
from ..._instrument_definition import ObjectDefinition
from .._enums import BarrierMode
from ._fx_double_barrier_info import FxDoubleBarrierInfo
class FxDoubleBarrierDefinition(ObjectDefinition):
"""
API endpoint for Financial Contract analytics,
that returns calculations relevant to each contract type.
Parameters
----------
barrier_down : FxDoubleBarrierInfo, optional
Barrier Information for the lower barrier
barrier_mode : BarrierMode or str, optional
Barrier Mode of the double barrier option
barrier_up : FxDoubleBarrierInfo, optional
Barrier Information for the upper barrier
"""
def __init__(
self,
barrier_down: Optional[FxDoubleBarrierInfo] = None,
barrier_mode: Union[BarrierMode, str] = None,
barrier_up: Optional[FxDoubleBarrierInfo] = None,
) -> None:
super().__init__()
self.barrier_down = barrier_down
self.barrier_mode = barrier_mode
self.barrier_up = barrier_up
@property
def barrier_down(self):
"""
Barrier Information for the lower barrier
:return: object FxDoubleBarrierInfo
"""
return self._get_object_parameter(FxDoubleBarrierInfo, "barrierDown")
@barrier_down.setter
def barrier_down(self, value):
self._set_object_parameter(FxDoubleBarrierInfo, "barrierDown", value)
@property
def barrier_mode(self):
"""
Barrier Mode of the double barrier option
:return: enum BarrierMode
"""
return self._get_enum_parameter(BarrierMode, "barrierMode")
@barrier_mode.setter
def barrier_mode(self, value):
self._set_enum_parameter(BarrierMode, "barrierMode", value)
@property
def barrier_up(self):
"""
Barrier Information for the upper barrier
:return: object FxDoubleBarrierInfo
"""
return self._get_object_parameter(FxDoubleBarrierInfo, "barrierUp")
@barrier_up.setter
def barrier_up(self, value):
self._set_object_parameter(FxDoubleBarrierInfo, "barrierUp", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/financial_contracts/option/_fx/_fx_double_barrier_definition.py | 0.946535 | 0.243912 | _fx_double_barrier_definition.py | pypi |
from typing import Optional, Union
from ......_types import OptDateTime
from .._base import BarrierDefinition
from .._enums import (
BarrierMode,
InOrOut,
UpOrDown,
)
class FxBarrierDefinition(BarrierDefinition):
"""
Parameters
----------
barrier_mode : BarrierMode or str, optional
Barrier Mode of the barrier option
in_or_out : InOrOut or str, optional
In/Out property of the barrier option
up_or_down : UpOrDown or str, optional
Up/Down property of the barrier option
level : float, optional
Barrier of the barrier option
rebate_amount : float, optional
Rebate of the barrier option
window_end_date : str or date or datetime or timedelta, optional
Window Start date of the barrier option
window_start_date : str or date or datetime or timedelta, optional
Window Start date of the barrier option
"""
def __init__(
self,
barrier_mode: Union[BarrierMode, str] = None,
in_or_out: Union[InOrOut, str] = None,
up_or_down: Union[UpOrDown, str] = None,
level: Optional[float] = None,
rebate_amount: Optional[float] = None,
window_end_date: "OptDateTime" = None,
window_start_date: "OptDateTime" = None,
) -> None:
super().__init__()
self.barrier_mode = barrier_mode
self.in_or_out = in_or_out
self.up_or_down = up_or_down
self.level = level
self.rebate_amount = rebate_amount
self.window_end_date = window_end_date
self.window_start_date = window_start_date
@property
def barrier_mode(self):
"""
Barrier Mode of the barrier option
:return: enum BarrierMode
"""
return self._get_enum_parameter(BarrierMode, "barrierMode")
@barrier_mode.setter
def barrier_mode(self, value):
self._set_enum_parameter(BarrierMode, "barrierMode", value)
@property
def in_or_out(self):
"""
In/Out property of the barrier option
:return: enum InOrOut
"""
return self._get_enum_parameter(InOrOut, "inOrOut")
@in_or_out.setter
def in_or_out(self, value):
self._set_enum_parameter(InOrOut, "inOrOut", value)
@property
def up_or_down(self):
"""
Up/Down property of the barrier option
:return: enum UpOrDown
"""
return self._get_enum_parameter(UpOrDown, "upOrDown")
@up_or_down.setter
def up_or_down(self, value):
self._set_enum_parameter(UpOrDown, "upOrDown", value)
@property
def level(self):
"""
Barrier of the barrier option
:return: float
"""
return self._get_parameter("level")
@level.setter
def level(self, value):
self._set_parameter("level", value)
@property
def rebate_amount(self):
"""
Rebate of the barrier option
:return: float
"""
return self._get_parameter("rebateAmount")
@rebate_amount.setter
def rebate_amount(self, value):
self._set_parameter("rebateAmount", value)
@property
def window_end_date(self):
"""
Window Start date of the barrier option
:return: str
"""
return self._get_parameter("windowEndDate")
@window_end_date.setter
def window_end_date(self, value):
self._set_datetime_parameter("windowEndDate", value)
@property
def window_start_date(self):
"""
Window Start date of the barrier option
:return: str
"""
return self._get_parameter("windowStartDate")
@window_start_date.setter
def window_start_date(self, value):
self._set_datetime_parameter("windowStartDate", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/financial_contracts/option/_fx/_fx_barrier_definition.py | 0.945387 | 0.219191 | _fx_barrier_definition.py | pypi |
from typing import Optional, Union
from ......_types import OptDateTime
from .._base import Info
from .._enums import (
AverageType,
FixingFrequency,
)
class FxAverageInfo(Info):
"""
Parameters
----------
average_type : AverageType or str, optional
The type of average used to compute.
fixing_frequency : FixingFrequency or str, optional
The fixing's frequency.
average_so_far : float, optional
The value of the average_type
fixing_ric_source : str, optional
The fixing's RIC source. Default value: the first available source RIC of the Fx
Cross Code
fixing_start_date : str or date or datetime or timedelta, optional
The beginning date of the fixing period.
include_holidays : bool, optional
Include the holidays in the list of fixings
include_week_ends : bool, optional
Include the week-ends in the list of fixings
"""
def __init__(
self,
average_type: Union[AverageType, str] = None,
fixing_frequency: Union[FixingFrequency, str] = None,
average_so_far: Optional[float] = None,
fixing_ric: Optional[str] = None,
fixing_start_date: "OptDateTime" = None,
include_holidays: Optional[bool] = None,
include_week_ends: Optional[bool] = None,
) -> None:
super().__init__()
self.average_type = average_type
self.fixing_frequency = fixing_frequency
self.average_so_far = average_so_far
self.fixing_ric = fixing_ric
self.fixing_start_date = fixing_start_date
self.include_holidays = include_holidays
self.include_week_ends = include_week_ends
@property
def average_type(self):
"""
The type of average used to compute. Possible values:
- ArithmeticRate
- ArithmeticStrike
- GeometricRate
- GeometricStrike
:return: enum AverageType
"""
return self._get_enum_parameter(AverageType, "averageType")
@average_type.setter
def average_type(self, value):
self._set_enum_parameter(AverageType, "averageType", value)
@property
def fixing_frequency(self):
"""
The fixing's frequency. Possible values:
- Daily
- Weekly
- BiWeekly
- Monthly
- Quaterly
- SemiAnnual
- Annual
:return: enum FixingFrequency
"""
return self._get_enum_parameter(FixingFrequency, "fixingFrequency")
@fixing_frequency.setter
def fixing_frequency(self, value):
self._set_enum_parameter(FixingFrequency, "fixingFrequency", value)
@property
def average_so_far(self):
"""
The value of the average_type
:return: float
"""
return self._get_parameter("averageSoFar")
@average_so_far.setter
def average_so_far(self, value):
self._set_parameter("averageSoFar", value)
@property
def fixing_ric(self):
"""
The fixing's ric source. default value: the first available source ric of the fx
cross code
:return: str
"""
return self._get_parameter("fixingRic")
@fixing_ric.setter
def fixing_ric(self, value):
self._set_parameter("fixingRic", value)
@property
def fixing_start_date(self):
"""
The beginning date of the fixing period.
:return: str
"""
return self._get_parameter("fixingStartDate")
@fixing_start_date.setter
def fixing_start_date(self, value):
self._set_datetime_parameter("fixingStartDate", value)
@property
def include_holidays(self):
"""
Include the holidays in the list of fixings
:return: bool
"""
return self._get_parameter("includeHolidays")
@include_holidays.setter
def include_holidays(self, value):
self._set_parameter("includeHolidays", value)
@property
def include_week_ends(self):
"""
Include the week-ends in the list of fixings
:return: bool
"""
return self._get_parameter("includeWeekEnds")
@include_week_ends.setter
def include_week_ends(self, value):
self._set_parameter("includeWeekEnds", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/financial_contracts/option/_fx/_fx_average_info.py | 0.953242 | 0.425426 | _fx_average_info.py | pypi |
from typing import TYPE_CHECKING, Optional
from ._enums import (
VolatilityAdjustmentType,
CalibrationType,
VolatilityType,
StrikeType,
)
from ._enums import Axis
from ._enums import InputVolatilityType
from .._enums import PriceSide, TimeStamp
from .._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ...._types import OptStr, OptFloat, OptBool, OptDateTime
class SwaptionCalculationParams(ObjectDefinition):
# new name VolatilityCubeSurfaceParameters in version 1.0.130
"""
This class property contains the properties that may be used to control the
calculation. It mainly covers dates, market data assumptions (e.g. interpolation),
and pricing model preferences. Some Parameters are common to all volatility surfaces
contracts, while others are specific to a particular type of volatility.
Parameters
----------
input_volatility_type : VolatilityType, optional
User can specify whether calibration is based on normal or lognorma vol. however
it would be preferrable to let the service determine the most appropriate one
volatility_adjustment_type : VolatilityAdjustmentType, optional
Volatility adjustment method applied to caplets surface before stripping. the
default value is 'constantcap'.
x_axis : Axis, optional
The enumerate that specifies the unit for the x axis.
y_axis : Axis, optional
The enumerate that specifies the unit for the y axis.
z_axis : Axis, optional
Specifies the unit for the z axis (e.g. strike, expiry, tenor). this applies to
swaption sabr cube.
market_data_date : DEPRECATED
This attribute doesn't use anymore.
shift_percent : float, optional
Shift applied to calibrated strikes allowing negative rates. the value is
expressed in percentages. the default value is selected based oninstrumentcode.
source : str, optional
Requested volatility data contributor.
stripping_shift_percent : float, optional
Shift value applied to strikes allowing the stripped caplets surface to include
volatility even when some strikes are negative. the value is expressed in
percentages. the default value is '0.0'.
valuation_date : str or date or datetime or timedelta, optional
The date at which the instrument is valued. the value is expressed in iso 8601
format: yyyy-mm-ddt[hh]:[mm]:[ss]z (e.g., '2021-01-01t00:00:00z'). by default,
marketdatadate is used. if marketdatadate is not specified, the default value is
today.
filters : DEPRECATED
This attribute doesn't use anymore.
price_side : PriceSide, optional
Specifies whether bid, ask, mid or settle is used to build the surface. if not
precised, default to mid.
time_stamp : TimeStamp, optional
Define how the timestamp is selected:
- open: the opening value of the valuationdate or if not available the close of
the previous day is used.
- default: the latest snapshot is used when valuationdate is today, the close
price when valuationdate is in the past.
calculation_date : str or date or datetime or timedelta, optional
The date the volatility surface is generated.
calibration_type : CalibrationType, optional
The calibration type defines the solver used during calibration (i.e. sabr model
calibration optimization method). the default value is selected based
oninstrumentcode.
output_volatility_type : VolatilityType, optional
The sabr volatility can be expressed as lognormal volatility (%) or normal
volatility (bp). by default the output volatility type follows the
inputvolatilitytype parameter.
strike_type : StrikeType, optional
The strike axis type of the volatility cube surface. the default value is
'relativepercent'.
beta : float, optional
Sabr beta parameter. the possible values: a number between 0 and 1. the default
value is '0.45'.
include_caplets_volatility : bool, optional
Determines whether the volatility cube is computed from interpolations on
volatility skews, or via atm swaption volatility and caplets volatility. the
default value is true.
use_smart_params : bool, optional
An indicator if a first sabr calibration is used to estimate the model initial
parameters (correlation and volatility of volatility). the possible values are:
true: will use a precalibration to estimate initial parameters, false: will
use an arbitrary initial parameters. the default value is 'false'.
"""
_market_data_date = None
_filters = None
def __init__(
self,
*,
input_volatility_type: Optional[InputVolatilityType] = None,
volatility_adjustment_type: Optional[VolatilityAdjustmentType] = None,
x_axis: Optional[Axis] = None,
y_axis: Optional[Axis] = None,
z_axis: Optional[Axis] = None,
market_data_date=None,
shift_percent: "OptFloat" = None,
source: "OptStr" = None,
stripping_shift_percent: "OptFloat" = None,
valuation_date: "OptDateTime" = None,
filters=None,
price_side: Optional[PriceSide] = None,
time_stamp: Optional[TimeStamp] = None,
calculation_date: "OptDateTime" = None,
calibration_type: Optional[CalibrationType] = None,
output_volatility_type: Optional[VolatilityType] = None,
strike_type: Optional[StrikeType] = None,
beta: "OptFloat" = None,
include_caplets_volatility: "OptBool" = None,
use_smart_params: "OptBool" = None,
):
super().__init__()
self.input_volatility_type = input_volatility_type
self.volatility_adjustment_type = volatility_adjustment_type
self.x_axis = x_axis
self.y_axis = y_axis
self.z_axis = z_axis
self.market_data_date = market_data_date
self.shift_percent = shift_percent
self.source = source
self.stripping_shift_percent = stripping_shift_percent
self.valuation_date = valuation_date
self.filters = filters
self.price_side = price_side
self.time_stamp = time_stamp
self.calculation_date = calculation_date
self.calibration_type = calibration_type
self.output_volatility_type = output_volatility_type
self.strike_type = strike_type
self.beta = beta
self.include_caplets_volatility = include_caplets_volatility
self.use_smart_params = use_smart_params
@property
def input_volatility_type(self):
"""
:return: enum InputVolatilityType
"""
return self._get_enum_parameter(InputVolatilityType, "inputVolatilityType")
@input_volatility_type.setter
def input_volatility_type(self, value):
self._set_enum_parameter(InputVolatilityType, "inputVolatilityType", value)
@property
def volatility_adjustment_type(self):
"""
Volatility Adjustment method for stripping: ConstantCaplet, ConstantCap, ShiftedCap, NormalizedCap, NormalizedCaplet
:return: enum VolatilityAdjustmentType
"""
return self._get_enum_parameter(VolatilityAdjustmentType, "volatilityAdjustmentType")
@volatility_adjustment_type.setter
def volatility_adjustment_type(self, value):
self._set_enum_parameter(VolatilityAdjustmentType, "volatilityAdjustmentType", value)
@property
def x_axis(self):
"""
Specifies the unit for the x axis (e.g. Date, Tenor)
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "xAxis")
@x_axis.setter
def x_axis(self, value):
self._set_enum_parameter(Axis, "xAxis", value)
@property
def y_axis(self):
"""
Specifies the unit for the y axis (e.g. Strike, Delta). This may depend on the asset class.
For Fx Volatility Surface, we support both Delta and Strike.
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "yAxis")
@y_axis.setter
def y_axis(self, value):
self._set_enum_parameter(Axis, "yAxis", value)
@property
def z_axis(self):
"""
Specifies the unit for the z axis (e.g. Strike, Tenor, Expiries). This applies on Ir SABR Volatility Cube.
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "zAxis")
@z_axis.setter
def z_axis(self, value):
self._set_enum_parameter(Axis, "zAxis", value)
@property
def market_data_date(self):
return self._market_data_date
@market_data_date.setter
def market_data_date(self, value):
self._market_data_date = value
@property
def shift_percent(self):
"""
Shift value to use in calibration(Strike/Forward). Default: 0.0
:return: float
"""
return self._get_parameter("shiftPercent")
@shift_percent.setter
def shift_percent(self, value):
self._set_parameter("shiftPercent", value)
@property
def source(self):
"""
Requested volatility data contributor.
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value)
@property
def stripping_shift_percent(self):
"""
Shift value to use in caplets stripping(Strike/Forward). Default: 0.0
:return: float
"""
return self._get_parameter("strippingShiftPercent")
@stripping_shift_percent.setter
def stripping_shift_percent(self, value):
self._set_parameter("strippingShiftPercent", value)
@property
def valuation_date(self):
"""
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_datetime_parameter("valuationDate", value)
@property
def filters(self):
return self._filters
@filters.setter
def filters(self, value):
self._filters = value
@property
def price_side(self):
"""
Specifies whether bid, ask, mid or settle is used to build the surface. if not
precised, default to mid.
:return: enum PriceSide
"""
return self._get_enum_parameter(PriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(PriceSide, "priceSide", value)
@property
def time_stamp(self):
"""
Define how the timestamp is selected:
- open: the opening value of the valuationdate or if not available the close of
the previous day is used.
- default: the latest snapshot is used when valuationdate is today, the close
price when valuationdate is in the past.
:return: enum TimeStamp
"""
return self._get_enum_parameter(TimeStamp, "timeStamp")
@time_stamp.setter
def time_stamp(self, value):
self._set_enum_parameter(TimeStamp, "timeStamp", value)
@property
def calculation_date(self):
"""
The date the volatility surface is generated.
:return: str
"""
return self._get_parameter("calculationDate")
@calculation_date.setter
def calculation_date(self, value):
self._set_datetime_parameter("calculationDate", value)
@property
def calibration_type(self):
"""
The calibration type defines the solver used during calibration (i.e. sabr model
calibration optimization method). the default value is selected based
oninstrumentcode.
:return: enum CalibrationType
"""
return self._get_enum_parameter(CalibrationType, "calibrationType")
@calibration_type.setter
def calibration_type(self, value):
self._set_enum_parameter(CalibrationType, "calibrationType", value)
@property
def output_volatility_type(self):
"""
The sabr volatility can be expressed as lognormal volatility (%) or normal
volatility (bp). by default the output volatility type follows the
inputvolatilitytype parameter.
:return: enum VolatilityType
"""
return self._get_enum_parameter(VolatilityType, "outputVolatilityType")
@output_volatility_type.setter
def output_volatility_type(self, value):
self._set_enum_parameter(VolatilityType, "outputVolatilityType", value)
@property
def strike_type(self):
"""
The strike axis type of the volatility cube surface. the default value is
'relativepercent'.
:return: enum StrikeType
"""
return self._get_enum_parameter(StrikeType, "strikeType")
@strike_type.setter
def strike_type(self, value):
self._set_enum_parameter(StrikeType, "strikeType", value)
@property
def beta(self):
"""
Sabr beta parameter. the possible values: a number between 0 and 1. the default
value is '0.45'.
:return: float
"""
return self._get_parameter("beta")
@beta.setter
def beta(self, value):
self._set_parameter("beta", value)
@property
def include_caplets_volatility(self):
"""
Determines whether the volatility cube is computed from interpolations on
volatility skews, or via atm swaption volatility and caplets volatility. the
default value is true.
:return: bool
"""
return self._get_parameter("includeCapletsVolatility")
@include_caplets_volatility.setter
def include_caplets_volatility(self, value):
self._set_parameter("includeCapletsVolatility", value)
@property
def use_smart_params(self):
"""
An indicator if a first sabr calibration is used to estimate the model initial
parameters (correlation and volatility of volatility). the possible values are:
true: will use a precalibration to estimate initial parameters, false: will
use an arbitrary initial parameters. the default value is 'false'.
:return: bool
"""
return self._get_parameter("useSmartParams")
@use_smart_params.setter
def use_smart_params(self, value):
self._set_parameter("useSmartParams", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_swaption_calculation_params.py | 0.945216 | 0.596374 | _swaption_calculation_params.py | pypi |
from typing import TYPE_CHECKING, Optional
from .._object_definition import ObjectDefinition
from ._enums import DiscountingType
if TYPE_CHECKING:
from ...._types import OptStr
class IIrVolModelDefinition(ObjectDefinition):
# new name CapletsStrippingDefinition version 1.0.130
"""
The definition of the volatility surface.
Parameters
----------
instrument_code : str, optional
The currency of the interest rate volatility model.
discounting_type : DiscountingType, optional
The discounting type of the interest rate volatility model. the default value is
selected based on 'instrumentcode'.
index_name : str, optional
Underlying index name.
reference_caplet_tenor : str, optional
Reference caplet payment or index tenor. ex: 1m, 3m, 6m, 1y.
"""
def __init__(
self,
instrument_code: "OptStr" = None,
discounting_type: Optional[DiscountingType] = None,
index_name: "OptStr" = None,
reference_caplet_tenor: "OptStr" = None,
):
super().__init__()
self.instrument_code = instrument_code
self.discounting_type = discounting_type
self.index_name = index_name
self.reference_caplet_tenor = reference_caplet_tenor
@property
def discounting_type(self):
"""
the discounting type of the IR vol model: OisDiscounting, or BorDiscounting (default)
:return: enum DiscountingType
"""
return self._get_enum_parameter(DiscountingType, "discountingType")
@discounting_type.setter
def discounting_type(self, value):
self._set_enum_parameter(DiscountingType, "discountingType", value)
@property
def instrument_code(self):
"""
The currency of the stripped cap surface, vol cube, or interest rate vol model
:return: str
"""
return self._get_parameter("instrumentCode")
@instrument_code.setter
def instrument_code(self, value):
self._set_parameter("instrumentCode", value)
@property
def reference_caplet_tenor(self):
"""
Reference caplet payment or index tenor. ex: 1m, 3m, 6m, 1y.
:return: str
"""
return self._get_parameter("referenceCapletTenor")
@reference_caplet_tenor.setter
def reference_caplet_tenor(self, value):
self._set_parameter("referenceCapletTenor", value)
@property
def index_name(self):
"""
Underlying index name.
:return: str
"""
return self._get_parameter("indexName")
@index_name.setter
def index_name(self, value):
self._set_parameter("indexName", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_i_ir_vol_model_definition.py | 0.920825 | 0.406567 | _i_ir_vol_model_definition.py | pypi |
from typing import TYPE_CHECKING, Optional
from ._enums import VolatilityAdjustmentType
from ._enums import Axis
from ._enums import InputVolatilityType
from ._models import SurfaceFilters
from .._enums import PriceSide, TimeStamp
from .._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ...._types import OptStr, OptFloat, OptDateTime
class IIrVolModelPricingParameters(ObjectDefinition):
# new name CapletsStrippingSurfaceParameters in version 1.0.130
"""
This class property contains the properties that may be used to control the
calculation. It mainly covers dates, market data assumptions (e.g. interpolation),
and pricing model preferences. Some Parameters are common to all volatility surfaces
contracts, while others are specific to a particular type of volatility.
Parameters
----------
input_volatility_type : InputVolatilityType, optional
User can specify whether calibration is based on normal or lognorma vol. however
it would be preferrable to let the service determine the most appropriate one
volatility_adjustment_type : VolatilityAdjustmentType, optional
Volatility adjustment method applied to caplets surface before stripping. the
default value is 'constantcap'.
x_axis : Axis, optional
The enumerate that specifies the unit for the x axis.
y_axis : Axis, optional
The enumerate that specifies the unit for the y axis.
z_axis : Axis, optional
Specifies the unit for the z axis (e.g. strike, expiry, tenor). this applies to
swaption sabr cube.
market_data_date : DEPRECATED
This attribute doesn't use anymore.
shift_percent : float, optional
Shift applied to calibrated strikes allowing negative rates. the value is
expressed in percentages. the default value is selected based oninstrumentcode
source : str, optional
Requested volatility data contributor.
stripping_shift_percent : float, optional
Shift value applied to strikes allowing the stripped caplets surface to include
volatility even when some strikes are negative. the value is expressed in
percentages. the default value is '0.0'.
valuation_date : str or date or datetime or timedelta, optional
The date at which the instrument is valued. the value is expressed in iso 8601
format: yyyy-mm-ddt[hh]:[mm]:[ss]z (e.g., '2021-01-01t00:00:00z'). by default,
marketdatadate is used. if marketdatadate is not specified, the default value is
today.
filters : SurfaceFilters, optional
price_side : PriceSide, optional
Specifies whether bid, ask, mid or settle is used to build the surface. if not
precised, default to mid.
time_stamp : TimeStamp, optional
Define how the timestamp is selected:
- open: the opening value of the valuationdate or if not available the close of
the previous day is used.
- default: the latest snapshot is used when valuationdate is today, the close
price when valuationdate is in the past.
calculation_date : str or date or datetime or timedelta, optional
The date the volatility surface is generated.
"""
_market_data_date = None
def __init__(
self,
input_volatility_type: Optional[InputVolatilityType] = None,
volatility_adjustment_type: Optional[VolatilityAdjustmentType] = None,
x_axis: Optional[Axis] = None,
y_axis: Optional[Axis] = None,
z_axis: Optional[Axis] = None,
market_data_date=None,
shift_percent: "OptFloat" = None,
source: "OptStr" = None,
stripping_shift_percent: "OptFloat" = None,
valuation_date: "OptDateTime" = None,
filters: Optional[SurfaceFilters] = None,
price_side: Optional[PriceSide] = None,
time_stamp: Optional[TimeStamp] = None,
calculation_date: "OptDateTime" = None,
):
super().__init__()
self.input_volatility_type = input_volatility_type
self.volatility_adjustment_type = volatility_adjustment_type
self.x_axis = x_axis
self.y_axis = y_axis
self.z_axis = z_axis
self.market_data_date = market_data_date
self.shift_percent = shift_percent
self.source = source
self.stripping_shift_percent = stripping_shift_percent
self.valuation_date = valuation_date
self.filters = filters
self.price_side = price_side
self.time_stamp = time_stamp
self.calculation_date = calculation_date
@property
def input_volatility_type(self):
"""
:return: enum InputVolatilityType
"""
return self._get_enum_parameter(InputVolatilityType, "inputVolatilityType")
@input_volatility_type.setter
def input_volatility_type(self, value):
self._set_enum_parameter(InputVolatilityType, "inputVolatilityType", value)
@property
def volatility_adjustment_type(self):
"""
Volatility Adjustment method for stripping: ConstantCaplet, ConstantCap, ShiftedCap, NormalizedCap, NormalizedCaplet
:return: enum VolatilityAdjustmentType
"""
return self._get_enum_parameter(VolatilityAdjustmentType, "volatilityAdjustmentType")
@volatility_adjustment_type.setter
def volatility_adjustment_type(self, value):
self._set_enum_parameter(VolatilityAdjustmentType, "volatilityAdjustmentType", value)
@property
def x_axis(self):
"""
Specifies the unit for the x axis (e.g. Date, Tenor)
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "xAxis")
@x_axis.setter
def x_axis(self, value):
self._set_enum_parameter(Axis, "xAxis", value)
@property
def y_axis(self):
"""
Specifies the unit for the y axis (e.g. Strike, Delta). This may depend on the asset class.
For Fx Volatility Surface, we support both Delta and Strike.
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "yAxis")
@y_axis.setter
def y_axis(self, value):
self._set_enum_parameter(Axis, "yAxis", value)
@property
def z_axis(self):
"""
Specifies the unit for the z axis (e.g. Strike, Tenor, Expiries). This applies on Ir SABR Volatility Cube.
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "zAxis")
@z_axis.setter
def z_axis(self, value):
self._set_enum_parameter(Axis, "zAxis", value)
@property
def market_data_date(self):
return self._market_data_date
@market_data_date.setter
def market_data_date(self, value):
self._market_data_date = value
@property
def shift_percent(self):
"""
Shift value to use in calibration(Strike/Forward). Default: 0.0
:return: float
"""
return self._get_parameter("shiftPercent")
@shift_percent.setter
def shift_percent(self, value):
self._set_parameter("shiftPercent", value)
@property
def source(self):
"""
Requested volatility data contributor.
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value)
@property
def stripping_shift_percent(self):
"""
Shift value to use in caplets stripping(Strike/Forward). Default: 0.0
:return: float
"""
return self._get_parameter("strippingShiftPercent")
@stripping_shift_percent.setter
def stripping_shift_percent(self, value):
self._set_parameter("strippingShiftPercent", value)
@property
def valuation_date(self):
"""
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_datetime_parameter("valuationDate", value)
@property
def filters(self):
"""
:return: object SurfaceFilters
"""
return self._get_object_parameter(SurfaceFilters, "filters")
@filters.setter
def filters(self, value):
self._set_object_parameter(SurfaceFilters, "filters", value)
@property
def price_side(self):
"""
Specifies whether bid, ask, mid or settle is used to build the surface. if not
precised, default to mid.
:return: enum PriceSide
"""
return self._get_enum_parameter(PriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(PriceSide, "priceSide", value)
@property
def time_stamp(self):
"""
Define how the timestamp is selected:
- open: the opening value of the valuationdate or if not available the close of
the previous day is used.
- default: the latest snapshot is used when valuationdate is today, the close
price when valuationdate is in the past.
:return: enum TimeStamp
"""
return self._get_enum_parameter(TimeStamp, "timeStamp")
@time_stamp.setter
def time_stamp(self, value):
self._set_enum_parameter(TimeStamp, "timeStamp", value)
@property
def calculation_date(self):
"""
The date the volatility surface is generated.
:return: str
"""
return self._get_parameter("calculationDate")
@calculation_date.setter
def calculation_date(self, value):
self._set_datetime_parameter("calculationDate", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_i_ir_vol_model_pricing_parameters.py | 0.948597 | 0.579995 | _i_ir_vol_model_pricing_parameters.py | pypi |
from typing import Optional
from ...._types import OptDateTime
from .._object_definition import ObjectDefinition
from ._enums import FxVolatilityModel
from ._enums import FxSwapCalculationMethod
from ._enums import PriceSide
from ._enums import TimeStamp
from ._enums import Axis
from ._models import BidAskMid
from ._models import InterpolationWeight
class FxSurfaceParameters(ObjectDefinition):
"""
This class property contains the properties that may be used to control the
calculation. It mainly covers dates, market data assumptions (e.g. interpolation),
and pricing model preferences. Some Parameters are common to all volatility surfaces
contracts, while others are specific to a particular type of volatility.
Parameters
----------
atm_volatility_object : BidAskMid, optional
butterfly10_d_object : BidAskMid, optional
butterfly25_d_object : BidAskMid, optional
domestic_deposit_rate_percent_object : BidAskMid, optional
foreign_deposit_rate_percent_object : BidAskMid, optional
forward_points_object : BidAskMid, optional
fx_spot_object : BidAskMid, optional
fx_swap_calculation_method : FxSwapCalculationMethod, optional
The method used to calculate an outright price or deposit rates.
The possible values are:
FxSwapImpliedFromDeposit: implied FX swap points are computed from deposit
rates,
DepositCcy1ImpliedFromFxSwap: the currency 1 deposit rates are computed
using swap points,
DepositCcy2ImpliedFromFxSwap: the currency 2 deposit rates are computed
using swap points.
implied_volatility_object : BidAskMid, optional
interpolation_weight : InterpolationWeight, optional
price_side : PriceSide, optional
Specifies whether bid, ask, mid or settle is used to build the surface. if not
precised, default to mid.
risk_reversal10_d_object : BidAskMid, optional
risk_reversal25_d_object : BidAskMid, optional
time_stamp : TimeStamp, optional
Define how the timestamp is selected:
- open: the opening value of the valuationdate or if not available the close of
the previous day is used.
- default: the latest snapshot is used when valuationdate is today, the close
price when valuationdate is in the past.
volatility_model : VolatilityModel, optional
The quantitative model used to generate the volatility surface. this may depend
on the asset class. for fx volatility surface, we currently support the svi
model.
x_axis : Axis, optional
Specifies the unit for the x axis (e.g. date, tenor)
y_axis : Axis, optional
Specifies the unit for the y axis (e.g. strike, delta). this may depend on the
asset class. for fx volatility surface, we support both delta and strike.
calculation_date : str or date or datetime or timedelta, optional
The date the volatility surface is generated.
cutoff_time : str, optional
The cutoff time
cutoff_time_zone : str, optional
The cutoff time zone
"""
def __init__(
self,
atm_volatility_object: Optional[BidAskMid] = None,
butterfly10_d_object: Optional[BidAskMid] = None,
butterfly25_d_object: Optional[BidAskMid] = None,
domestic_deposit_rate_percent_object: Optional[BidAskMid] = None,
foreign_deposit_rate_percent_object: Optional[BidAskMid] = None,
forward_points_object: Optional[BidAskMid] = None,
fx_spot_object: Optional[BidAskMid] = None,
fx_swap_calculation_method: Optional[FxSwapCalculationMethod] = None,
implied_volatility_object: Optional[BidAskMid] = None,
interpolation_weight: Optional[InterpolationWeight] = None,
price_side: Optional[PriceSide] = None,
risk_reversal10_d_object: Optional[BidAskMid] = None,
risk_reversal25_d_object: Optional[BidAskMid] = None,
time_stamp: Optional[TimeStamp] = None,
volatility_model: Optional[FxVolatilityModel] = None,
x_axis: Optional[Axis] = None,
y_axis: Optional[Axis] = None,
calculation_date: "OptDateTime" = None,
cutoff_time: Optional[str] = None,
cutoff_time_zone: Optional[str] = None,
):
super().__init__()
self.atm_volatility_object = atm_volatility_object
self.butterfly10_d_object = butterfly10_d_object
self.butterfly25_d_object = butterfly25_d_object
self.domestic_deposit_rate_percent_object = domestic_deposit_rate_percent_object
self.foreign_deposit_rate_percent_object = foreign_deposit_rate_percent_object
self.forward_points_object = forward_points_object
self.fx_spot_object = fx_spot_object
self.fx_swap_calculation_method = fx_swap_calculation_method
self.implied_volatility_object = implied_volatility_object
self.interpolation_weight = interpolation_weight
self.price_side = price_side
self.risk_reversal10_d_object = risk_reversal10_d_object
self.risk_reversal25_d_object = risk_reversal25_d_object
self.time_stamp = time_stamp
self.volatility_model = volatility_model
self.x_axis = x_axis
self.y_axis = y_axis
self.calculation_date = calculation_date
self.cutoff_time = cutoff_time
self.cutoff_time_zone = cutoff_time_zone
@property
def atm_volatility_object(self):
"""
At the money volatility at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "atmVolatilityObject")
@atm_volatility_object.setter
def atm_volatility_object(self, value):
self._set_object_parameter(BidAskMid, "atmVolatilityObject", value)
@property
def butterfly10_d_object(self):
"""
BF 10 Days at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "butterfly10DObject")
@butterfly10_d_object.setter
def butterfly10_d_object(self, value):
self._set_object_parameter(BidAskMid, "butterfly10DObject", value)
@property
def butterfly25_d_object(self):
"""
BF 25 Days at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "butterfly25DObject")
@butterfly25_d_object.setter
def butterfly25_d_object(self, value):
self._set_object_parameter(BidAskMid, "butterfly25DObject", value)
@property
def domestic_deposit_rate_percent_object(self):
"""
Domestic Deposit Rate at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "domesticDepositRatePercentObject")
@domestic_deposit_rate_percent_object.setter
def domestic_deposit_rate_percent_object(self, value):
self._set_object_parameter(BidAskMid, "domesticDepositRatePercentObject", value)
@property
def foreign_deposit_rate_percent_object(self):
"""
Foreign Deposit Rate at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "foreignDepositRatePercentObject")
@foreign_deposit_rate_percent_object.setter
def foreign_deposit_rate_percent_object(self, value):
self._set_object_parameter(BidAskMid, "foreignDepositRatePercentObject", value)
@property
def forward_points_object(self):
"""
Forward Points at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "forwardPointsObject")
@forward_points_object.setter
def forward_points_object(self, value):
self._set_object_parameter(BidAskMid, "forwardPointsObject", value)
@property
def fx_spot_object(self):
"""
Spot Price
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "fxSpotObject")
@fx_spot_object.setter
def fx_spot_object(self, value):
self._set_object_parameter(BidAskMid, "fxSpotObject", value)
@property
def fx_swap_calculation_method(self):
"""
The method we chose to price outrights using or not implied deposits. Possible values are:
FxSwap (compute outrights using swap points),
DepositCcy1ImpliedFromFxSwap (compute currency1 deposits using swap points),
DepositCcy2ImpliedFromFxSwap (compute currency2 deposits using swap points).
Optional. Defaults to 'FxSwap'.
:return: enum FxSwapCalculationMethod
"""
return self._get_enum_parameter(FxSwapCalculationMethod, "fxSwapCalculationMethod")
@fx_swap_calculation_method.setter
def fx_swap_calculation_method(self, value):
self._set_enum_parameter(FxSwapCalculationMethod, "fxSwapCalculationMethod", value)
@property
def implied_volatility_object(self):
"""
Implied Volatility at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "impliedVolatilityObject")
@implied_volatility_object.setter
def implied_volatility_object(self, value):
self._set_object_parameter(BidAskMid, "impliedVolatilityObject", value)
@property
def interpolation_weight(self):
"""
Vol Term Structure Interpolation
:return: object InterpolationWeight
"""
return self._get_object_parameter(InterpolationWeight, "interpolationWeight")
@interpolation_weight.setter
def interpolation_weight(self, value):
self._set_object_parameter(InterpolationWeight, "interpolationWeight", value)
@property
def price_side(self):
"""
Specifies whether bid, ask or mid is used to build the surface.
:return: enum PriceSide
"""
return self._get_enum_parameter(PriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(PriceSide, "priceSide", value)
@property
def risk_reversal10_d_object(self):
"""
RR 10 Days at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "riskReversal10DObject")
@risk_reversal10_d_object.setter
def risk_reversal10_d_object(self, value):
self._set_object_parameter(BidAskMid, "riskReversal10DObject", value)
@property
def risk_reversal25_d_object(self):
"""
RR 25 Days at Expiry
:return: object BidAskMid
"""
return self._get_object_parameter(BidAskMid, "riskReversal25DObject")
@risk_reversal25_d_object.setter
def risk_reversal25_d_object(self, value):
self._set_object_parameter(BidAskMid, "riskReversal25DObject", value)
@property
def time_stamp(self):
"""
Define how the timestamp is selected:
- Open: the opening value of the valuationDate or if not available the close of the previous day is used.
- Default: the latest snapshot is used when valuationDate is today, the close price when valuationDate is in the past.
:return: enum TimeStamp
"""
return self._get_enum_parameter(TimeStamp, "timeStamp")
@time_stamp.setter
def time_stamp(self, value):
self._set_enum_parameter(TimeStamp, "timeStamp", value)
@property
def volatility_model(self):
"""
The quantitative model used to generate the volatility surface. This may depend on the asset class.
For Fx Volatility Surface, we currently support the SVI model.
:return: enum FxVolatilityModel
"""
return self._get_enum_parameter(FxVolatilityModel, "volatilityModel")
@volatility_model.setter
def volatility_model(self, value):
self._set_enum_parameter(FxVolatilityModel, "volatilityModel", value)
@property
def x_axis(self):
"""
Specifies the unit for the x axis (e.g. Date, Tenor)
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "xAxis")
@x_axis.setter
def x_axis(self, value):
self._set_enum_parameter(Axis, "xAxis", value)
@property
def y_axis(self):
"""
Specifies the unit for the y axis (e.g. Strike, Delta). This may depend on the asset class.
For Fx Volatility Surface, we support both Delta and Strike.
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "yAxis")
@y_axis.setter
def y_axis(self, value):
self._set_enum_parameter(Axis, "yAxis", value)
@property
def calculation_date(self):
"""
The date the volatility surface is generated.
:return: str
"""
return self._get_parameter("calculationDate")
@calculation_date.setter
def calculation_date(self, value):
self._set_datetime_parameter("calculationDate", value)
@property
def cutoff_time(self):
"""
The cutoff time
:return: str
"""
return self._get_parameter("cutoffTime")
@cutoff_time.setter
def cutoff_time(self, value):
self._set_parameter("cutoffTime", value)
@property
def cutoff_time_zone(self):
"""
The cutoff time zone
:return: str
"""
return self._get_parameter("cutoffTimeZone")
@cutoff_time_zone.setter
def cutoff_time_zone(self, value):
self._set_parameter("cutoffTimeZone", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_fx_surface_parameters.py | 0.918251 | 0.493103 | _fx_surface_parameters.py | pypi |
import warnings
from dataclasses import dataclass
from typing import Any, Callable, List, TYPE_CHECKING, Tuple
import numpy as np
import pandas as pd
from numpy import iterable
from ._models import Surface
from .._content_provider import CurvesAndSurfacesRequestFactory, get_type_by_axis
from .._enums import Axis
from .._ipa_content_validator import IPAContentValidator
from ..._content_data import Data
from ..._content_data_provider import ContentDataProvider
from ..._error_parser import ErrorParser
from ...._tools import cached_property
from ....delivery._data._data_provider import ValidatorContainer
from ....delivery._data._endpoint_data import EndpointData
from ....delivery._data._response_factory import ResponseFactory
if TYPE_CHECKING:
from ....delivery._data._data_provider import ParsedData
SURFACE_WARNING = "Surface cannot be built for rd.content.ipa.surfaces.swaption."
DF_WARNING = "Dataframe cannot be built for rd.content.ipa.surfaces.swaption."
# ---------------------------------------------------------------------------
# ContentValidator
# ---------------------------------------------------------------------------
class SurfacesContentValidator(IPAContentValidator):
@classmethod
def content_data_status_is_not_error(cls, data: "ParsedData") -> bool:
content_data = data.content_data
if isinstance(content_data.get("data"), list) and content_data.get("status") == "Error":
data.error_codes = content_data.get("code")
data.error_messages = content_data.get("message")
return False
return True
@cached_property
def validators(self) -> List[Callable[["ParsedData"], bool]]:
return [
self.content_data_is_not_none,
self.content_data_status_is_not_error,
self.any_element_have_no_error,
]
# ---------------------------------------------------------------------------
# Data
# ---------------------------------------------------------------------------
def parse_axis(
universe: dict,
x_axis: Axis,
y_axis: Axis,
) -> (np.array, np.array, np.array):
"""
This method parsing the surface into lists row, column and matrix
>>> from refinitiv.data.content import ipa
>>> definition = ipa.surfaces.eti.Definition(
... underlying_definition=ipa.surfaces.eti.EtiSurfaceDefinition(
... instrument_code="BNPP.PA@RIC"
... ),
... surface_parameters=ipa.surfaces.eti.EtiCalculationParams(
... price_side=ipa.surfaces.eti.PriceSide.MID,
... volatility_model=ipa.surfaces.eti.VolatilityModel.SVI,
... x_axis=ipa.surfaces.eti.Axis.STRIKE,
... y_axis=ipa.surfaces.eti.Axis.DATE,
... ),
... surface_tag="1",
... surface_layout=ipa.surfaces.eti.SurfaceLayout(
... format=ipa.surfaces.eti.Format.MATRIX, y_point_count=10
... ),
... )
This example for surface_parameters with
x_axis = Axis.STRIKE and y_axis = Axis.DATE
|--→ column=Y
↓
row=X
>>> surface = universe.get("surface")
>>> surface
... [
... [None, '2021-08-20', '2021-09-17', '2021-12-17', '2022-03-18'],
... ['25.36', 63.76680855, 76.566676686, 514160483847, 45.563136028],
... ['30.432', 56.20802369, 64.051912234, 46.118622487, 41.540289743],
... ['35.504', 49.91436068, 51.916645386, 41.495311424, 37.870408673],
... ]
Parameters
----------
universe : dict
dict with surface
x_axis : Axis
y_axis : Axis
Returns
-------
(np.array, np.array, np.array)
row, column, matrix or x, y, z
Raises
-------
ValueError
If x_axis or y_axis not correct
"""
if not x_axis or not y_axis:
raise ValueError(f"Cannot parse surface without information about x_axis={x_axis} or y_axis={y_axis}")
surface = universe.get("surface")
if surface is None:
# column is ["-2.00", "-1.00", "-0.50"]
column = universe.get("x")
# row is ["1Y", "2Y", "3Y"]
row = universe.get("y")
# universe has z axis too: ["1M", "2M", "3M"]
matrix = []
# z_dimension is [["129.03", "121.85", "123.85"]]
for z_dimension in universe.get("ndimensionalArray", []):
# Y dimension is ["129.03", "121.85", "123.85"]
# X dimension is "129.03"
# matrix is [["129.03", "121.85", "123.85"]]
matrix.extend(z_dimension)
else:
# column is ['2021-08-20', '2021-09-17', '2021-12-17', '2022-03-18', '2022-06-17']
column = surface[0][1:]
row = []
matrix = []
# curve is ['25.36', 63.76680855, 76.566676686, 514160483847, 41.187204258]
for curve in surface[1:]:
# row is '25.36'
row.append(curve[0])
# matrix is [63.76680855, 76.566676686, 514160483847, 41.187204258]
matrix.append(curve[1:])
try:
column = np.array(column, dtype=get_type_by_axis(y_axis))
except ValueError:
column = np.array(column, dtype=object)
try:
row = np.array(row, dtype=get_type_by_axis(x_axis))
except ValueError:
row = np.array(row, dtype=object)
matrix = np.array(matrix, dtype=float)
return row, column, matrix
def create_surfaces(raw, axes_params) -> List[Surface]:
surfaces = []
if raw and axes_params:
for i, universe in enumerate(raw.get("data")):
x_axis, y_axis = axes_params[i]
row, column, matrix = parse_axis(universe, x_axis, y_axis)
surface = Surface(row=row, column=column, matrix=matrix)
surfaces.append(surface)
return surfaces
@dataclass
class BaseData(EndpointData):
_dataframe: "pd.DataFrame" = None
_axes_params: List = None
@property
def df(self):
if self._dataframe is None and self.raw:
data = self.raw.get("data")
if data:
surface = data[0].get("surface")
if isinstance(surface, dict):
data_frame = pd.DataFrame([])
else:
data_frame = pd.DataFrame(data)
data_frame.set_index("surfaceTag", inplace=True)
else:
data_frame = pd.DataFrame([])
if not data_frame.empty:
data_frame = data_frame.convert_dtypes()
self._dataframe = data_frame
return self._dataframe
@dataclass
class OneSurfaceData(BaseData):
_surface: Surface = None
@property
def surface(self) -> Surface:
if self._surface is None:
surfaces = create_surfaces(self.raw, self._axes_params)
self._surface = surfaces[0]
return self._surface
@property
def df(self):
if self._dataframe is None:
data = {x: z for x, z in zip(self.surface.x, self.surface.z)}
if data:
data_frame = pd.DataFrame(data, index=self.surface.y)
else:
data_frame = super().df
if not data_frame.empty:
data_frame.fillna(pd.NA, inplace=True)
data_frame = data_frame.convert_dtypes()
self._dataframe = data_frame
return self._dataframe
@dataclass
class OneSwaptionSurfaceData(Data):
@property
def surface(self):
warnings.warn(SURFACE_WARNING)
return Surface([], [], [[]])
@property
def df(self):
warnings.warn(DF_WARNING)
return pd.DataFrame()
@dataclass
class SurfacesData(BaseData):
_surfaces: List[Surface] = None
@property
def surfaces(self) -> List[Surface]:
if self._surfaces is None:
self._surfaces = create_surfaces(self.raw, self._axes_params)
return self._surfaces
@dataclass
class SwaptionSurfacesData(Data):
@property
def df(self):
warnings.warn(DF_WARNING)
return pd.DataFrame()
@property
def surfaces(self):
warnings.warn(SURFACE_WARNING)
return []
# ---------------------------------------------------------------------------
# ResponseFactory
# ---------------------------------------------------------------------------
def get_surface_parameters(obj):
if hasattr(obj, "_kwargs"):
request_item = obj._kwargs.get("universe")
else:
request_item = obj
return request_item.surface_parameters
def get_names_axis(surface_parameters) -> Tuple[str, str]:
x_axis = surface_parameters._get_enum_parameter(Axis, "xAxis")
y_axis = surface_parameters._get_enum_parameter(Axis, "yAxis")
return x_axis, y_axis
def get_axis_params(obj, axis_params: list = None) -> List[Tuple[str, str]]:
if axis_params is None:
axis_params = []
surface_parameters = get_surface_parameters(obj)
axis_params.append(get_names_axis(surface_parameters))
return axis_params
class SurfaceResponseFactory(ResponseFactory):
def create_data_success(self, raw: Any, **kwargs) -> EndpointData:
return self._do_create_data(raw, **kwargs)
def create_data_fail(self, raw: Any, **kwargs) -> EndpointData:
return self._do_create_data({}, **kwargs)
def _do_create_data(self, raw: Any, universe=None, **kwargs):
if universe:
if iterable(universe):
axes_params = []
for definition in universe:
get_axis_params(definition, axes_params)
return SurfacesData(raw, _axes_params=axes_params)
surface_parameters = get_surface_parameters(universe)
if surface_parameters and all(get_names_axis(surface_parameters)):
axes_params = get_axis_params(universe)
return OneSurfaceData(raw, _axes_params=axes_params)
return BaseData(raw)
class SwaptionSurfaceResponseFactory(SurfaceResponseFactory):
def _do_create_data(self, raw: Any, universe=None, **kwargs):
if universe:
if iterable(universe):
return SwaptionSurfacesData(raw)
surface_parameters = get_surface_parameters(universe)
if surface_parameters and all(get_names_axis(surface_parameters)):
return OneSwaptionSurfaceData(raw)
return BaseData(raw)
# ---------------------------------------------------------------------------
# DataProvider
# ---------------------------------------------------------------------------
surfaces_data_provider = ContentDataProvider(
request=CurvesAndSurfacesRequestFactory(),
response=SurfaceResponseFactory(),
validator=ValidatorContainer(content_validator=SurfacesContentValidator()),
parser=ErrorParser(),
)
swaption_surfaces_data_provider = ContentDataProvider(
request=CurvesAndSurfacesRequestFactory(),
response=SwaptionSurfaceResponseFactory(),
validator=ValidatorContainer(content_validator=SurfacesContentValidator()),
parser=ErrorParser(),
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_surfaces_data_provider.py | 0.791176 | 0.242665 | _surfaces_data_provider.py | pypi |
from typing import TYPE_CHECKING, Optional
from .._object_definition import ObjectDefinition
from ._enums import DiscountingType
if TYPE_CHECKING:
from ...._types import OptStr
class SwaptionSurfaceDefinition(ObjectDefinition):
# new name VolatilityCubeDefinition in version 1.0.130
"""
The definition of the volatility surface.
Parameters
----------
instrument_code : str, optional
The currency of the interest rate volatility model.
discounting_type : DiscountingType, optional
The discounting type of the interest rate volatility model. the default value is
selected based on 'instrumentcode'.
index_name : str, optional
Underlying index name (e.g. 'euribor').
index_tenor : str, optional
Index tenor of the projected zero curve used to calculate swap rates. the
default value is the index tenor associated with the underlying swap structure
(for eur_ab6e, 6m).
underlying_swap_structure : str, optional
Underlying swap structure, eg: eur_ab6e
"""
def __init__(
self,
*,
instrument_code: "OptStr" = None,
discounting_type: Optional[DiscountingType] = None,
index_name: "OptStr" = None,
index_tenor: "OptStr" = None,
underlying_swap_structure: "OptStr" = None,
) -> None:
super().__init__()
self.instrument_code = instrument_code
self.index_name = index_name
self.index_tenor = index_tenor
self.discounting_type = discounting_type
self.underlying_swap_structure = underlying_swap_structure
@property
def discounting_type(self):
"""
The discounting type of the interest rate volatility model. the default value is
selected based on 'instrumentcode'.
:return: enum DiscountingType
"""
return self._get_enum_parameter(DiscountingType, "discountingType")
@discounting_type.setter
def discounting_type(self, value):
self._set_enum_parameter(DiscountingType, "discountingType", value)
@property
def index_name(self):
"""
Underlying index name (e.g. 'euribor').
:return: str
"""
return self._get_parameter("indexName")
@index_name.setter
def index_name(self, value):
self._set_parameter("indexName", value)
@property
def index_tenor(self):
"""
Index tenor of the projected zero curve used to calculate swap rates. the
default value is the index tenor associated with the underlying swap structure
(for eur_ab6e, 6m).
:return: str
"""
return self._get_parameter("indexTenor")
@index_tenor.setter
def index_tenor(self, value):
self._set_parameter("indexTenor", value)
@property
def instrument_code(self):
"""
The currency of the interest rate volatility model.
:return: str
"""
return self._get_parameter("instrumentCode")
@instrument_code.setter
def instrument_code(self, value):
self._set_parameter("instrumentCode", value)
@property
def underlying_swap_structure(self):
"""
Underlying swap structure, eg: eur_ab6e
:return: str
"""
return self._get_parameter("underlyingSwapStructure")
@underlying_swap_structure.setter
def underlying_swap_structure(self, value):
self._set_parameter("underlyingSwapStructure", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_swaption_surface_definition.py | 0.955672 | 0.483587 | _swaption_surface_definition.py | pypi |
from typing import Optional, TYPE_CHECKING, Iterable
from ._enums import Axis
from ._enums import EtiInputVolatilityType
from ._enums import MoneynessType
from ._enums import PriceSide
from ._enums import TimeStamp
from ._enums import VolatilityModel
from ._models import MoneynessWeight
from ._models import SurfaceFilters
from .._object_definition import ObjectDefinition
from ...._tools import try_copy_to_list
if TYPE_CHECKING:
from ...._types import OptBool, OptDateTime
class EtiSurfaceParameters(ObjectDefinition):
"""
This class property contains the properties that may be used to control the
calculation. It mainly covers dates, market data assumptions (e.g. interpolation),
and pricing model preferences. Some Parameters are common to all volatility surfaces
contracts, while others are specific to a particular type of volatility.
Parameters
----------
filters : SurfaceFilters, optional
The parameters of options that should be used to construct the
volatility surface.
input_volatility_type : InputVolatilityType, optional
Specifies the type of volatility used as an input of the model (calculated
implied volatility, settlement)
- settle: [deprecated] the service uses the settlement volatility to build the
volatility surface
- quoted: the service uses the quoted volatility to build the volatility surface
- implied: the service internally calculates implied volatilities for the option
universe before building the surface default value is "implied".
moneyness_type : MoneynessType, optional
The enumerate that specifies the moneyness type to use for calibration.
- spot
- fwd
- sigma optional. default value is "spot".
price_side : PriceSide, optional
Specifies whether bid, ask or mid is used to build the surface.
time_stamp : TimeStamp, optional
Define how the timestamp is selected:
- open: the opening value of the valuationdate or if not available the close of
the previous day is used.
- default: the latest snapshot is used when valuationdate is today, the close
price when valuationdate is in the past.
volatility_model : VolatilityModel, optional
The quantitative model used to generate the volatility surface. this may depend
on the asset class.
weights : MoneynessWeight, optional
The list of calibration weights that should be applied to different
MoneynessWeight.
x_axis : Axis, optional
Specifies the unit for the x axis (e.g. date, tenor)
y_axis : Axis, optional
Specifies the unit for the y axis (e.g. strike, delta). this may depend on the
asset class. for fx volatility surface, we support both delta and strike.
calculation_date : str or date or datetime or timedelta, optional
The date the volatility surface is generated.
svi_alpha_extrapolation : bool, optional
Svi alpha extrapolation for building the surface default value : true
"""
def __init__(
self,
filters: Optional[SurfaceFilters] = None,
input_volatility_type: Optional[EtiInputVolatilityType] = None,
moneyness_type: Optional[MoneynessType] = None,
price_side: Optional[PriceSide] = None,
time_stamp: Optional[TimeStamp] = None,
volatility_model: Optional[VolatilityModel] = None,
weights: Optional[Iterable[MoneynessWeight]] = None,
x_axis: Optional[Axis] = None,
y_axis: Optional[Axis] = None,
calculation_date: "OptDateTime" = None,
svi_alpha_extrapolation: "OptBool" = None,
):
super().__init__()
self.filters = filters
self.input_volatility_type = input_volatility_type
self.moneyness_type = moneyness_type
self.price_side = price_side
self.time_stamp = time_stamp
self.volatility_model = volatility_model
self.weights = try_copy_to_list(weights)
self.x_axis = x_axis
self.y_axis = y_axis
self.calculation_date = calculation_date
self.svi_alpha_extrapolation = svi_alpha_extrapolation
@property
def filters(self):
"""
The details of the filtering
:return: object SurfaceFilters
"""
return self._get_object_parameter(SurfaceFilters, "filters")
@filters.setter
def filters(self, value):
self._set_object_parameter(SurfaceFilters, "filters", value)
@property
def input_volatility_type(self):
"""
Specifies the type of volatility used as an input of the model (calculated Implied Volatility, Settlement)
- Settle: [DEPRECATED] The service uses the settlement volatility to build the volatility surface
- Quoted: The service uses the quoted volatility to build the volatility surface
- Implied: The service internally calculates implied volatilities for the option universe before building the surface
Default value is "Implied".
:return: enum EtiInputVolatilityType
"""
return self._get_enum_parameter(EtiInputVolatilityType, "inputVolatilityType")
@input_volatility_type.setter
def input_volatility_type(self, value):
self._set_enum_parameter(EtiInputVolatilityType, "inputVolatilityType", value)
@property
def moneyness_type(self):
"""
The enumerate that specifies the moneyness type to use for calibration.
- Spot
- Fwd
- Sigma
Optional. Default value is "Spot".
:return: enum MoneynessType
"""
return self._get_enum_parameter(MoneynessType, "moneynessType")
@moneyness_type.setter
def moneyness_type(self, value):
self._set_enum_parameter(MoneynessType, "moneynessType", value)
@property
def price_side(self):
"""
Specifies whether bid, ask or mid is used to build the surface.
:return: enum PriceSide
"""
return self._get_enum_parameter(PriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(PriceSide, "priceSide", value)
@property
def time_stamp(self):
"""
Define how the timestamp is selected:
- Open: the opening value of the valuationDate or if not available the close of the previous day is used.
- Default: the latest snapshot is used when valuationDate is today, the close price when valuationDate is in the past.
:return: enum TimeStamp
"""
return self._get_enum_parameter(TimeStamp, "timeStamp")
@time_stamp.setter
def time_stamp(self, value):
self._set_enum_parameter(TimeStamp, "timeStamp", value)
@property
def volatility_model(self):
"""
The quantitative model used to generate the volatility surface. This may depend on the asset class.
:return: enum VolatilityModel
"""
return self._get_enum_parameter(VolatilityModel, "volatilityModel")
@volatility_model.setter
def volatility_model(self, value):
self._set_enum_parameter(VolatilityModel, "volatilityModel", value)
@property
def weights(self):
"""
Specifies the list of calibration weight.
:return: list MoneynessWeight
"""
return self._get_list_parameter(MoneynessWeight, "weights")
@weights.setter
def weights(self, value):
self._set_list_parameter(MoneynessWeight, "weights", value)
@property
def x_axis(self):
"""
Specifies the unit for the x axis (e.g. Date, Tenor)
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "xAxis")
@x_axis.setter
def x_axis(self, value):
self._set_enum_parameter(Axis, "xAxis", value)
@property
def y_axis(self):
"""
Specifies the unit for the y axis (e.g. Strike, Delta). This may depend on the asset class.
For Fx Volatility Surface, we support both Delta and Strike.
:return: enum Axis
"""
return self._get_enum_parameter(Axis, "yAxis")
@y_axis.setter
def y_axis(self, value):
self._set_enum_parameter(Axis, "yAxis", value)
@property
def calculation_date(self):
"""
The date the volatility surface is generated.
:return: str
"""
return self._get_parameter("calculationDate")
@calculation_date.setter
def calculation_date(self, value):
self._set_datetime_parameter("calculationDate", value)
@property
def svi_alpha_extrapolation(self):
"""
Svi Alpha Extrapolation for building the surface
Default value : TRUE
:return: bool
"""
return self._get_parameter("sviAlphaExtrapolation")
@svi_alpha_extrapolation.setter
def svi_alpha_extrapolation(self, value):
self._set_parameter("sviAlphaExtrapolation", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_eti_surface_parameters.py | 0.95347 | 0.455441 | _eti_surface_parameters.py | pypi |
from typing import TYPE_CHECKING
from .._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ...._types import OptStr, OptBool
class EtiSurfaceDefinition(ObjectDefinition):
"""
The definition of the volatility surface.
Parameters
----------
instrument_code : str, optional
The code (ric for equities and indices and ricroot for futures.) that represents
the instrument. the format for equities and indices is xxx@ric (example:
vod.l@ric) the format for futures is xx@ricroot (example: cl@ricroot)
clean_instrument_code : str, optional
exchange : str, optional
Specifies the exchange to be used to retrieve the underlying data.
is_future_underlying : bool, optional
is_lme_future_underlying : bool, optional
"""
def __init__(
self,
instrument_code: "OptStr" = None,
clean_instrument_code: "OptStr" = None,
exchange: "OptStr" = None,
is_future_underlying: "OptBool" = None,
is_lme_future_underlying: "OptBool" = None,
):
super().__init__()
self.instrument_code = instrument_code
self.clean_instrument_code = clean_instrument_code
self.exchange = exchange
self.is_future_underlying = is_future_underlying
self.is_lme_future_underlying = is_lme_future_underlying
@property
def clean_instrument_code(self):
"""
:return: str
"""
return self._get_parameter("cleanInstrumentCode")
@clean_instrument_code.setter
def clean_instrument_code(self, value):
self._set_parameter("cleanInstrumentCode", value)
@property
def exchange(self):
"""
Specifies the exchange to be used to retrieve the underlying data.
:return: str
"""
return self._get_parameter("exchange")
@exchange.setter
def exchange(self, value):
self._set_parameter("exchange", value)
@property
def instrument_code(self):
"""
The code (RIC for equities and indices and RICROOT for Futures.) that represents the instrument.
The format for equities and indices is xxx@RIC (Example: VOD.L@RIC)
The format for Futures is xx@RICROOT (Example: CL@RICROOT)
:return: str
"""
return self._get_parameter("instrumentCode")
@instrument_code.setter
def instrument_code(self, value):
self._set_parameter("instrumentCode", value)
@property
def is_future_underlying(self):
"""
:return: bool
"""
return self._get_parameter("isFutureUnderlying")
@is_future_underlying.setter
def is_future_underlying(self, value):
self._set_parameter("isFutureUnderlying", value)
@property
def is_lme_future_underlying(self):
"""
:return: bool
"""
return self._get_parameter("isLmeFutureUnderlying")
@is_lme_future_underlying.setter
def is_lme_future_underlying(self, value):
self._set_parameter("isLmeFutureUnderlying", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_eti_surface_definition.py | 0.912223 | 0.338733 | _eti_surface_definition.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._surface_request_item import SurfaceRequestItem
from ._enums import UnderlyingType
from ._fx_statistics_parameters import FxStatisticsParameters
from ._fx_surface_parameters import FxSurfaceParameters as FxCalculationParams
from ._fx_surface_definition import FxVolatilitySurfaceDefinition as FxSurfaceDefinition
if TYPE_CHECKING:
from ...._types import OptStr
class FxSurfaceRequestItem(SurfaceRequestItem):
# new name FxVolatilitySurfaceRequestItem into version 1.0.130
def __init__(
self,
surface_layout=None,
surface_parameters: Optional[FxCalculationParams] = None,
underlying_definition: Optional[FxSurfaceDefinition] = None,
surface_tag: "OptStr" = None,
surface_statistics_parameters: Optional[FxStatisticsParameters] = None,
):
super().__init__(
surface_layout=surface_layout,
surface_tag=surface_tag,
underlying_type=UnderlyingType.FX,
)
self.surface_parameters = surface_parameters
self.underlying_definition = underlying_definition
self.surface_statistics_parameters = surface_statistics_parameters
@property
def surface_parameters(self):
"""
The section that contains the properties that define how the volatility surface is generated
:return: object FxCalculationParams
"""
return self._get_object_parameter(FxCalculationParams, "surfaceParameters")
@surface_parameters.setter
def surface_parameters(self, value):
self._set_object_parameter(FxCalculationParams, "surfaceParameters", value)
@property
def underlying_definition(self):
"""
The section that contains the properties that define the underlying instrument
:return: object FxSurfaceDefinition
"""
return self._get_object_parameter(FxSurfaceDefinition, "underlyingDefinition")
@underlying_definition.setter
def underlying_definition(self, value):
self._set_object_parameter(FxSurfaceDefinition, "underlyingDefinition", value)
@property
def surface_statistics_parameters(self):
"""
:return: object FxStatisticsParameters
"""
return self._get_object_parameter(FxStatisticsParameters, "surfaceStatisticsParameters")
@surface_statistics_parameters.setter
def surface_statistics_parameters(self, value):
self._set_object_parameter(FxStatisticsParameters, "surfaceStatisticsParameters", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_fx_surface_request_item.py | 0.940503 | 0.236483 | _fx_surface_request_item.py | pypi |
__all__ = ["MoneynessWeight"]
from typing import TYPE_CHECKING
from ..._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ....._types import OptFloat
class MoneynessWeight(ObjectDefinition):
"""
MoneynessWeight for surface.
Parameters
----------
max_moneyness : float, optional
The upper bound of the moneyness range of options to which the specified
weight should be applied for surface construction. The value is expressed in
percentages (call option moneyness = UnderlyingPrice / Strike * 100; put option
moneyness = Strike / UnderlyingPrice * 100). The value of 100 corresponds to
at-the-money option.
min_moneyness : float, optional
The lower bound of the moneyness range of options to which the specified weight
should be applied for surface construction. The value is expressed in
percentages (call option moneyness = UnderlyingPrice / Strike * 100;
put option moneyness = Strike / UnderlyingPrice * 100). The value of 100
corresponds to at-the-money option.
weight : float, optional
The weight which should be applied to the options in the specified range of the
moneyness. The value is expressed in absolute numbers. The contribution of a
specific option is computed by the dividing the weight of the option by the
sum of weights of all constituent options.
"""
def __init__(
self,
max_moneyness: "OptFloat" = None,
min_moneyness: "OptFloat" = None,
weight: "OptFloat" = None,
):
super().__init__()
self.max_moneyness = max_moneyness
self.min_moneyness = min_moneyness
self.weight = weight
@property
def max_moneyness(self):
"""
:return: float
"""
return self._get_parameter("maxMoneyness")
@max_moneyness.setter
def max_moneyness(self, value):
self._set_parameter("maxMoneyness", value)
@property
def min_moneyness(self):
"""
:return: float
"""
return self._get_parameter("minMoneyness")
@min_moneyness.setter
def min_moneyness(self, value):
self._set_parameter("minMoneyness", value)
@property
def weight(self):
"""
:return: float
"""
return self._get_parameter("weight")
@weight.setter
def weight(self, value):
self._set_parameter("weight", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_models/_moneyness_weight.py | 0.93789 | 0.392511 | _moneyness_weight.py | pypi |
__all__ = ["SurfaceFilters"]
from typing import Optional, TYPE_CHECKING
from ..._object_definition import ObjectDefinition
from ._maturity_filter import MaturityFilter
from ._strike_filter_range import StrikeFilterRange
if TYPE_CHECKING:
from ....._types import OptBool, OptInt, OptFloat
class SurfaceFilters(ObjectDefinition):
"""
Filter object for surface.
Parameters
----------
maturity_filter_range : MaturityFilter, optional
The object allows to specify the range of expiry periods of options that are
used to construct the surface.
strike_range : StrikeFilterRange, optional
The range allows to exclude strike levels that have implied volatilities which
exceed upper bound or below lower bound.
strike_range_percent : DEPRECATED
This attribute doesn't use anymore.
atm_tolerance_interval_percent : float, optional
Filter on the atm tolerance interval percent
ensure_prices_monotonicity : bool, optional
Filter on the monotonicity of price options.
max_of_median_bid_ask_spread : float, optional
Spread mutltiplier to filter the options with the same expiry
max_staleness_days : int, optional
Max staleness past days to use for building the surface
use_only_calls : bool, optional
Select only teh calls to build the surface
use_only_puts : bool, optional
Select only the puts to build the surface
use_weekly_options : bool, optional
Filter on the weekly options.
include_min_tick_prices : bool, optional
Take into account the minimum tick prices to build the surface
"""
_strike_range_percent = None
def __init__(
self,
maturity_filter_range: Optional[MaturityFilter] = None,
strike_range: Optional[StrikeFilterRange] = None,
strike_range_percent=None,
atm_tolerance_interval_percent: "OptFloat" = None,
ensure_prices_monotonicity: "OptBool" = None,
max_of_median_bid_ask_spread: "OptFloat" = None,
max_staleness_days: "OptInt" = None,
use_only_calls: "OptBool" = None,
use_only_puts: "OptBool" = None,
use_weekly_options: "OptBool" = None,
include_min_tick_prices: "OptBool" = None,
):
super().__init__()
self.maturity_filter_range = maturity_filter_range
self.strike_range = strike_range
self.strike_range_percent = strike_range_percent
self.atm_tolerance_interval_percent = atm_tolerance_interval_percent
self.ensure_prices_monotonicity = ensure_prices_monotonicity
self.max_of_median_bid_ask_spread = max_of_median_bid_ask_spread
self.max_staleness_days = max_staleness_days
self.use_only_calls = use_only_calls
self.use_only_puts = use_only_puts
self.use_weekly_options = use_weekly_options
self.include_min_tick_prices = include_min_tick_prices
@property
def maturity_filter_range(self):
"""
Define the MaturityFilterRange
:return: object MaturityFilter
"""
return self._get_object_parameter(MaturityFilter, "maturityFilterRange")
@maturity_filter_range.setter
def maturity_filter_range(self, value):
self._set_object_parameter(MaturityFilter, "maturityFilterRange", value)
@property
def strike_range(self):
"""
Define the StrikeFilterRange
:return: object StrikeFilterRange
"""
return self._get_object_parameter(StrikeFilterRange, "strikeRange")
@strike_range.setter
def strike_range(self, value):
self._set_object_parameter(StrikeFilterRange, "strikeRange", value)
@property
def strike_range_percent(self):
"""
[DEPRECATED]
"""
return self._strike_range_percent
@strike_range_percent.setter
def strike_range_percent(self, value):
self._strike_range_percent = value
@property
def atm_tolerance_interval_percent(self):
"""
Filter on the ATM tolerance interval percent
:return: float
"""
return self._get_parameter("atmToleranceIntervalPercent")
@atm_tolerance_interval_percent.setter
def atm_tolerance_interval_percent(self, value):
self._set_parameter("atmToleranceIntervalPercent", value)
@property
def ensure_prices_monotonicity(self):
"""
Filter on the monotonicity of price options.
:return: bool
"""
return self._get_parameter("ensurePricesMonotonicity")
@ensure_prices_monotonicity.setter
def ensure_prices_monotonicity(self, value):
self._set_parameter("ensurePricesMonotonicity", value)
@property
def max_of_median_bid_ask_spread(self):
"""
Spread mutltiplier to filter the options with the same expiry
:return: float
"""
return self._get_parameter("maxOfMedianBidAskSpread")
@max_of_median_bid_ask_spread.setter
def max_of_median_bid_ask_spread(self, value):
self._set_parameter("maxOfMedianBidAskSpread", value)
@property
def max_staleness_days(self):
"""
Max Staleness past days to use for building the surface
:return: int
"""
return self._get_parameter("maxStalenessDays")
@max_staleness_days.setter
def max_staleness_days(self, value):
self._set_parameter("maxStalenessDays", value)
@property
def use_only_calls(self):
"""
SElect only teh calls to build the surface
:return: bool
"""
return self._get_parameter("useOnlyCalls")
@use_only_calls.setter
def use_only_calls(self, value):
self._set_parameter("useOnlyCalls", value)
@property
def use_only_puts(self):
"""
Select only the puts to build the surface
:return: bool
"""
return self._get_parameter("useOnlyPuts")
@use_only_puts.setter
def use_only_puts(self, value):
self._set_parameter("useOnlyPuts", value)
@property
def use_weekly_options(self):
"""
Filter on the weekly options.
:return: bool
"""
return self._get_parameter("useWeeklyOptions")
@use_weekly_options.setter
def use_weekly_options(self, value):
self._set_parameter("useWeeklyOptions", value)
@property
def include_min_tick_prices(self):
"""
Take into account the minimum tick prices to build the surface
:return: bool
"""
return self._get_parameter("includeMinTickPrices")
@include_min_tick_prices.setter
def include_min_tick_prices(self, value):
self._set_parameter("includeMinTickPrices", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_models/_surface_filters.py | 0.924266 | 0.419886 | _surface_filters.py | pypi |
from typing import Union
import numpy as np
from scipy import interpolate
from ._surface_point import SurfacePoint
from .._enums import Axis
from ..._content_provider import value_arg_parser, x_arg_parser, y_arg_parser
from ..._curves._models._curve import Curve
from ....._tools._common import cached_property
class Surface:
"""
The actual volatility surface
Parameters
-------
row : np.array
Specifies a data of discrete values for the y-axis
column : np.array
Specifies a data of discrete values for the x-axis
matrix : np.array
Specifies whether the calculated volatilities a matrix.
Methods
-------
get_curve(value, axis): Curve
get_point(x, y): SurfacePoint
Examples
-------
>>> from refinitiv.data.content.ipa.surfaces import eti
>>> definition = eti.Definition(
... underlying_definition=eti.EtiSurfaceDefinition(
... instrument_code="BNPP.PA@RIC"
... ),
... surface_parameters=eti.EtiCalculationParams(
... price_side=eti.PriceSide.MID,
... volatility_model=eti.VolatilityModel.SVI,
... x_axis=eti.Axis.STRIKE,
... y_axis=eti.Axis.DATE,
... ),
... surface_tag="1_MATRIX",
... surface_layout=eti.SurfaceLayout(
... format=eti.Format.MATRIX,
... y_point_count=10
... ),
... )
>>> response = definition.get_data()
>>> surface = response.data.surface
>>> curve = surface.get_curve("25.35", eti.Axis.X)
>>> curve = surface.get_curve("2021-08-20", eti.Axis.Y)
>>> point = surface.get_point(25.35, "2020-08-20")
"""
def __init__(self, row: np.array, column: np.array, matrix: np.array) -> None:
self._row = row
self._column = column
self._matrix = matrix
@cached_property
def _values_by_axis(self):
return {
Axis.X: self.x,
Axis.Y: self.y,
Axis.Z: self.z,
}
@cached_property
def _interp(self):
"""
For interpolate.interp2d axes are:
|--→ column=x
↓
row=y
"""
return interpolate.interp2d(
x=self._column.astype(float),
y=self._row.astype(float),
z=self._matrix.astype(float),
)
@property
def x(self):
return self._row
@property
def y(self):
return self._column
@property
def z(self):
return self._matrix
def get_curve(
self,
value: Union[str, float, int, np.datetime64],
axis: Union[Axis, str],
) -> Curve:
"""
Get curve
Parameters
----------
value: str, float, int, np.datetime64
Establishment value
axis: Axis
The enumerate that specifies the unit for the axis
Returns
-------
Curve
"""
values = self._values_by_axis.get(axis, [])
value = value_arg_parser.parse(value)
axis_x, axis_y = [], []
is_axis_x = axis == Axis.X
is_axis_y = axis == Axis.Y
is_axis_z = axis == Axis.Z
# interpolate
if value not in values and not is_axis_z:
value = value_arg_parser.get_float(value)
if is_axis_x:
axis_x = self._column
axis_y = self._interp(
x=self._column.astype(float),
y=value,
)
elif is_axis_y:
axis_x = self._interp(
x=value,
y=self._row.astype(float),
)
axis_x = axis_x[:, 0]
axis_y = self._row
else:
index = np.where(values == value)
if is_axis_x:
axis_x = self.z[index, :]
axis_x = axis_x[0][0]
axis_y = self.y
elif is_axis_y:
axis_x = self.x
axis_y = self.z[:, index]
axis_y = axis_y[:, 0][:, 0]
elif is_axis_z:
axis_x = self.x
axis_y = self.y
return Curve(axis_x, axis_y)
def get_point(
self,
x: Union[str, int, float, np.datetime64],
y: Union[str, int, float, np.datetime64],
) -> SurfacePoint:
"""
Get SurfacePoint
Parameters
----------
x: str, float, int, np.datetime64
X axis
y: str, float, int, np.datetime64
Y axis
Returns
-------
SurfacePoint
"""
x = x_arg_parser.parse(x)
y = y_arg_parser.parse(y)
if x in self.x and y in self.y:
(row,) = np.where(self._row == x)
(column,) = np.where(self._column == y)
z = self._matrix[row, column]
z = z[0]
# interpolate
else:
x_as_float = value_arg_parser.get_float(x)
y_as_float = value_arg_parser.get_float(y)
z = self._interp(x=y_as_float, y=x_as_float)
z = z[0]
return SurfacePoint(x, y, z) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_models/_surface.py | 0.957814 | 0.559471 | _surface.py | pypi |
__all__ = ["MaturityFilter"]
from typing import TYPE_CHECKING
from ..._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ....._types import OptStr, OptFloat
class MaturityFilter(ObjectDefinition):
"""
MaturityFilter for surface.
Parameters
----------
max_maturity : str, optional
The period code used to set the maximal maturity of options used to construct
the surface (e.g., '1M', '1Y').
min_maturity : str, optional
The period code used to set the minimal maturity of options used to construct
the surface (e.g., '1M', '1Y').
min_of_median_nb_of_strikes_percent : float, optional
The value is used to set the minimum number of strikes that should be available
for maturities that are used to construct the surface. The minimum threshold
is computed as MinOfMedianNbOfStrikesPercent multiplied by the median number
of Strikes and divided by 100. The value is expressed in percentages.
"""
def __init__(
self,
max_maturity: "OptStr" = None,
min_maturity: "OptStr" = None,
min_of_median_nb_of_strikes_percent: "OptFloat" = None,
):
super().__init__()
self.max_maturity = max_maturity
self.min_maturity = min_maturity
self.min_of_median_nb_of_strikes_percent = min_of_median_nb_of_strikes_percent
@property
def max_maturity(self):
"""
Max Maturity to consider in the filtering. (expressed in tenor)
:return: str
"""
return self._get_parameter("maxMaturity")
@max_maturity.setter
def max_maturity(self, value):
self._set_parameter("maxMaturity", value)
@property
def min_maturity(self):
"""
Min Maturity to consider in the filtering. (expressed in tenor)
Default value: 7D
:return: str
"""
return self._get_parameter("minMaturity")
@min_maturity.setter
def min_maturity(self, value):
self._set_parameter("minMaturity", value)
@property
def min_of_median_nb_of_strikes_percent(self):
"""
Remove maturities whose number of strikes is less than MinOfMedianNbOfStrikesPercent of the Median number of Strikes.
:return: float
"""
return self._get_parameter("minOfMedianNbOfStrikesPercent")
@min_of_median_nb_of_strikes_percent.setter
def min_of_median_nb_of_strikes_percent(self, value):
self._set_parameter("minOfMedianNbOfStrikesPercent", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_models/_maturity_filter.py | 0.927503 | 0.478285 | _maturity_filter.py | pypi |
__all__ = ["SurfaceLayout"]
from ..._object_definition import ObjectDefinition
from ._volatility_surface_point import VolatilitySurfacePoint
from .._enums import Format
from .._surface_types import OptFormat, OptVolatilitySurfacePoints
from ....._types import OptStrings, OptInt
from ....._tools import create_repr, try_copy_to_list
class SurfaceLayout(ObjectDefinition):
"""
This class property contains the properties that may be used to control how the
surface is displayed.
Parameters
---------
data_points : list of VolatilitySurfacePoint, optional
Specifies the list of specific data points to be returned
format : Format, option
Specifies whether the calculated volatilities are returned as a list or a matrix
x_values : list of str, optional
Specifies a list of discrete values for the x-axis
y_values : list of str, optional
Specifies a list of discrete values for the y-axis
z_values : list of str, optional
Specifies a list of discrete values for the z-axis
x_point_count : int, optional
Specifies the number of values that will be generated along the x-axis.
These values will distributed depending on the available input data and the type
of volatility
y_point_count : int, optional
Specifies the number of values that will be generated along the y-axis.
These values will distributed depending on the available input data and the type
of volatility
z_point_count : int, optional
Specifies the number of values that will be generated along the z-axis.
These values will distributed depending on the available input data and the type
of volatility
Examples
-------
>>> from refinitiv.data.content.ipa.surfaces.fx import SurfaceLayout
>>> from refinitiv.data.content.ipa.surfaces import fx
>>> SurfaceLayout(format=fx.Format.MATRIX)
"""
def __init__(
self,
data_points: OptVolatilitySurfacePoints = None,
format: OptFormat = None,
x_values: OptStrings = None,
y_values: OptStrings = None,
z_values: OptStrings = None,
x_point_count: OptInt = None,
y_point_count: OptInt = None,
z_point_count: OptInt = None,
):
super().__init__()
self.data_points = try_copy_to_list(data_points)
self.format = format
self.x_values = try_copy_to_list(x_values)
self.y_values = try_copy_to_list(y_values)
self.z_values = try_copy_to_list(z_values)
self.x_point_count = x_point_count
self.y_point_count = y_point_count
self.z_point_count = z_point_count
def __repr__(self):
return create_repr(
self,
middle_path="surfaces.fx",
class_name="SurfaceLayout",
)
@property
def data_points(self):
"""
Specifies the list of specific data points to be returned.
:return: list VolatilitySurfacePoint
"""
return self._get_list_parameter(VolatilitySurfacePoint, "dataPoints")
@data_points.setter
def data_points(self, value):
self._set_list_parameter(VolatilitySurfacePoint, "dataPoints", value)
@property
def format(self):
"""
Specifies whether the calculated volatilities are returned as a list or a matrix.
:return: enum Format
"""
return self._get_enum_parameter(Format, "format")
@format.setter
def format(self, value):
self._set_enum_parameter(Format, "format", value)
@property
def x_values(self):
"""
Specifies a list of discrete values for the x-axis.
:return: list string
"""
return self._get_list_parameter(str, "xValues")
@x_values.setter
def x_values(self, value):
self._set_list_parameter(str, "xValues", value)
@property
def y_values(self):
"""
Specifies a list of discrete values for the y-axis.
:return: list string
"""
return self._get_list_parameter(str, "yValues")
@y_values.setter
def y_values(self, value):
self._set_list_parameter(str, "yValues", value)
@property
def z_values(self):
"""
Specifies a list of discrete values for the z-axis.
:return: list string
"""
return self._get_list_parameter(str, "zValues")
@z_values.setter
def z_values(self, value):
self._set_list_parameter(str, "zValues", value)
@property
def x_point_count(self):
"""
Specifies the number of values that will be generated along the x-axis.
These values will distributed depending on the available input data and the type of volatility.
:return: int
"""
return self._get_parameter("xPointCount")
@x_point_count.setter
def x_point_count(self, value):
self._set_parameter("xPointCount", value)
@property
def y_point_count(self):
"""
Specifies the number of values that will be generated along the y-axis.
These values will distributed depending on the available input data and the type of volatility.
:return: int
"""
return self._get_parameter("yPointCount")
@y_point_count.setter
def y_point_count(self, value):
self._set_parameter("yPointCount", value)
@property
def z_point_count(self):
"""
Specifies the number of values that will be generated along the z-axis.
These values will distributed depending on the available input data and the type of volatility.
:return: int
"""
return self._get_parameter("zPointCount")
@z_point_count.setter
def z_point_count(self, value):
self._set_parameter("zPointCount", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_models/_surface_output.py | 0.918132 | 0.622517 | _surface_output.py | pypi |
__all__ = ["StrikeFilterRange"]
from typing import TYPE_CHECKING
from ..._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ....._types import OptFloat
class StrikeFilterRange(ObjectDefinition):
"""
StrikeFilterRange for surface.
Parameters
----------
max_of_median_implied_vol_percent : float, optional
The value can be used to exclude strikes with implied volatilities larger
than upper bound. The upper bound is computed as MaxOfMedianImpliedVolPercent
multiplied by median implied volatility and divided by 100. The value is
expressed in percentages.
Mandatory if strikeRange object is used.
min_of_median_implied_vol_percent : float, optional
The value can be used to exclude strikes with implied volatilities less than
lower bound. The lower bound is computed as MinOfMedianImpliedVolPercent
multiplied by median implied volatility and divided by 100.
The value is expressed in percentages.
"""
def __init__(
self,
max_of_median_implied_vol_percent: "OptFloat" = None,
min_of_median_implied_vol_percent: "OptFloat" = None,
):
super().__init__()
self.max_of_median_implied_vol_percent = max_of_median_implied_vol_percent
self.min_of_median_implied_vol_percent = min_of_median_implied_vol_percent
@property
def max_of_median_implied_vol_percent(self):
"""
Remove strikes whose implied vol is more than MaxOfMedianImpliedVolPercent x Median implied Vol.
:return: float
"""
return self._get_parameter("maxOfMedianImpliedVolPercent")
@max_of_median_implied_vol_percent.setter
def max_of_median_implied_vol_percent(self, value):
self._set_parameter("maxOfMedianImpliedVolPercent", value)
@property
def min_of_median_implied_vol_percent(self):
"""
Remove strikes whose implied vol is less than MinOfMedianImpliedVolPercent x Median implied Vol.
:return: float
"""
return self._get_parameter("minOfMedianImpliedVolPercent")
@min_of_median_implied_vol_percent.setter
def min_of_median_implied_vol_percent(self, value):
self._set_parameter("minOfMedianImpliedVolPercent", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_surfaces/_models/_strike_filter_range.py | 0.921194 | 0.294526 | _strike_filter_range.py | pypi |
from typing import TYPE_CHECKING, Optional
from numpy import iterable
from ..._curves import ShiftScenario
from ...._content_provider_layer import ContentProviderLayer
from ....._tools import create_repr, try_copy_to_list
from ..._curves._zc_curve_request_item import ZcCurveRequestItem
from ....._content_type import ContentType
if TYPE_CHECKING:
from ....._types import OptStr, ExtendedParams
from ..._curves._zc_curve_types import (
DefnDefns,
OptConstituents,
CurveDefinition,
CurveParameters,
)
class Definition(ContentProviderLayer):
"""
Parameters
----------
constituents : Constituents, optional
curve_definition : ZcCurveDefinitions, optional
curve_parameters : ZcCurveParameters, optional
curve_tag : str, optional
extended_params : dict, optional
If necessary other parameters.
shift_scenarios : ShiftScenario, optional
The list of attributes applied to the curve shift scenarios.
Methods
-------
get_data(session=session, on_response=on_response)
Returns a response to the data platform
get_data_async(session=None, on_response=None, async_mode=None)
Returns a response asynchronously to the data platform
Examples
--------
>>> import refinitiv.data.content.ipa.curves.zc_curves as zc_curves
>>> definition = zc_curves.Definition(
... curve_definition=zc_curves.ZcCurveDefinitions(
... currency="CHF",
... name="CHF LIBOR Swap ZC Curve",
... discounting_tenor="OIS",
... ),
... curve_parameters=zc_curves.ZcCurveParameters(
... use_steps=True
... )
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
constituents: "OptConstituents" = None,
curve_definition: "CurveDefinition" = None,
curve_parameters: "CurveParameters" = None,
curve_tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
shift_scenarios: Optional[ShiftScenario] = None,
):
request_item = ZcCurveRequestItem(
constituents=constituents,
curve_definition=curve_definition,
curve_parameters=curve_parameters,
curve_tag=curve_tag,
shift_scenarios=shift_scenarios,
)
super().__init__(
content_type=ContentType.ZC_CURVES,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self)
class Definitions(ContentProviderLayer):
"""
Parameters
----------
universe : zc_curves.Definition, list of zc_curves.Definition
Methods
-------
get_data(session=session, on_response=on_response)
Returns a response to the data platform
get_data_async(session=None, on_response=None, async_mode=None)
Returns a response asynchronously to the data platform
Examples
--------
>>> import refinitiv.data.content.ipa.curves.zc_curves as zc_curves
>>> definition = zc_curves.Definition(
... curve_definition=zc_curves.ZcCurveDefinitions(
... currency="CHF",
... name="CHF LIBOR Swap ZC Curve",
... discounting_tenor="OIS",
... ),
... curve_parameters=zc_curves.ZcCurveParameters(
... use_steps=True
... )
... )
>>> definition = zc_curves.Definitions(universe=definition)
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
universe: "DefnDefns",
):
universe = try_copy_to_list(universe)
if not iterable(universe):
universe = [universe]
super().__init__(
content_type=ContentType.ZC_CURVES,
universe=universe,
__plural__=True,
)
def __repr__(self):
return create_repr(self, class_name=self.__class__.__name__) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/zc_curves/_definition.py | 0.937533 | 0.191706 | _definition.py | pypi |
from typing import TYPE_CHECKING, Optional
from numpy import iterable
from ..._curves import ShiftScenario
from ...._content_provider_layer import ContentProviderLayer
from ....._tools import create_repr, try_copy_to_list
from ..._curves._forward_curve_request_item import ForwardCurveRequestItem
from ....._content_type import ContentType
if TYPE_CHECKING:
from ..._curves._forward_curve_types import (
OptStr,
DefnDefns,
ExtendedParams,
CurveDefinition,
CurveParameters,
OptForwardCurveDefinitions,
)
class Definition(ContentProviderLayer):
"""
Parameters
----------
curve_definition : SwapZcCurveDefinition, optional
curve_parameters : SwapZcCurveParameters, optional
forward_curve_definitions : list of ForwardCurveDefinition, optional
curve_tag : str, optional
extended_params : dict, optional
If necessary other parameters.
Methods
-------
get_data(session=session, on_response=on_response)
Returns a response to the data platform
get_data_async(session=None, on_response=None, async_mode=None)
Returns a response asynchronously to the data platform
Examples
--------
>>> import refinitiv.data.content.ipa.curves.forward_curves as forward_curves
>>> definition = forward_curves.Definition(
... curve_definition=forward_curves.SwapZcCurveDefinition(
... currency="EUR",
... index_name="EURIBOR",
... name="EUR EURIBOR Swap ZC Curve",
... discounting_tenor="OIS",
... ),
... forward_curve_definitions=[
... forward_curves.ForwardCurveDefinition(
... index_tenor="3M",
... forward_curve_tag="ForwardTag",
... forward_start_date="2021-02-01",
... forward_curve_tenors=[
... "0D",
... "1D",
... "2D",
... "3M",
... "6M",
... "9M",
... "1Y",
... "2Y",
... "3Y",
... "4Y",
... "5Y",
... "6Y",
... "7Y",
... "8Y",
... "9Y",
... "10Y",
... "15Y",
... "20Y",
... "25Y"
... ]
... )
... ]
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
curve_definition: "CurveDefinition" = None,
forward_curve_definitions: "OptForwardCurveDefinitions" = None,
curve_parameters: "CurveParameters" = None,
curve_tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
shift_scenarios: Optional[ShiftScenario] = None,
):
forward_curve_definitions = try_copy_to_list(forward_curve_definitions)
request_item = ForwardCurveRequestItem(
curve_definition=curve_definition,
forward_curve_definitions=forward_curve_definitions,
curve_parameters=curve_parameters,
curve_tag=curve_tag,
shift_scenarios=shift_scenarios,
)
super().__init__(
content_type=ContentType.FORWARD_CURVE,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self)
class Definitions(ContentProviderLayer):
"""
Parameters
----------
universe : forward_curves.Definition, list of forward_curves.Definition
Methods
-------
get_data(session=session, on_response=on_response)
Returns a response to the data platform
get_data_async(session=None, on_response=None, async_mode=None)
Returns a response asynchronously to the data platform
Examples
--------
>>> import refinitiv.data.content.ipa.curves.forward_curves as forward_curves
>>>
>>> forward_curve_definition = forward_curves.Definition(
... curve_definition=forward_curves.SwapZcCurveDefinition(
... currency="EUR",
... index_name="EURIBOR",
... name="EUR EURIBOR Swap ZC Curve",
... discounting_tenor="OIS",
... ),
... forward_curve_definitions=[
... forward_curves.ForwardCurveDefinition(
... index_tenor="3M",
... forward_curve_tag="ForwardTag",
... forward_start_date="2021-02-01",
... forward_curve_tenors=[
... "0D",
... "1D",
... "2D",
... "3M",
... "6M",
... "9M",
... "1Y",
... "2Y",
... "3Y",
... "4Y",
... "5Y",
... "6Y",
... "7Y",
... "8Y",
... "9Y",
... "10Y",
... "15Y",
... "20Y",
... "25Y"
... ]
... )
... ]
... )
>>> definition = forward_curves.Definitions(
... universe=[forward_curve_definition],
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
universe: "DefnDefns",
):
universe = try_copy_to_list(universe)
if not iterable(universe):
universe = [universe]
super().__init__(
content_type=ContentType.FORWARD_CURVE,
universe=universe,
__plural__=True,
)
def __repr__(self):
return create_repr(self, class_name=self.__class__.__name__) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/forward_curves/_definition.py | 0.934761 | 0.265419 | _definition.py | pypi |
from typing import List, Optional, TYPE_CHECKING, Union
from numpy import iterable
from ..._curves._zc_curve_definition_request import ZcCurveDefinitionRequest
from ...._content_provider_layer import ContentProviderLayer
from ....._content_type import ContentType
from ....._tools import create_repr, try_copy_to_list
if TYPE_CHECKING:
from ....._types import OptStr, ExtendedParams, OptDateTime
from ..._enums._risk_type import RiskType
from ..._enums._asset_class import AssetClass
class Definition(ContentProviderLayer):
"""
Parameters
----------
index_name : str, optional
Example:
"EURIBOR"
main_constituent_asset_class : AssetClass, optional
See detail class AssetClass.
risk_type : RiskType, optional
See detail RiskType class.
currency : str, optional
The currency code of the interest rate curve.
curve_tag : str, optional
User defined string to identify the curve. It can be used to link output results
to the curve definition. Only alphabetic, numeric and '- _.#=@' characters
are supported.
id : str, optional
Id of the curve definition
name : str, optional
The name of the interest rate curve.
source : str, optional
Example:
"Refinitiv"
valuation_date: str or date, optional
Example:
"2019-08-21"
extended_params : dict, optional
If necessary other parameters.
market_data_location : str, optional
The identifier of the market place from which constituents come from.
Currently the following values are supported: 'onshore' and 'emea'.
The list of values can be extended by a user when creating a curve.
Methods
-------
get_data(session=session, on_response=on_response, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.curves import zc_curve_definitions
>>> definition = zc_curve_definitions.Definition(source="Refinitiv")
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
index_name: "OptStr" = None,
main_constituent_asset_class: Optional["AssetClass"] = None,
risk_type: Optional["RiskType"] = None,
currency: "OptStr" = None,
curve_tag: "OptStr" = None,
id: "OptStr" = None,
name: "OptStr" = None,
source: "OptStr" = None,
valuation_date: "OptDateTime" = None,
extended_params: "ExtendedParams" = None,
market_data_location: "OptStr" = None,
) -> None:
request_item = ZcCurveDefinitionRequest(
index_name=index_name,
main_constituent_asset_class=main_constituent_asset_class,
risk_type=risk_type,
currency=currency,
curve_tag=curve_tag,
id=id,
name=name,
source=source,
valuation_date=valuation_date,
market_data_location=market_data_location,
)
super().__init__(
content_type=ContentType.ZC_CURVE_DEFINITIONS,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self)
DefnDefns = Union[Definition, List[Definition]]
class Definitions(ContentProviderLayer):
"""
Parameters
----------
universe : list of zc_curve_definitions.Definition
See detail class zc_curve_definitions.Definition.
Methods
-------
get_data(session=session, on_response=on_response, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.curves import zc_curve_definitions
>>> definition1 = zc_curve_definitions.Definition(source="Refinitiv")
>>> definition2 = zc_curve_definitions.Definition(source="Peugeot")
>>> definitions = zc_curve_definitions.Definitions(
... universe=[definition1, definition2]
...)
>>> response = definitions.get_data()
Using get_data_async
>>> import asyncio
>>> task = definitions.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
universe: "DefnDefns",
):
universe = try_copy_to_list(universe)
if not iterable(universe):
universe = [universe]
super().__init__(
content_type=ContentType.ZC_CURVE_DEFINITIONS,
universe=universe,
__plural__=True,
)
def __repr__(self):
return create_repr(self, class_name=self.__class__.__name__) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/zc_curve_definitions/_definition.py | 0.94651 | 0.326889 | _definition.py | pypi |
from typing import TYPE_CHECKING
from ...._curves._cross_currency_curves._curves._request import RequestItem
from ......_content_type import ContentType
from ......_tools import create_repr
from ....._content_provider_layer import ContentProviderLayer
if TYPE_CHECKING:
from ......_types import OptStr, ExtendedParams
from ...._curves._cross_currency_curves._curves._types import (
CurveDefinition,
CurveParameters,
ShiftScenarios,
FxConstituents,
)
class Definition(ContentProviderLayer):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
constituents : FxForwardConstituents, optional
FxForwardConstituents object.
curve_definition : FxForwardCurveDefinition, optional
FxForwardCurveDefinition object.
curve_parameters : FxForwardCurveParameters, optional
FxForwardCurveParameters object.
shift_scenarios : FxShiftScenario, optional
The list of attributes applied to the curve shift scenarios.
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
extended_params : dict, optional
If necessary other parameters.
Examples
--------
>>> import refinitiv.data.content.ipa.curves._cross_currency_curves as crs_currency
>>> definition = crs_currency.curves.Definition(
... curve_definition=crs_currency.curves.FxForwardCurveDefinition(
... base_currency="EUR",
... base_index_name="ESTR",
... quoted_currency="USD",
... quoted_index_name="SOFR"
... ),
... curve_parameters=crs_currency.curves.FxForwardCurveParameters(
... valuation_date="2021-10-06"
... )
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
constituents: "FxConstituents" = None,
curve_definition: "CurveDefinition" = None,
curve_parameters: "CurveParameters" = None,
shift_scenarios: "ShiftScenarios" = None,
curve_tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
) -> None:
request_item = RequestItem(
constituents=constituents,
curve_definition=curve_definition,
curve_parameters=curve_parameters,
shift_scenarios=shift_scenarios,
curve_tag=curve_tag,
)
super().__init__(
content_type=ContentType.CROSS_CURRENCY_CURVES_CURVES,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self, middle_path="_cross_currency_curves.curves") | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_cross_currency_curves/curves/_definition.py | 0.930054 | 0.172921 | _definition.py | pypi |
from dataclasses import dataclass
from typing import TYPE_CHECKING
from .._arg_enums import main_constituent_asset_class_arg_parser, risk_type_arg_parser
from .._base_data_class import BaseData
from ......delivery._data._endpoint_data import EndpointData
if TYPE_CHECKING:
from ......_types import OptStr, OptBool, OptDateTime
from ...._curves._cross_currency_curves._types import (
OptMainConstituentAssetClass,
OptRiskType,
)
curve_info_camel_to_snake = {
"creationDateTime": "creation_date_time",
"creationUserId": "creation_user_id",
"updateDateTime": "update_date_time",
"updateUserId": "update_user_id",
"version": "version",
}
curve_definition_camel_to_snake = {
"mainConstituentAssetClass": "main_constituent_asset_class",
"riskType": "risk_type",
"baseCurrency": "base_currency",
"baseIndexName": "base_index_name",
"definitionExpiryDate": "definition_expiry_date",
"firstHistoricalAvailabilityDate": "first_historical_availability_date",
"id": "id",
"isFallbackForFxCurveDefinition": "is_fallback_for_fx_curve_definition",
"isNonDeliverable": "is_non_deliverable",
"name": "name",
"quotedCurrency": "quoted_currency",
"quotedIndexName": "quoted_index_name",
"source": "source",
}
def convert_camel_to_snake(mapper: dict, data: dict) -> dict:
return {mapper.get(name, name): value for name, value in data.items()}
class CurveInfo(BaseData):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
creation_date_time : str, optional
creation_user_id : str, optional
update_date_time : str, optional
update_user_id : str, optional
version : str, optional
"""
def __init__(
self,
creation_date_time: "OptStr" = None,
creation_user_id: "OptStr" = None,
update_date_time: "OptStr" = None,
update_user_id: "OptStr" = None,
version: "OptStr" = None,
**kwargs,
):
self.creation_date_time = creation_date_time
self.creation_user_id = creation_user_id
self.update_date_time = update_date_time
self.update_user_id = update_user_id
self.version = version
super().__init__(**kwargs)
class CrossCurrencyCurveDefinition(BaseData):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
definition_expiry_date : str or date or datetime or timedelta, optional
The date after which curvedefinitions can not be used. the value is expressed in
iso 8601 format: yyyy-mm-dd (e.g., '2021-01-01').
first_historical_availability_date : str, optional
The date starting from which cross currency curve definition can be used. the
value is expressed in iso 8601 format: yyyy-mm-dd (e.g., '2021-01-01').
id : str, optional
The identifier of the cross currency curve.
is_fallback_for_fx_curve_definition : bool, optional
The indicator used to define the fallback logic for the fx curve definition. the
possible values are: * true: there's a fallback logic to use cross currency
curve definition for fx curve definition, * false: there's no fallback logic
to use cross currency curve definition for fx curve definition.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
"""
def __init__(
self,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
definition_expiry_date: "OptDateTime" = None,
first_historical_availability_date: "OptStr" = None,
id: "OptStr" = None,
is_fallback_for_fx_curve_definition: "OptBool" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
**kwargs,
):
self.main_constituent_asset_class = main_constituent_asset_class_arg_parser.get_enum(
main_constituent_asset_class
)
self.risk_type = risk_type_arg_parser.get_enum(risk_type)
self.base_currency = base_currency
self.base_index_name = base_index_name
self.definition_expiry_date = definition_expiry_date
self.first_historical_availability_date = first_historical_availability_date
self.id = id
self.is_fallback_for_fx_curve_definition = is_fallback_for_fx_curve_definition
self.is_non_deliverable = is_non_deliverable
self.name = name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.source = source
super().__init__(**kwargs)
@dataclass
class CurveDefinitionData(EndpointData):
_curve_definition: CrossCurrencyCurveDefinition = None
_curve_info: CurveInfo = None
@property
def curve_definition(self):
if self._curve_definition is None:
curve_definition = self.raw.get("curveDefinition")
if curve_definition:
curve_definition = convert_camel_to_snake(curve_definition_camel_to_snake, curve_definition)
self._curve_definition = CrossCurrencyCurveDefinition(**curve_definition)
return self._curve_definition
@property
def curve_info(self):
if self._curve_info is None:
curve_info = self.raw.get("curveInfo")
if curve_info:
curve_info = convert_camel_to_snake(curve_info_camel_to_snake, curve_info)
self._curve_info = CurveInfo(**curve_info)
return self._curve_info | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_cross_currency_curves/definitions/_data_classes.py | 0.926893 | 0.260608 | _data_classes.py | pypi |
from typing import Union, TYPE_CHECKING
from ...._curves._cross_currency_curves._definitions._create import CreateRequest
from ...._curves._cross_currency_curves._definitions._delete import DeleteRequest
from ...._curves._cross_currency_curves._definitions._get import (
CrossCurrencyCurveDefinitionKeys,
GetRequest,
)
from ...._curves._cross_currency_curves._definitions._update import UpdateRequest
from ......_content_type import ContentType
from ......delivery._data import RequestMethod
from ......delivery._data._data_provider_layer import DataProviderLayer
if TYPE_CHECKING:
from ...._curves._cross_currency_curves._definitions._types import (
OptMainConstituentAssetClass,
OptRiskType,
Segments,
OptTurns,
CurveCreateDefinition,
OptOverrides,
CurveUpdateDefinition,
)
from ......delivery._data._data_provider import Response
from ......_core.session import Session
from ......_types import ExtendedParams, OptStr, OptBool
UnionSaveRequest = Union[CreateRequest, UpdateRequest]
def delete(id: str, session: "Session" = None) -> "Response":
"""
Delete the Cross Currency curve definition for the definition Id provided.
Parameters
----------
id : str
The identifier of the cross currency definition.
session : Session, optional
session=None. Means default session would be used.
Examples
--------
>>> from refinitiv.data.content.ipa.curves._cross_currency_curves import definitions
>>> response = definitions.manage.delete(id="334b89f6-e272-4900-ad1e-dfefv")
"""
request_item = DeleteRequest(id)
data_provider_layer = DataProviderLayer(
data_type=ContentType.CROSS_CURRENCY_CURVES_DEFINITIONS_DELETE,
request_items=request_item,
method=RequestMethod.POST,
)
return data_provider_layer.get_data(session)
def get(
id: "OptStr" = None,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
extended_params: "ExtendedParams" = None,
session: "Session" = None,
) -> "Response":
"""
Gets the Commodities curve definition for the definition provided.
Parameters
----------
id : str, optional
The identifier of the cross currency definitions.
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
extended_params : ExtendedParams, optional
If necessary other parameters.
session : Session, optional
session=None - means default session would be used.
Examples
--------
>>> from refinitiv.data.content.ipa.curves._cross_currency_curves import definitions
>>> response = definitions.manage.get(
... base_currency="EUR",
... base_index_name="EURIBOR",
... quoted_currency="USD",
... quoted_index_name="LIBOR",
>>> )
"""
definition_obj = CrossCurrencyCurveDefinitionKeys(
main_constituent_asset_class=main_constituent_asset_class,
risk_type=risk_type,
base_currency=base_currency,
base_index_name=base_index_name,
id=id,
is_non_deliverable=is_non_deliverable,
name=name,
quoted_currency=quoted_currency,
quoted_index_name=quoted_index_name,
source=source,
)
request_item = GetRequest(curve_definition=definition_obj)
content_provider_layer = DataProviderLayer(
data_type=ContentType.CROSS_CURRENCY_CURVES_DEFINITIONS_GET,
request_items=request_item,
extended_params=extended_params,
)
response = content_provider_layer.get_data(session=session)
return response
def create(
curve_definition: "CurveCreateDefinition",
segments: "Segments",
*,
overrides: "OptOverrides" = None,
turns: "OptTurns" = None,
extended_params: "ExtendedParams" = None,
session: "Session" = None,
) -> "Response":
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
curve_definition : CrossCurrencyCurveDefinitionDescription
CrossCurrencyCurveDefinitionDescription object
segments : list of CrossCurrencyInstrumentsSegment
list of CrossCurrencyInstrumentsSegment objects
overrides : list of OverrideBidAsk, optional
OverrideBidAsk object.
turns : list of OverrideFxForwardTurn, optional
extended_params : ExtendedParams, optional
If necessary other parameters.
session : Session, optional
session=None - means default session would be used
Examples
--------
>>> from refinitiv.data.content.ipa.curves._cross_currency_curves import definitions
>>> response = definitions.manage.create(
... curve_definition=definitions.CrossCurrencyCurveCreateDefinition(
... source="SourceName",
... name="Name of the Curve854",
... base_currency="EUR",
... base_index_name="ESTR",
... quoted_currency="USD",
... quoted_index_name="SOFR",
... is_non_deliverable=False
... ),
... segments=[
... definitions.CrossCurrencyInstrumentsSegment(
... start_date="2021-01-01",
... constituents=definitions.CrossCurrencyConstituentsDescription(
... fx_forwards=[
... definitions.FxForwardInstrumentDescription(
... instrument_definition=definitions.FxForwardInstrumentDefinition(
... instrument_code="EUR1M=",
... tenor="1M",
... is_non_deliverable=False,
... quotation_mode=definitions.QuotationMode.OUTRIGHT
... )
... )
... ]
... ),
... )
... ]
>>> )
"""
request_items = CreateRequest(
curve_definition=curve_definition,
overrides=overrides,
segments=segments,
turns=turns,
)
response = _save(
ContentType.CROSS_CURRENCY_CURVES_DEFINITIONS_CREATE,
request_items=request_items,
extended_params=extended_params,
session=session,
)
return response
def update(
curve_definition: "CurveUpdateDefinition",
segments: "Segments",
*,
overrides: "OptOverrides" = None,
turns: "OptTurns" = None,
extended_params: "ExtendedParams" = None,
session: "Session" = None,
) -> "Response":
"""
Updates the Cross Currency curve definition with the definition provided.
Parameters
----------
curve_definition : CrossCurrencyCurveUpdateDefinition
CrossCurrencyCurveUpdateDefinition object.
segments : list of CrossCurrencyInstrumentsSegment
list of CrossCurrencyInstrumentsSegment objects
overrides : list of OverrideBidAsk, optional
OverrideBidAsk object.
turns : list of OverrideFxForwardTurn, optional
extended_params : ExtendedParams, optional
If necessary other parameters.
session : Session, optional
session=None - means default session would be used
Examples
--------
>>> from refinitiv.data.content.ipa.curves._cross_currency_curves import definitions
>>> response = definitions.manage.update(
... curve_definition=definitions.CrossCurrencyCurveUpdateDefinition(
... id="7bdb00f3-0a48-40be-ace2-6d3cfd0e8e59",
... source="SourceName",
... name="rename curve",
... base_currency="EUR",
... base_index_name="ESTR",
... quoted_currency="USD",
... quoted_index_name="SOFR",
... is_non_deliverable=False
... ),
... segments=[
... definitions.CrossCurrencyInstrumentsSegment(
... start_date="2021-01-01",
... constituents=definitions.CrossCurrencyConstituentsDescription(
... fx_forwards=[
... definitions.FxForwardInstrumentDescription(
... instrument_definition=definitions.FxForwardInstrumentDefinition(
... instrument_code="EUR1M=",
... tenor="1M",
... is_non_deliverable=False,
... quotation_mode=definitions.QuotationMode.OUTRIGHT
... )
... )
... ]
... ),
... )
... ]
>>> )
"""
request_items = UpdateRequest(
curve_definition=curve_definition,
overrides=overrides,
segments=segments,
turns=turns,
)
response = _save(
ContentType.CROSS_CURRENCY_CURVES_DEFINITIONS_UPDATE,
request_items=request_items,
extended_params=extended_params,
session=session,
)
return response
def _save(
content_type: ContentType,
request_items: UnionSaveRequest,
extended_params: "ExtendedParams" = None,
session: "Session" = None,
) -> "Response":
data_provider_layer = DataProviderLayer(
data_type=content_type,
request_items=request_items,
method=RequestMethod.POST,
extended_params=extended_params,
)
return data_provider_layer.get_data(session=session) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_cross_currency_curves/definitions/_manage.py | 0.922408 | 0.229319 | _manage.py | pypi |
__all__ = (
"search",
"manage",
"CrossCurrencyCurveCreateDefinition",
"CrossCurrencyCurveUpdateDefinition",
"BidAskFieldsDescription",
"BidAskFieldsFormulaDescription",
"CrossCurrencyConstituentsDescription",
"CrossCurrencyCurveParameters",
"CrossCurrencyInstrumentDefinition",
"CrossCurrencyInstrumentDescription",
"CrossCurrencyInstrumentsSegment",
"FieldDescription",
"FieldFormulaDescription",
"FormulaParameterDescription",
"FxForwardInstrumentDefinition",
"FxForwardInstrumentDescription",
"FxForwardTurnFields",
"FxSpotInstrumentDefinition",
"FxSpotInstrumentDescription",
"OverrideBidAsk",
"OverrideBidAskFields",
"OverrideFxForwardTurn",
"TurnAdjustment",
"InterpolationMode",
"MainConstituentAssetClass",
"QuotationMode",
"RiskType",
"StandardTurnPeriod",
)
from . import search, manage
from ...._curves._cross_currency_curves._definitions import (
BidAskFieldsDescription,
BidAskFieldsFormulaDescription,
CrossCurrencyConstituentsDescription,
CrossCurrencyCurveParameters,
CrossCurrencyInstrumentDefinition,
CrossCurrencyInstrumentDescription,
CrossCurrencyInstrumentsSegment,
FieldDescription,
FieldFormulaDescription,
FormulaParameterDescription,
FxForwardInstrumentDefinition,
FxForwardInstrumentDescription,
FxForwardTurnFields,
FxSpotInstrumentDefinition,
FxSpotInstrumentDescription,
OverrideBidAsk,
OverrideBidAskFields,
OverrideFxForwardTurn,
TurnAdjustment,
)
from ...._curves._cross_currency_curves._definitions._create import (
CrossCurrencyCurveCreateDefinition,
)
from ...._curves._cross_currency_curves._definitions._update import (
CrossCurrencyCurveUpdateDefinition,
)
from ...._curves._cross_currency_curves._enums import (
InterpolationMode,
MainConstituentAssetClass,
RiskType,
)
from ...._curves._cross_currency_curves._definitions._enums import (
QuotationMode,
StandardTurnPeriod,
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_cross_currency_curves/definitions/__init__.py | 0.637144 | 0.249093 | __init__.py | pypi |
from typing import TYPE_CHECKING
from ...._curves._cross_currency_curves._definitions._search import (
CrossCurrencyCurveGetDefinitionItem,
)
from ......_content_type import ContentType
from ......_tools import create_repr
from ....._content_provider_layer import ContentProviderLayer
if TYPE_CHECKING:
from ...._curves._cross_currency_curves._types import (
OptMainConstituentAssetClass,
OptRiskType,
)
from ......_types import OptStr, OptBool, ExtendedParams
class Definition(ContentProviderLayer):
"""
Returns the definitions of the available Commodities curves for the filters
selected (e.g. sector, subSector...).
Parameters
----------
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
id : str, optional
The identifier of the cross currency definitions.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
valuation_date : str or date or datetime or timedelta, optional
The date used to define a list of curves or a unique cross currency curve that
can be priced at this date. the value is expressed in iso 8601 format:
yyyy-mm-dd (e.g., '2021-01-01').
extended_params : dict, optional
If necessary other parameters.
Examples
--------
>>> from refinitiv.data.content.ipa.curves._cross_currency_curves import definitions
>>> definition = definitions.search.Definition(
... base_currency="EUR",
... quoted_currency="CHF"
>>> )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
curve_tag: "OptStr" = None,
id: "OptStr" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
valuation_date: "OptDateTime" = None,
extended_params: "ExtendedParams" = None,
) -> None:
request_item = CrossCurrencyCurveGetDefinitionItem(
main_constituent_asset_class=main_constituent_asset_class,
risk_type=risk_type,
base_currency=base_currency,
base_index_name=base_index_name,
curve_tag=curve_tag,
id=id,
is_non_deliverable=is_non_deliverable,
name=name,
quoted_currency=quoted_currency,
quoted_index_name=quoted_index_name,
source=source,
valuation_date=valuation_date,
)
super().__init__(
content_type=ContentType.CROSS_CURRENCY_CURVES_DEFINITIONS_SEARCH,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self, middle_path="_cross_currency_curves.definitions.search") | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_cross_currency_curves/definitions/_search.py | 0.923472 | 0.473049 | _search.py | pypi |
from dataclasses import dataclass
from typing import List, TYPE_CHECKING
from .._arg_enums import main_constituent_asset_class_arg_parser, risk_type_arg_parser
from .._base_data_class import BaseData
from ......delivery._data._endpoint_data import EndpointData
if TYPE_CHECKING:
from ...._curves._cross_currency_curves._types import (
OptMainConstituentAssetClass,
OptRiskType,
)
from ......_types import OptStr, OptBool
_camel_to_snake = {
"mainConstituentAssetClass": "main_constituent_asset_class",
"riskType": "risk_type",
"baseCurrency": "base_currency",
"baseIndexName": "base_index_name",
"id": "id",
"isFallbackForFxCurveDefinition": "is_fallback_for_fx_curve_definition",
"isNonDeliverable": "is_non_deliverable",
"name": "name",
"quotedCurrency": "quoted_currency",
"quotedIndexName": "quoted_index_name",
"source": "source",
}
def convert_camel_to_snake(data: dict) -> dict:
return {_camel_to_snake.get(name, name): value for name, value in data.items()}
class CurveDefinitionTriangulate(BaseData):
"""
Gets the Cross Currency curve definitions who can be used with provided criterias.
Parameters
----------
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
id : str, optional
The identifier of the cross currency definitions.
is_fallback_for_fx_curve_definition : bool, optional
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
"""
def __init__(
self,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
id: "OptStr" = None,
is_fallback_for_fx_curve_definition: "OptBool" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
**kwargs,
):
self.main_constituent_asset_class = main_constituent_asset_class_arg_parser.get_enum(
main_constituent_asset_class
)
self.risk_type = risk_type_arg_parser.get_enum(risk_type)
self.base_currency = base_currency
self.base_index_name = base_index_name
self.id = id
self.is_fallback_for_fx_curve_definition = is_fallback_for_fx_curve_definition
self.is_non_deliverable = is_non_deliverable
self.name = name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.source = source
super().__init__(**kwargs)
class CurveDefinition:
def __init__(self, **kwargs):
self._direct_curve_definitions = None
self._indirect_curve_definitions = None
self._kwargs = kwargs
@property
def direct_curve_definitions(self):
if self._direct_curve_definitions is None:
self._direct_curve_definitions = []
direct_curves = self._kwargs.get("directCurveDefinitions")
self._direct_curve_definitions = self._create_list_definition_triangulates(direct_curves)
return self._direct_curve_definitions
@property
def indirect_curve_definitions(self):
if self._indirect_curve_definitions is None:
self._indirect_curve_definitions = []
indirect_curves = self._kwargs.get("indirectCurveDefinitions")
for indirect_curve in indirect_curves:
cross_currencies = indirect_curve.get("crossCurrencyDefinitions", [])
list_triangulates = self._create_list_definition_triangulates(cross_currencies)
self._indirect_curve_definitions.append(list_triangulates)
return self._indirect_curve_definitions
@property
def curve_tag(self):
return self._kwargs.get("curveTag")
def _create_list_definition_triangulates(self, items: list):
return [CurveDefinitionTriangulate(**convert_camel_to_snake(item)) for item in items]
@dataclass
class TriangulateDefinitionsData(EndpointData):
_curve_definitions: List[CurveDefinition] = None
@property
def curve_definitions(self):
if self._curve_definitions is None:
self._curve_definitions = [CurveDefinition(**item) for item in self.raw.get("data", [])]
return self._curve_definitions | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_cross_currency_curves/triangulate_definitions/_data_provider.py | 0.922071 | 0.311938 | _data_provider.py | pypi |
from typing import TYPE_CHECKING
from ...._curves._cross_currency_curves._triangulate_definitions import RequestItem
from ......_content_type import ContentType
from ......_tools import create_repr
from ....._content_provider_layer import ContentProviderLayer
if TYPE_CHECKING:
from ......_types import OptStr, ExtendedParams
class Definition(ContentProviderLayer):
"""
API endpoint for Financial Contract analytics,
that returns calculations relevant to each contract type.
Parameters
----------
base_currency : str, optional
The base currency pair. It is expressed in ISO 4217 alphabetical format
(e.g., 'EUR').
base_index_name : str, optional
The name of the floating rate index (e.g., 'ESTR') applied to the base currency.
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
quoted_currency : str, optional
The quoted currency pair. It is expressed in ISO 4217 alphabetical
format (e.g., 'USD').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'SOFR') applied to the
quoted currency.
valuation_date : str, optional
The valuation date.
extended_params : dict, optional
If necessary other parameters.
Examples
--------
>>> from refinitiv.data.content.ipa.curves._cross_currency_curves import triangulate_definitions
... definition = triangulate_definitions.search.Definition(
... base_currency="EUR",
... quoted_currency="CHF"
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
curve_tag: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
valuation_date: "OptStr" = None,
extended_params: "ExtendedParams" = None,
) -> None:
request_item = RequestItem(
base_currency=base_currency,
base_index_name=base_index_name,
curve_tag=curve_tag,
quoted_currency=quoted_currency,
quoted_index_name=quoted_index_name,
valuation_date=valuation_date,
)
super().__init__(
content_type=ContentType.CROSS_CURRENCY_CURVES_TRIANGULATE_DEFINITIONS_SEARCH,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self, middle_path="_cross_currency_curves.triangulate_definitions.search") | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_cross_currency_curves/triangulate_definitions/_search.py | 0.92632 | 0.306449 | _search.py | pypi |
from typing import TYPE_CHECKING
from ...._curves._bond_curves._curves._request import RequestItem
from ......_content_type import ContentType
from ......_tools import create_repr
from ....._content_provider_layer import ContentProviderLayer
if TYPE_CHECKING:
from ......_types import OptStr, ExtendedParams
from ...._curves._bond_curves._types import (
CurveDefinition,
CurveParameters,
OptCreditConstituents,
)
class Definition(ContentProviderLayer):
"""
Generates the Bond curves for the definitions provided.
Parameters
----------
constituents : CreditConstituents, optional
CreditConstituents object.
curve_definition : CreditCurveDefinition, optional
CreditCurveDefinition object.
curve_parameters : CreditCurveParameters, optional
CreditCurveParameters object.
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
extended_params : dict, optional
If necessary other parameters.
Methods
-------
get_data(session=session, on_response=on_response)
Returns a response to the data platform
get_data_async(session=None, on_response=None, async_mode=None)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.curves._bond_curves import curves
>>> definition = curves.Definition(
... curve_definition=curves.CreditCurveDefinition(
... reference_entity="0#EUGOVPBMK=R",
... reference_entity_type=curves.ReferenceEntityType.CHAIN_RIC
... ))
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
def __init__(
self,
constituents: "OptCreditConstituents" = None,
curve_definition: "CurveDefinition" = None,
curve_parameters: "CurveParameters" = None,
curve_tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
):
request_item = RequestItem(
constituents=constituents,
curve_definition=curve_definition,
curve_parameters=curve_parameters,
curve_tag=curve_tag,
)
super().__init__(
content_type=ContentType.BOND_CURVE,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self, middle_path="_bond_curves.curves") | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/curves/_bond_curves/curves/_definition.py | 0.923769 | 0.181173 | _definition.py | pypi |
from typing import TYPE_CHECKING, Union, Optional
from .._definition import BaseSurfaceDefinition
from ..._surfaces._cap_surface_request_item import CapSurfaceRequestItem
from ....._content_type import ContentType
if TYPE_CHECKING:
from . import CapSurfaceDefinition, CapCalculationParams
from ..._surfaces._surface_types import SurfaceLayout
from ....._types import ExtendedParams, OptStr
class Definition(BaseSurfaceDefinition):
"""
Create a Cap data Definition object.
Parameters
----------
surface_layout : SurfaceLayout
See details in SurfaceLayout class
surface_parameters : CapCalculationParams
See details in CapCalculationParams class
underlying_definition : dict or CapSurfaceDefinition
Dict or CapSurfaceDefinition object. See details in CapSurfaceDefinition class
Example:
{"instrumentCode": "USD"}
surface_tag : str, optional
A user defined string to describe the volatility surface
instrument_type : DEPRECATED
This attribute doesn't use anymore.
extended_params : dict, optional
If necessary other parameters
Methods
-------
get_data(session=session, on_response=on_response, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.surfaces import cap
>>> definition = cap.Definition(
... underlying_definition=cap.CapSurfaceDefinition(
... instrument_code="USD",
... reference_caplet_tenor="3M",
... discounting_type=cap.DiscountingType.OIS_DISCOUNTING
... ),
... surface_tag="USD_Strike__Tenor_",
... surface_layout=cap.SurfaceLayout(
... format=cap.Format.MATRIX
... ),
... surface_parameters=cap.CapCalculationParams(
... x_axis=cap.Axis.STRIKE,
... y_axis=cap.Axis.TENOR,
... calculation_date="2020-03-20"
... )
>>> )
"""
def __init__(
self,
surface_layout: "SurfaceLayout" = None,
surface_parameters: Optional["CapCalculationParams"] = None,
underlying_definition: Union[dict, "CapSurfaceDefinition"] = None,
surface_tag: "OptStr" = None,
instrument_type=None,
extended_params: "ExtendedParams" = None,
):
request_item = CapSurfaceRequestItem(
instrument_type=instrument_type,
surface_layout=surface_layout,
surface_params=surface_parameters,
underlying_definition=underlying_definition,
surface_tag=surface_tag,
)
super().__init__(
content_type=ContentType.SURFACES,
universe=request_item,
extended_params=extended_params,
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/surfaces/cap/_definition.py | 0.934887 | 0.309219 | _definition.py | pypi |
from typing import TYPE_CHECKING, Union, Optional
from .._definition import BaseSurfaceDefinition
from ..._surfaces._swaption_surface_request_item import SwaptionSurfaceRequestItem
from ....._content_type import ContentType
if TYPE_CHECKING:
from . import SwaptionSurfaceDefinition, SwaptionCalculationParams
from ..._surfaces._surface_types import SurfaceLayout
from ....._types import ExtendedParams, OptStr
class Definition(BaseSurfaceDefinition):
"""
Create a Swaption data Definition object.
Parameters
----------
instrument_type : DEPRECATED
This attribute doesn't use anymore.
surface_layout : SurfaceLayout
See details in SurfaceLayout class
surface_parameters : SwaptionCalculationParams
See details in SwaptionCalculationParams class
underlying_definition : dict or EtiSurfaceDefinition
Dict or EtiSurfaceDefinition object. See details in EtiSurfaceDefinition class
Example:
{"fxCrossCode": "EURUSD"}
surface_tag : str, optional
A user defined string to describe the volatility surface
extended_params : dict, optional
If necessary other parameters
Methods
-------
get_data(session=session, on_response=on_response, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.surfaces import swaption
>>> definition = swaption.Definition(
... underlying_definition=swaption.SwaptionSurfaceDefinition(
... instrument_code="USD",
... discounting_type=swaption.DiscountingType.OIS_DISCOUNTING
... ),
... surface_tag="USD_Strike__Tenor_",
... surface_layout=swaption.SurfaceLayout(
... format=swaption.Format.MATRIX
... ),
... surface_parameters=swaption.SwaptionCalculationParams(
... x_axis=swaption.Axis.TENOR,
... y_axis=swaption.Axis.STRIKE,
... calculation_date="2020-03-20"
... )
>>> )
"""
def __init__(
self,
instrument_type=None,
surface_layout: "SurfaceLayout" = None,
surface_parameters: Optional["SwaptionCalculationParams"] = None,
underlying_definition: Union[dict, "SwaptionSurfaceDefinition"] = None,
surface_tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
):
request_item = SwaptionSurfaceRequestItem(
instrument_type=instrument_type,
surface_layout=surface_layout,
surface_parameters=surface_parameters,
underlying_definition=underlying_definition,
surface_tag=surface_tag,
)
super().__init__(
content_type=ContentType.SURFACES_SWAPTION,
universe=request_item,
extended_params=extended_params,
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/surfaces/swaption/_definition.py | 0.930844 | 0.215309 | _definition.py | pypi |
from typing import TYPE_CHECKING, Union
from .._definition import BaseSurfaceDefinition
from ..._surfaces._fx_surface_request_item import FxSurfaceRequestItem
from ....._content_type import ContentType
from ....._tools import create_repr
if TYPE_CHECKING:
from . import FxSurfaceDefinition
from ..._surfaces._surface_types import SurfaceParameters, SurfaceLayout
from ....._types import ExtendedParams, OptStr
class Definition(BaseSurfaceDefinition):
"""
Create a Fx data Definition object.
Parameters
----------
surface_layout : SurfaceLayout
See details in SurfaceLayout class
surface_parameters : SurfaceParameters
See details in SurfaceParameters class
underlying_definition : dict or FxSurfaceDefinition
Dict or FxSurfaceDefinition object. See details in FxSurfaceDefinition class
Example:
{"fxCrossCode": "EURUSD"}
surface_tag : str, optional
A user defined string to describe the volatility surface
extended_params : dict, optional
If necessary other parameters
Methods
-------
get_data(session=session, on_response=on_response, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.surfaces import fx
>>> definition = fx.Definition(
... underlying_definition={"fxCrossCode": "EURUSD"},
... surface_tag="FxVol-EURUSD",
... surface_layout=fx.SurfaceLayout(
... format=fx.Format.MATRIX
... ),
... surface_parameters=fx.FxCalculationParams(
... x_axis=fx.Axis.DATE,
... y_axis=fx.Axis.STRIKE,
... calculation_date="2018-08-20T00:00:00Z"
... )
...)
>>>
"""
def __init__(
self,
surface_layout: "SurfaceLayout" = None,
surface_parameters: "SurfaceParameters" = None,
underlying_definition: Union[dict, "FxSurfaceDefinition"] = None,
surface_tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
):
request_item = FxSurfaceRequestItem(
surface_layout=surface_layout,
surface_parameters=surface_parameters,
underlying_definition=underlying_definition,
surface_tag=surface_tag,
)
super().__init__(
content_type=ContentType.SURFACES,
universe=request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/surfaces/fx/_definition.py | 0.916887 | 0.274442 | _definition.py | pypi |
from typing import TYPE_CHECKING, Union, Optional
from .._definition import BaseSurfaceDefinition
from ..._surfaces._eti_surface_request_item import EtiSurfaceRequestItem
from ....._content_type import ContentType
if TYPE_CHECKING:
from . import EtiCalculationParams, EtiSurfaceDefinition
from ..._surfaces._surface_types import SurfaceLayout
from ....._types import ExtendedParams, OptStr
class Definition(BaseSurfaceDefinition):
"""
Create a Eti data Definition object.
Parameters
----------
surface_layout : SurfaceLayout
See details in SurfaceLayout class
surface_parameters : EtiCalculationParams
See details in EtiCalculationParams class
underlying_definition : dict or EtiSurfaceDefinition
Dict or EtiSurfaceDefinition object. See details in EtiSurfaceDefinition class
Example:
{"instrumentCode": "USD"}
surface_tag : str, optional
A user defined string to describe the volatility surface
extended_params : dict, optional
If necessary other parameters
Methods
-------
get_data(session=session, on_response=on_response, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.surfaces import eti
>>> definition = eti.Definition(
... underlying_definition=eti.EtiSurfaceDefinition(instrument_code="USD"),
... surface_tag="USD_Strike__Tenor_",
... surface_layout=eti.SurfaceLayout(
... format=eti.Format.MATRIX
... ),
... surface_parameters=eti.EtiCalculationParams(
... x_axis=eti.Axis.TENOR,
... y_axis=eti.Axis.STRIKE,
... calculation_date="2020-03-20"
... )
>>> )
"""
def __init__(
self,
surface_layout: "SurfaceLayout" = None,
surface_parameters: Optional["EtiCalculationParams"] = None,
underlying_definition: Union[dict, "EtiSurfaceDefinition"] = None,
surface_tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
):
request_item = EtiSurfaceRequestItem(
surface_layout=surface_layout,
surface_parameters=surface_parameters,
underlying_definition=underlying_definition,
surface_tag=surface_tag,
)
super().__init__(
content_type=ContentType.SURFACES,
universe=request_item,
extended_params=extended_params,
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/surfaces/eti/_definition.py | 0.938379 | 0.236428 | _definition.py | pypi |
from enum import unique
from ...._base_enum import StrEnum
@unique
class RedemptionDateType(StrEnum):
"""
- RedemptionAtAverageLife : yield and price are computed at average life (case
of sinkable bonds)
- RedemptionAtBestDate : yield and price are computed at the highest yield date.
- RedemptionAtCallDate : yield and price are computed at call date (next call
date by default).
- RedemptionAtCustomDate : yield and price are computed at custom date specified in RedemptionDate parameter.
- RedemptionAtMakeWholeCallDate : yield and price are computed at Make Whole
Call date.
- RedemptionAtMaturityDate : yield and price are computed at maturity date.
- RedemptionAtNextDate : yield and price are computed at next redemption date
available.
- RedemptionAtParDate : yield and price are computed at next par.
- RedemptionAtPremiumDate : yield and price are computed at next premium.
- RedemptionAtPutDate : yield and price are computed at put date (next put date
by default)..
- RedemptionAtSinkDate : yield and price are computed at sinking fund date.
- RedemptionAtWorstDate : yield and price are computed at the lowest yield date.
"""
REDEMPTION_AT_AVERAGE_LIFE = "RedemptionAtAverageLife"
REDEMPTION_AT_BEST_DATE = "RedemptionAtBestDate"
REDEMPTION_AT_CALL_DATE = "RedemptionAtCallDate"
REDEMPTION_AT_CUSTOM_DATE = "RedemptionAtCustomDate"
REDEMPTION_AT_MAKE_WHOLE_CALL_DATE = "RedemptionAtMakeWholeCallDate"
REDEMPTION_AT_MATURITY_DATE = "RedemptionAtMaturityDate"
REDEMPTION_AT_NEXT_DATE = "RedemptionAtNextDate"
REDEMPTION_AT_PAR_DATE = "RedemptionAtParDate"
REDEMPTION_AT_PARTIAL_CALL_DATE = "RedemptionAtPartialCallDate"
REDEMPTION_AT_PARTIAL_PUT_DATE = "RedemptionAtPartialPutDate"
REDEMPTION_AT_PERPETUITY = "RedemptionAtPerpetuity"
REDEMPTION_AT_PREMIUM_DATE = "RedemptionAtPremiumDate"
REDEMPTION_AT_PUT_DATE = "RedemptionAtPutDate"
REDEMPTION_AT_SINK_DATE = "RedemptionAtSinkDate"
REDEMPTION_AT_WORST_DATE = "RedemptionAtWorstDate" | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_enums/_redemption_date_type.py | 0.779238 | 0.626638 | _redemption_date_type.py | pypi |
from dataclasses import dataclass
from typing import List
import pandas as pd
from dateutil import parser
from pandas.tseries.holiday import Holiday as PandasHoliday, nearest_workday
from .._content_data_validator import ContentDataValidator
from .._request_factory import DatesAndCalendarsResponseFactory
from ...._content_data import Data
from ...._content_data_provider import ContentDataProvider
from ....._tools import add_periods_datetime_adapter, create_repr
from ....._types import OptDateTime
from .....content.ipa._content_provider import DatesAndCalendarsRequestFactory
from .....delivery._data._data_provider import ValidatorContainer
@dataclass
class HolidayName:
name: str
calendars: list
countries: list
def holiday_name_from_dict(datum: dict):
return HolidayName(
name=datum["name"],
calendars=datum["calendars"],
countries=datum["countries"],
)
class Holiday(PandasHoliday):
_holiday_names = None
def __init__(
self,
date: "OptDateTime" = None,
name: str = None,
holiday: dict = None,
tag: str = "",
):
self._holiday = holiday or {}
if self._holiday.get("names"):
name = self._holiday.get("names")[0]["name"]
elif not name:
name = "Name not requested"
if date is not None:
date = add_periods_datetime_adapter.get_str(date)
else:
date = self._holiday.get("date")
year, month, day = pd.NA, pd.NA, pd.NA
if date:
_date = parser.parse(date)
year, month, day = _date.year, _date.month, _date.day
PandasHoliday.__init__(
self,
name=name,
year=year,
month=month,
day=day,
observance=nearest_workday,
)
self._date = date or self._holiday.get("date", "Date not requested")
self._tag = tag
self._countries = self._holiday.get("countries", [])
self._calendars = self._holiday.get("calendars", [])
@property
def date(self):
return self._date
@property
def countries(self):
return self._countries
@property
def calendars(self):
return self._calendars
@property
def names(self) -> List[HolidayName]:
if self._holiday_names is None:
self._holiday_names = [
holiday_name_from_dict(holiday_name) for holiday_name in self._holiday.get("names", [])
]
return self._holiday_names
@property
def tag(self):
return self._tag
def __repr__(self):
return create_repr(
self,
class_name="HolidayData",
content="representation of 'holidayOutputs' response",
)
@dataclass
class HolidaysData(Data):
_holidays: List[Holiday] = None
@property
def holidays(self) -> List[Holiday]:
if self._holidays is None:
self._holidays = [
Holiday(holiday=holiday, tag=raw_item.get("tag"))
for raw_item in self.raw
if not raw_item.get("error")
for holiday in raw_item["holidays"]
]
return self._holidays
holidays_data_provider = ContentDataProvider(
request=DatesAndCalendarsRequestFactory(),
response=DatesAndCalendarsResponseFactory(data_class=HolidaysData),
validator=ValidatorContainer(content_validator=ContentDataValidator()),
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/holidays/_holidays_data_provider.py | 0.829768 | 0.331431 | _holidays_data_provider.py | pypi |
from typing import List, Optional, Union, TYPE_CHECKING
from numpy import iterable
from ._holidays_data_provider import HolidaysData
from .._base_request_items import StartEndDateBase
from ..._enums import HolidayOutputs
from ...._content_provider_layer import ContentUsageLoggerMixin
from ....._content_type import ContentType
from ....._tools import create_repr, try_copy_to_list
from .....delivery._data._data_provider import DataProviderLayer, BaseResponse
if TYPE_CHECKING:
from ....._types import ExtendedParams, OptStr, OptDateTime, OptStrStrs
class HolidaysRequestItem(StartEndDateBase):
def __init__(self, tag, start_date, end_date, calendars, currencies, holiday_outputs):
super().__init__(start_date, end_date)
self.tag = tag
self.calendars = calendars
self.currencies = currencies
self.holiday_outputs = holiday_outputs
@property
def tag(self):
"""
:return: str
"""
return self._get_parameter("tag")
@tag.setter
def tag(self, value):
self._set_parameter("tag", value)
@property
def calendars(self):
"""
:return: list
"""
return self._get_parameter("calendars")
@calendars.setter
def calendars(self, value):
self._set_parameter("calendars", value)
@property
def currencies(self):
"""
:return: list
"""
return self._get_parameter("currencies")
@currencies.setter
def currencies(self, value):
self._set_parameter("currencies", value)
@property
def holiday_outputs(self):
"""
:return: list
"""
return self._get_list_of_enums(HolidayOutputs, "holidayOutputs")
@holiday_outputs.setter
def holiday_outputs(self, value):
self._set_list_of_enums(HolidayOutputs, "holidayOutputs", value)
class Definition(
ContentUsageLoggerMixin[BaseResponse[HolidaysData]],
DataProviderLayer[BaseResponse[HolidaysData]],
):
"""
Holidays definition object
Parameters
----------
start_date: str or datetime or timedelta
Start date of calculation.
end_date: str or datetime or timedelta
End date of calculation.
tag: str, optional
Reference tag to map particular response in payload.
calendars: list of str, optional
Calendars to use the date for working day or weekend.
Optional if currencies is provided.
currencies: list of str, optional
Currencies to use the date for working day or weekend.
Optional if calendars is provided.
holiday_outputs : HolidayOutputs or list of str, optional
In case if test date is holiday you may request additional information about the holiday.
Possible options are: Date, Names, Calendars, Countries
extended_params : dict, optional
If necessary other parameters.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform.
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform.
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import holidays
>>>
>>> definition = holidays.Definition(
... tag="my request",
... start_date=datetime.datetime(2020, 5, 2),
... end_date=datetime.timedelta(-30),
... calendars=["UKR", "FRA"],
... currencies=["EUR"],
... holiday_outputs=["Date", "Names", "Calendars", "Countries"]
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.HolidaysDefinition"
def __init__(
self,
start_date: "OptDateTime" = None,
end_date: "OptDateTime" = None,
tag: "OptStr" = None,
calendars: "OptStrStrs" = None,
currencies: "OptStrStrs" = None,
holiday_outputs: Optional[Union[List[HolidayOutputs], List[str]]] = None,
extended_params: "ExtendedParams" = None,
):
calendars = try_copy_to_list(calendars)
currencies = try_copy_to_list(currencies)
holiday_outputs = try_copy_to_list(holiday_outputs)
self.extended_params = extended_params
self.request_item = HolidaysRequestItem(
tag=tag,
start_date=start_date,
end_date=end_date,
calendars=calendars,
currencies=currencies,
holiday_outputs=holiday_outputs,
)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_HOLIDAYS,
universe=[self.request_item],
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self)
DefnDefns = Union[List[Definition], Definition]
class Definitions(
ContentUsageLoggerMixin[BaseResponse[HolidaysData]],
DataProviderLayer[BaseResponse[HolidaysData]],
):
"""
Holidays definitions object
Parameters
----------
universe: Definition or list of Definition objects
List of initialized Definition objects to retrieve data.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import holidays
>>>
>>> first_definition = holidays.Definition(
... tag="my request",
... start_date=datetime.datetime(2020, 5, 2),
... end_date=datetime.timedelta(-30),
... calendars=["UKR", "FRA"],
... currencies=["EUR"],
... holiday_outputs=["Date", "Names", "Calendars", "Countries"]
... )
...
>>>
>>> second_definition = holidays.Definition(
... tag="my second request",
... start_date="2020-01-01",
... end_date=datetime.timedelta(0),
... calendars=["UKR", "FRA"],
... currencies=["EUR"],
... holiday_outputs=["Date", "Names", "Calendars", "Countries"]
... )
>>> response = holidays.Definitions([first_definition, second_definition]).get_data()
Using get_data_async
>>> import asyncio
>>> task = holidays.Definitions([first_definition, second_definition]).get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.HolidaysDefinitions"
def __init__(self, universe: "DefnDefns"):
universe = try_copy_to_list(universe)
if not iterable(universe):
universe = [universe]
request_items = []
extended_params = []
for item in universe:
request_items.append(item.request_item)
extended_params.append(item.extended_params)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_HOLIDAYS,
universe=request_items,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/holidays/_holidays.py | 0.894712 | 0.342214 | _holidays.py | pypi |
from dataclasses import dataclass
from typing import List, Union
from .._content_data_validator import ContentDataValidator
from .._request_factory import DatesAndCalendarsResponseFactory
from ..holidays._holidays_data_provider import Holiday
from ...._content_data import Data
from ...._content_data_provider import ContentDataProvider
from ...._df_builder import build_dates_calendars_df
from .....content.ipa._content_provider import DatesAndCalendarsRequestFactory
from .....delivery._data._data_provider import ValidatorContainer
@dataclass
class Period:
date: str
holidays: Union[list, None]
tag: str = ""
def period_from_dict(datum: dict):
tag = datum.get("tag")
holidays = datum.get("holidays", [])
holidays = [Holiday(holiday=holiday, tag=tag) for holiday in holidays]
return Period(date=datum["date"], holidays=holidays, tag=tag)
@dataclass
class AddedPeriods(Data):
_added_periods: List = None
@property
def added_periods(self):
if self._added_periods is None:
self._added_periods = [period_from_dict(raw_item) for raw_item in self.raw if not raw_item.get("error")]
return self._added_periods
def __getitem__(self, item):
return self.added_periods[item]
@dataclass
class AddedPeriod(Data):
_period: Period = None
@property
def added_period(self):
return self._period
class AddPeriodsResponseFactory(DatesAndCalendarsResponseFactory):
def create_data_success(self, raw: List[dict], **kwargs):
if len(raw) > 1:
data = AddedPeriods(raw, _dfbuilder=build_dates_calendars_df)
else:
raw_item = raw[0]
data = AddedPeriod(
raw=raw,
_period=period_from_dict(raw_item),
_dfbuilder=build_dates_calendars_df,
)
return data
add_period_data_provider = ContentDataProvider(
request=DatesAndCalendarsRequestFactory(),
response=AddPeriodsResponseFactory(),
validator=ValidatorContainer(content_validator=ContentDataValidator()),
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/add_periods/_add_periods_data_provider.py | 0.870101 | 0.289472 | _add_periods_data_provider.py | pypi |
from datetime import datetime, timedelta
from typing import List, Optional, Union, TYPE_CHECKING
from numpy import iterable
from ._add_periods_data_provider import AddedPeriod, AddedPeriods
from .._base_request_items import StartDateBase
from ..._enums import DateMovingConvention, EndOfMonthConvention, HolidayOutputs
from ...._content_provider_layer import ContentUsageLoggerMixin
from ....._content_type import ContentType
from ....._tools import create_repr, make_enum_arg_parser, try_copy_to_list
from .....delivery._data._data_provider import DataProviderLayer, BaseResponse
if TYPE_CHECKING:
from ....._types import ExtendedParams, OptDateTime, OptStrStrs
from ..._enums._holiday_outupts import OptHolidayOutputs
holiday_outputs_arg_parser = make_enum_arg_parser(HolidayOutputs)
class DatePeriodsRequestItem(StartDateBase):
def __init__(
self,
start_date: Union[str, datetime, timedelta] = None,
period: str = None,
calendars: Optional[List[str]] = None,
currencies: Optional[List[str]] = None,
tag: Optional[str] = None,
date_moving_convention: Optional[DateMovingConvention] = None,
end_of_month_convention: Optional[EndOfMonthConvention] = None,
holiday_outputs: Optional[List[HolidayOutputs]] = None,
):
super().__init__(start_date)
self.tag = tag
self.period = period
self.calendars = calendars
self.currencies = currencies
self.date_moving_convention = date_moving_convention
self.end_of_month_convention = end_of_month_convention
self.holiday_outputs = holiday_outputs
@property
def tag(self):
"""
:return: str
"""
return self._get_parameter("tag")
@tag.setter
def tag(self, value):
self._set_parameter("tag", value)
@property
def period(self):
"""
:return: str
"""
return self._get_parameter("period")
@period.setter
def period(self, value):
self._set_parameter("period", value)
@property
def calendars(self):
"""
:return: list
"""
return self._get_parameter("calendars")
@calendars.setter
def calendars(self, value):
self._set_parameter("calendars", value)
@property
def currencies(self):
"""
:return: list
"""
return self._get_parameter("currencies")
@currencies.setter
def currencies(self, value):
self._set_parameter("currencies", value)
@property
def date_moving_convention(self):
"""
:return: DateMovingConvention
"""
return self._get_enum_parameter(DateMovingConvention, "dateMovingConvention")
@date_moving_convention.setter
def date_moving_convention(self, value):
self._set_enum_parameter(DateMovingConvention, "dateMovingConvention", value)
@property
def end_of_month_convention(self):
"""
:return: EndOfMonthConvention
"""
return self._get_enum_parameter(EndOfMonthConvention, "endOfMonthConvention")
@end_of_month_convention.setter
def end_of_month_convention(self, value):
self._set_enum_parameter(EndOfMonthConvention, "endOfMonthConvention", value)
@property
def holiday_outputs(self):
"""
:return: list
"""
return self._get_list_of_enums(HolidayOutputs, "holidayOutputs")
@holiday_outputs.setter
def holiday_outputs(self, value):
self._set_list_of_enums(HolidayOutputs, "holidayOutputs", value)
class Definition(
ContentUsageLoggerMixin[BaseResponse[AddedPeriod]],
DataProviderLayer[BaseResponse[AddedPeriod]],
):
"""
Add periods definition object
Parameters
----------
start_date: str or datetime or timedelta
Start date of calculation.
period: str
String representing the tenor.
calendars: list of str, optional
Calendars to use the date for working day or weekend.
Optional if currencies is provided.
currencies: list of str, optional
Currencies to use the date for working day or weekend.
Optional if calendars is provided.
tag: str, optional
Reference tag to map particular response in payload.
date_moving_convention : DateMovingConvention or str, optional
The method to adjust dates.
end_of_month_convention : EndOfMonthConvention or str, optional
End of month convention.
holiday_outputs : HolidayOutputs or list of str, optional
In case if test date is holiday you may request additional information about the holiday.
Possible options are: Date, Names, Calendars, Countries
extended_params : dict, optional
If necessary other parameters.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> from refinitiv.data.content.ipa.dates_and_calendars import add_periods
>>> definition = add_periods.Definition(
... start_date="2020-01-01",
... period="4D",
... calendars=["BAR", "KOR", "JAP"],
... currencies=["USD"],
... tag="my request",
... date_moving_convention=add_periods.DateMovingConvention.NEXT_BUSINESS_DAY,
... end_of_month_convention=add_periods.EndOfMonthConvention.LAST,
... holiday_outputs=["Date", "Calendars", "Names"]
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.AddPeriodsDefinition"
def __init__(
self,
start_date: "OptDateTime" = None,
period: str = None,
calendars: "OptStrStrs" = None,
currencies: "OptStrStrs" = None,
tag: Optional[str] = None,
date_moving_convention: Union[DateMovingConvention, str, None] = None,
end_of_month_convention: Union[EndOfMonthConvention, str, None] = None,
holiday_outputs: "OptHolidayOutputs" = None,
extended_params: "ExtendedParams" = None,
):
self.extended_params = extended_params
calendars = try_copy_to_list(calendars)
currencies = try_copy_to_list(currencies)
if holiday_outputs:
holiday_outputs = try_copy_to_list(holiday_outputs)
holiday_outputs = holiday_outputs_arg_parser.get_list(holiday_outputs)
self.request_item = DatePeriodsRequestItem(
start_date=start_date,
period=period,
calendars=calendars,
currencies=currencies,
tag=tag,
date_moving_convention=date_moving_convention,
end_of_month_convention=end_of_month_convention,
holiday_outputs=holiday_outputs,
)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_ADD_PERIODS,
universe=[self.request_item],
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self)
DefnDefns = Union[List[Definition], Definition]
class Definitions(
ContentUsageLoggerMixin[BaseResponse[AddedPeriods]],
DataProviderLayer[BaseResponse[AddedPeriods]],
):
"""
Add periods definitions object
Parameters
----------
universe: Definition or list of Definition objects
List of initialized Definition objects to retrieve data.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import add_periods
>>>
>>> first_definition = add_periods.Definition(
... tag="first",
... start_date="2020-01-01",
... period="4D",
... calendars=["BAR", "KOR", "JAP"],
... currencies=["USD"],
... date_moving_convention=add_periods.DateMovingConvention.NEXT_BUSINESS_DAY,
... end_of_month_convention=add_periods.EndOfMonthConvention.LAST,
... holiday_outputs=["Date", "Calendars", "Names"]
... )
>>> second_definition = add_periods.Definition(
... tag="second",
... start_date="2018-01-01",
... period="4D",
... calendars=["BAR", "JAP"],
... currencies=["USD"],
... date_moving_convention=add_periods.DateMovingConvention.NEXT_BUSINESS_DAY,
... end_of_month_convention=add_periods.EndOfMonthConvention.LAST28,
... holiday_outputs=[add_periods.HolidayOutputs.DATE, add_periods.HolidayOutputs.NAMES]
... )
>>> response = add_periods.Definitions([first_definition, second_definition]).get_data()
Using get_data_async
>>> import asyncio
>>> task = add_periods.Definitions([first_definition, second_definition]).get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.AddPeriodsDefinitions"
def __init__(self, universe: "DefnDefns"):
universe = try_copy_to_list(universe)
if not iterable(universe):
universe = [universe]
request_items = []
extended_params = []
for item in universe:
request_items.append(item.request_item)
extended_params.append(item.extended_params)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_ADD_PERIODS,
universe=request_items,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/add_periods/_definition.py | 0.908196 | 0.292453 | _definition.py | pypi |
from datetime import datetime, timedelta
from typing import List, Optional, Union, TYPE_CHECKING
from numpy import iterable
from ._count_periods_data_provider import CountedPeriod, CountedPeriods
from .._base_request_items import StartEndDateBase
from ..._enums import DayCountBasis, PeriodType
from ...._content_provider_layer import ContentUsageLoggerMixin
from ....._content_type import ContentType
from ....._tools import create_repr, try_copy_to_list
from .....delivery._data._data_provider import DataProviderLayer, BaseResponse
if TYPE_CHECKING:
from ....._types import ExtendedParams, OptDateTime, OptStrStrs
class CountPeriodsRequestItem(StartEndDateBase):
def __init__(
self,
tag: Optional[str],
start_date: Union[str, datetime, timedelta],
end_date: Union[str, datetime, timedelta],
period_type: Optional[PeriodType],
calendars: Optional[List[str]],
currencies: Optional[List[str]],
day_count_basis,
):
super().__init__(start_date, end_date)
self.tag = tag
self.calendars = calendars
self.period_type = period_type
self.currencies = currencies
self.day_count_basis = day_count_basis
@property
def tag(self):
"""
:return: str
"""
return self._get_parameter("tag")
@tag.setter
def tag(self, value):
self._set_parameter("tag", value)
@property
def calendars(self):
"""
:return: list
"""
return self._get_parameter("calendars")
@calendars.setter
def calendars(self, value):
"""
:return: list
"""
self._set_parameter("calendars", value)
@property
def period_type(self):
"""
:return: PeriodType
"""
return self._get_enum_parameter(PeriodType, "periodType")
@period_type.setter
def period_type(self, value):
self._set_enum_parameter(PeriodType, "periodType", value)
@property
def currencies(self):
"""
:return: list
"""
return self._get_parameter("currencies")
@currencies.setter
def currencies(self, value):
self._set_parameter("currencies", value)
@property
def day_count_basis(self):
"""
:return: DayCountBasis
"""
return self._get_enum_parameter(DayCountBasis, "dayCountBasis")
@day_count_basis.setter
def day_count_basis(self, value):
self._set_enum_parameter(DayCountBasis, "dayCountBasis", value)
class Definition(
ContentUsageLoggerMixin[BaseResponse[CountedPeriod]],
DataProviderLayer[BaseResponse[CountedPeriod]],
):
"""
Count periods definition object
Parameters
----------
start_date: str or datetime or timedelta
Start date of calculation.
end_date: str or datetime or timedelta
End date of calculation.
tag: str, optional
Reference tag to map particular response in payload.
period_type : PeriodType or str, optional
The method we chose to count the period of time based on value from PeriodType enumeration.
calendars: list of str, optional
Calendars to use the date for working day or weekend.
Optional if currencies is provided.
currencies: list of str, optional
Currencies to use the date for working day or weekend.
Optional if calendars is provided.
day_count_basis: DayCountBasis or str, optional
Day count basis value from DayCountBasis enumeration.
extended_params : dict, optional
If necessary other parameters.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import count_periods
>>> definition = count_periods.Definition(
... tag="my request",
... start_date=datetime.timedelta(-11),
... end_date=datetime.timedelta(-3),
... period_type=count_periods.PeriodType.WORKING_DAY,
... calendars=["EMU"],
... currencies=["EUR"],
... day_count_basis=count_periods.DayCountBasis.DCB_30_360
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.CountPeriodsDefinition"
def __init__(
self,
start_date: "OptDateTime" = None,
end_date: "OptDateTime" = None,
tag: Optional[str] = None,
period_type: Optional[Union[PeriodType, str]] = None,
calendars: "OptStrStrs" = None,
currencies: "OptStrStrs" = None,
day_count_basis: Optional[Union[DayCountBasis, str]] = None,
extended_params: "ExtendedParams" = None,
):
calendars = try_copy_to_list(calendars)
currencies = try_copy_to_list(currencies)
self.extended_params = extended_params
self.request_item = CountPeriodsRequestItem(
tag=tag,
start_date=start_date,
end_date=end_date,
period_type=period_type,
calendars=calendars,
currencies=currencies,
day_count_basis=day_count_basis,
)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_COUNT_PERIODS,
universe=[self.request_item],
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self)
DefnDefns = Union[List[Definition], Definition]
class Definitions(
ContentUsageLoggerMixin[BaseResponse[CountedPeriods]],
DataProviderLayer[BaseResponse[CountedPeriods]],
):
"""
Count periods definitions object
Parameters
----------
universe: Definition or list of Definition objects
List of initialized Definition objects to retrieve data.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import count_periods
>>> first_definition = count_periods.Definition(
... tag="my request",
... start_date=datetime.timedelta(-11),
... end_date=datetime.timedelta(-3),
... period_type=count_periods.PeriodType.WORKING_DAY,
... calendars=["EMU"],
... currencies=["EUR"],
... day_count_basis=count_periods.DayCountBasis.DCB_30_360
... )
...
>>> second_definition = count_periods.Definition(
... tag="my second request",
... start_date=datetime.timedelta(-15),
... end_date=datetime.timedelta(-10),
... period_type=count_periods.PeriodType.NON_WORKING_DAY,
... calendars=["EMU"],
... currencies=["EUR"],
... day_count_basis=count_periods.DayCountBasis.DCB_30_360
... )
>>> response = count_periods.Definitions([first_definition, second_definition]).get_data()
Using get_data_async
>>> import asyncio
>>> task = count_periods.Definitions([first_definition, second_definition]).get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.CountPeriodsDefinitions"
def __init__(self, universe: "DefnDefns"):
universe = try_copy_to_list(universe)
if not iterable(universe):
universe = [universe]
request_items = []
extended_params = []
for item in universe:
request_items.append(item.request_item)
extended_params.append(item.extended_params)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_COUNT_PERIODS,
universe=request_items,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/count_periods/_count_periods.py | 0.928571 | 0.404478 | _count_periods.py | pypi |
from typing import Optional, Union, TYPE_CHECKING
from ._date_schedule_data_provider import DateSchedule
from .._base_request_items import StartEndDateBase
from ...._content_provider_layer import ContentUsageLoggerMixin
from ..._enums import DateScheduleFrequency, DayOfWeek
from ....._content_type import ContentType
from ....._tools import create_repr, try_copy_to_list
from .....delivery._data._data_provider import DataProviderLayer, BaseResponse
if TYPE_CHECKING:
from ....._types import ExtendedParams, OptInt, OptDateTime, OptStrStrs
class DateScheduleRequestItem(StartEndDateBase):
def __init__(
self,
start_date,
end_date,
count,
frequency,
calendars,
currencies,
day_of_week,
calendar_day_of_month,
):
super().__init__(start_date, end_date)
self.count = count
self.frequency = frequency
self.calendars = calendars
self.currencies = currencies
self.day_of_week = day_of_week
self.calendar_day_of_month = calendar_day_of_month
@property
def count(self):
"""
:return: int
"""
return self._get_parameter("count")
@count.setter
def count(self, value):
self._set_parameter("count", value)
@property
def calendars(self):
"""
:return: list
"""
return self._get_parameter("calendars")
@calendars.setter
def calendars(self, value):
self._set_parameter("calendars", value)
@property
def currencies(self):
"""
:return: list
"""
return self._get_parameter("currencies")
@currencies.setter
def currencies(self, value):
self._set_parameter("currencies", value)
@property
def frequency(self):
"""
:return: DateScheduleFrequency
"""
return self._get_enum_parameter(DateScheduleFrequency, "frequency")
@frequency.setter
def frequency(self, value):
self._set_enum_parameter(DateScheduleFrequency, "frequency", value)
@property
def day_of_week(self):
"""
:return: DayOfWeek
"""
return self._get_enum_parameter(DayOfWeek, "DayOfWeek")
@day_of_week.setter
def day_of_week(self, value):
self._set_enum_parameter(DayOfWeek, "DayOfWeek", value)
@property
def calendar_day_of_month(self):
"""
:return: str
"""
return self._get_parameter("calendarDayOfMonth")
@calendar_day_of_month.setter
def calendar_day_of_month(self, value):
self._set_parameter("calendarDayOfMonth", value)
class Definition(
ContentUsageLoggerMixin[BaseResponse[DateSchedule]],
DataProviderLayer[BaseResponse[DateSchedule]],
):
"""
Date schedule definition object
Parameters
----------
frequency: DateScheduleFrequency or str
The frequency of dates in the predefined period.
start_date: str or datetime or timedelta, optional
The start date of the predetermined list of dates.
The start date must be earlier or equal to the end date.
Mandatory if endDate is in the past.
end_date: str or datetime or timedelta, optional
The end date of the predetermined list of dates.
If start_date is not set end_date is used to
define a list of dates from today to the end date;
end_date and count should not be set at a time;
end_date must be later or equal to start_date.
Mandatory if count is not specified.
calendar_day_of_month : int, optional
The number of the day of the month to which dates are adjusted.
The first date in the list is defined as the corresponding
day of the month to which the start date belongs.
Mandatory if frequency is set to 'Monthly'.
calendars: list of str, optional
Calendars to use the date for working day or weekend.
Optional if currencies is provided.
currencies: list of str, optional
Currencies to use the date for working day or weekend.
Optional if calendars is provided.
day_of_week : DayOfWeek or str, optional
The day of week to which dates are adjusted.
The first date in the list is defined as
corresponding day of week following the start date.
The last date in the list is defined as
corresponding day of week preceding the end date.
count : int, optional
A number is used to define a list of dates from the
start date (or today if the start day is not set) to the end date.
Mandatory if end_date is not specified.
extended_params : dict, optional
If necessary other parameters.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import date_schedule
>>> definition = date_schedule.Definition(
... start_date="2020-01-01",
... end_date=datetime.timedelta(0),
... frequency="Weekly",
... calendars=["EMU", "GER"],
... day_of_week=date_schedule.DayOfWeek.MONDAY,
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.DateScheduleDefinition"
def __init__(
self,
frequency: Union[DateScheduleFrequency, str, None] = None,
start_date: "OptDateTime" = None,
end_date: "OptDateTime" = None,
calendar_day_of_month: "OptInt" = None,
calendars: "OptStrStrs" = None,
currencies: "OptStrStrs" = None,
day_of_week: Optional[Union[DayOfWeek, str]] = None,
count: "OptInt" = None,
extended_params: "ExtendedParams" = None,
):
calendars = try_copy_to_list(calendars)
currencies = try_copy_to_list(currencies)
self.request_item = DateScheduleRequestItem(
start_date=start_date,
end_date=end_date,
count=count,
frequency=frequency,
calendars=calendars,
currencies=currencies,
calendar_day_of_month=calendar_day_of_month,
day_of_week=day_of_week,
)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_DATE_SCHEDULE,
universe=self.request_item,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/date_schedule/_date_schedule.py | 0.922198 | 0.326446 | _date_schedule.py | pypi |
from typing import List, Optional, Union, TYPE_CHECKING
from numpy import iterable
from ._is_working_day_data_provider import IsWorkingDay, IsWorkingDays
from .._base_request_items import DateBase
from ..._enums import HolidayOutputs
from ...._content_provider_layer import ContentUsageLoggerMixin
from ....._content_type import ContentType
from ....._tools import create_repr, try_copy_to_list
from .....delivery._data._data_provider import DataProviderLayer, BaseResponse
if TYPE_CHECKING:
from ....._types import ExtendedParams, OptStr, OptDateTime, OptStrStrs
class IsWorkingDayRequestItem(DateBase):
def __init__(self, tag, date, calendars, currencies, holiday_outputs):
super().__init__(date)
self.tag = tag
self.currencies = currencies
self.calendars = calendars
self.holiday_outputs = holiday_outputs
@property
def tag(self):
"""
:return: str
"""
return self._get_parameter("tag")
@tag.setter
def tag(self, value):
self._set_parameter("tag", value)
@property
def currencies(self):
"""
:return: list
"""
return self._get_parameter("currencies")
@currencies.setter
def currencies(self, value):
self._set_parameter("currencies", value)
@property
def calendars(self):
"""
:return: list
"""
return self._get_parameter("calendars")
@calendars.setter
def calendars(self, value):
self._set_parameter("calendars", value)
@property
def holiday_outputs(self):
"""
:return: list
"""
return self._get_list_of_enums(HolidayOutputs, "holidayOutputs")
@holiday_outputs.setter
def holiday_outputs(self, value):
self._set_list_of_enums(HolidayOutputs, "holidayOutputs", value)
class Definition(
ContentUsageLoggerMixin[BaseResponse[IsWorkingDay]],
DataProviderLayer[BaseResponse[IsWorkingDay]],
):
"""
Is working day definition object
Parameters
----------
date: str or datetime or timedelta
Date to test.
calendars: list of str, optional
Calendars to use the date for working day or weekend.
Optional if currencies is provided.
currencies: list of str, optional
Currencies to use the date for working day or weekend.
Optional if calendars is provided.
holiday_outputs : HolidayOutputs or list of str, optional
In case if test date is holiday you may request additional information about the holiday.
Possible options are: Date, Names, Calendars, Countries
tag: str, optional
Reference tag to map particular response in payload.
extended_params : dict, optional
If necessary other parameters.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import is_working_day
>>>
>>> definition = is_working_day.Definition(
... tag="my request",
... date=datetime.timedelta(0),
... currencies=["EUR"],
... holiday_outputs=["Date", "Names", "Calendars", "Countries"]
... )
>>> response = definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.IsWorkingDayDefinition"
def __init__(
self,
date: "OptDateTime" = None,
currencies: "OptStrStrs" = None,
calendars: "OptStrStrs" = None,
holiday_outputs: Optional[Union[List[HolidayOutputs], List[str]]] = None,
tag: "OptStr" = None,
extended_params: "ExtendedParams" = None,
):
currencies = try_copy_to_list(currencies)
calendars = try_copy_to_list(calendars)
holiday_outputs = try_copy_to_list(holiday_outputs)
self.extended_params = extended_params
self.request_item = IsWorkingDayRequestItem(
tag=tag,
date=date,
calendars=calendars,
currencies=currencies,
holiday_outputs=holiday_outputs,
)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_IS_WORKING_DAY,
universe=[self.request_item],
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self)
DefnDefns = Union[List[Definition], Definition]
class Definitions(
ContentUsageLoggerMixin[BaseResponse[IsWorkingDays]],
DataProviderLayer[BaseResponse[IsWorkingDays]],
):
"""
Is working day definitions object
Parameters
----------
universe: Definition or list of Definition objects
List of initialized Definition objects to retrieve data.
Methods
-------
get_data(session=None, on_response=None, **kwargs)
Returns a response to the data platform
get_data_async(session=None, on_response=None, **kwargs)
Returns a response asynchronously to the data platform
Examples
--------
>>> import datetime
>>> from refinitiv.data.content.ipa.dates_and_calendars import is_working_day
>>>
>>> first_definition = is_working_day.Definition(
... tag="my request",
... date=datetime.timedelta(0),
... currencies=["EUR"],
... holiday_outputs=["Date", "Names", "Calendars", "Countries"]
... )
...
>>>
>>> second_definition = is_working_day.Definition(
... tag="my second request",
... date="2020-01-01",
... currencies=["EUR"],
... holiday_outputs=["Date", "Names", "Calendars", "Countries"]
... )
>>> response = is_working_day.Definitions([first_definition, second_definition]).get_data()
Using get_data_async
>>> import asyncio
>>> task = is_working_day.Definitions([first_definition, second_definition]).get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "IPA.DatesAndCalendars.IsWorkingDayDefinitions"
def __init__(self, universe: "DefnDefns"):
universe = try_copy_to_list(universe)
if not iterable(universe):
universe = [universe]
request_items = []
extended_params = []
for item in universe:
request_items.append(item.request_item)
extended_params.append(item.extended_params)
super().__init__(
data_type=ContentType.DATES_AND_CALENDARS_IS_WORKING_DAY,
universe=request_items,
extended_params=extended_params,
)
def __repr__(self):
return create_repr(self) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/is_working_day/_is_working_day.py | 0.894423 | 0.325976 | _is_working_day.py | pypi |
from dataclasses import dataclass
from typing import Any, List, Optional
from .._content_data_validator import ContentDataValidator
from .._request_factory import DatesAndCalendarsResponseFactory
from ..holidays._holidays_data_provider import Holiday
from ...._content_data import Data
from ...._content_data_provider import ContentDataProvider
from ...._df_builder import build_dates_calendars_df
from .....content.ipa._content_provider import DatesAndCalendarsRequestFactory
from .....delivery._data._data_provider import ValidatorContainer
@dataclass
class WorkingDay:
is_weekend: bool
is_working_day: bool
tag: str = ""
holidays: Optional[list] = None
def working_day_from_dict(datum: dict):
holidays = datum.get("holidays", [])
tag = datum.get("tag")
holidays = [Holiday(holiday=holiday, tag=tag) for holiday in holidays]
return WorkingDay(
is_weekend=datum["isWeekEnd"],
is_working_day=datum.get("isWorkingDay"),
tag=tag,
holidays=holidays,
)
@dataclass
class IsWorkingDay(Data):
_day: WorkingDay = None
@property
def day(self):
return self._day
@dataclass
class IsWorkingDays(Data):
_is_working_days_: List[WorkingDay] = None
@property
def _is_working_days(self):
if self._is_working_days_ is None:
self._is_working_days_ = [
working_day_from_dict(raw_item) for raw_item in self.raw if not raw_item.get("error")
]
return self._is_working_days_
@property
def days(self):
return self._is_working_days
def __getitem__(self, item: int):
return self._is_working_days[item]
class IsWorkingDayResponseFactory(DatesAndCalendarsResponseFactory):
def create_data_success(self, raw: Any, **kwargs):
if len(raw) > 1:
data = IsWorkingDays(raw=raw, _dfbuilder=build_dates_calendars_df, _kwargs=kwargs)
else:
data = IsWorkingDay(
raw=raw,
_day=working_day_from_dict(raw[0]),
_dfbuilder=build_dates_calendars_df,
_kwargs=kwargs,
)
return data
is_working_day_data_provider = ContentDataProvider(
request=DatesAndCalendarsRequestFactory(),
response=IsWorkingDayResponseFactory(),
validator=ValidatorContainer(content_validator=ContentDataValidator()),
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/dates_and_calendars/is_working_day/_is_working_day_data_provider.py | 0.863593 | 0.28189 | _is_working_day_data_provider.py | pypi |
from typing import Optional, Iterable, TYPE_CHECKING
from ._cross_currency_curves import CrossCurrencyCurveDefinitionPricing
from .._object_definition import ObjectDefinition
from ...._tools import create_repr, try_copy_to_list
from ._enums import RiskType, AssetClass, ConstituentOverrideMode
from ._zc_curve_definition import ZcCurveDefinition
if TYPE_CHECKING:
from ...._types import OptStr, OptStrings, OptBool
class ZcCurveDefinitions(ObjectDefinition):
"""
Parameters
----------
index_name : str, optional
index_tenors : string, optional
Defines expected rate surface tenor/slices Defaults to the tenors available,
based on provided market data
main_constituent_asset_class : AssetClass, optional
pivot_curve_definition : ZcCurveDefinition, optional
reference_curve_definition : ZcCurveDefinition, optional
risk_type : RiskType, optional
currency : str, optional
The currency code of the interest rate curve
discounting_tenor : str, optional
Mono currency discounting tenor
id : str, optional
Id of the curve definition
name : str, optional
The name of the interest rate curve
source : str, optional
constituent_override_mode : ConstituentOverrideMode, optional
The possible values are:
* replacedefinition: replace the default constituents by the user
constituents from the input request,
* mergewithdefinition: merge the default constituents and the user
constituents from the input request, the default value is 'replacedefinition'.
If the ignore_existing_definition is true, the constituent_override_mode
is set to 'replacedefinition'.
cross_currency_definitions : CrossCurrencyCurveDefinitionPricing, optional
The list of the cross currency definition attributes used for pricing the
adjusted interest rate curve. if not set in the request the definition matching
the currencies, index names and the isnondeliverable flag are retrieved.
curve_tenors : string, optional
The list of user-defined tenors or dates for which curvepoints to be computed.
The values are expressed in:
* time period code for tenors (e.g., '1m', '6m', '4y'),
* iso 8601 format 'yyyy-mm-dd' for dates (e.g., '2021-01-01').
ignore_existing_definition : bool, optional
An indicator whether default definitions are used to get curve parameters and
constituents.
The possible values are:
* True: default definitions are not used (definitions and constituents must
be set in the request),
* False: default definitions are used.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable.
The possible values are:
* True: the instrument is non-deliverable,
* False: the instrument is not non-deliverable.
This parameter may be used to specify the use of crosscurrencydefinitions made
of non-deliverable or deliverable instruments. When this parameters isn't
specified, the default crosscurrencydefinitions is used. this definition with
'isfallbackforfxcurvedefinition'=True is returned by the
crosscurrencydefinitions curve search.
"""
def __init__(
self,
index_name: "OptStr" = None,
index_tenors: "OptStrings" = None,
main_constituent_asset_class: Optional[AssetClass] = None,
pivot_curve_definition: Optional[ZcCurveDefinition] = None,
reference_curve_definition: Optional[ZcCurveDefinition] = None,
risk_type: Optional[RiskType] = None,
currency: "OptStr" = None,
discounting_tenor: "OptStr" = None,
id: "OptStr" = None,
name: "OptStr" = None,
source: "OptStr" = None,
constituent_override_mode: Optional[ConstituentOverrideMode] = None,
cross_currency_definitions: Optional[Iterable[CrossCurrencyCurveDefinitionPricing]] = None,
curve_tenors: "OptStrings" = None,
ignore_existing_definition: "OptBool" = None,
is_non_deliverable: "OptBool" = None,
market_data_location: "OptStr" = None,
) -> None:
super().__init__()
self.index_name = index_name
self.index_tenors = try_copy_to_list(index_tenors)
self.main_constituent_asset_class = main_constituent_asset_class
self.pivot_curve_definition = pivot_curve_definition
self.reference_curve_definition = reference_curve_definition
self.risk_type = risk_type
self.currency = currency
self.discounting_tenor = discounting_tenor
self.id = id
self.name = name
self.source = source
self.constituent_override_mode = constituent_override_mode
self.cross_currency_definitions = try_copy_to_list(cross_currency_definitions)
self.curve_tenors = try_copy_to_list(curve_tenors)
self.ignore_existing_definition = ignore_existing_definition
self.is_non_deliverable = is_non_deliverable
self.market_data_location = market_data_location
def __repr__(self):
return create_repr(
self,
middle_path="curves.zc_curves",
class_name=self.__class__.__name__,
)
@property
def index_tenors(self):
"""
Defines expected rate surface tenor/slices Defaults to the tenors available,
based on provided market data
:return: list string
"""
return self._get_list_parameter(str, "indexTenors")
@index_tenors.setter
def index_tenors(self, value):
self._set_list_parameter(str, "indexTenors", value)
@property
def main_constituent_asset_class(self):
"""
:return: enum AssetClass
"""
return self._get_enum_parameter(AssetClass, "mainConstituentAssetClass")
@main_constituent_asset_class.setter
def main_constituent_asset_class(self, value):
self._set_enum_parameter(AssetClass, "mainConstituentAssetClass", value)
@property
def pivot_curve_definition(self):
"""
:return: object ZcCurveDefinition
"""
return self._get_object_parameter(ZcCurveDefinition, "pivotCurveDefinition")
@pivot_curve_definition.setter
def pivot_curve_definition(self, value):
self._set_object_parameter(ZcCurveDefinition, "pivotCurveDefinition", value)
@property
def reference_curve_definition(self):
"""
:return: object ZcCurveDefinition
"""
return self._get_object_parameter(ZcCurveDefinition, "referenceCurveDefinition")
@reference_curve_definition.setter
def reference_curve_definition(self, value):
self._set_object_parameter(ZcCurveDefinition, "referenceCurveDefinition", value)
@property
def risk_type(self):
"""
:return: enum RiskType
"""
return self._get_enum_parameter(RiskType, "riskType")
@risk_type.setter
def risk_type(self, value):
self._set_enum_parameter(RiskType, "riskType", value)
@property
def currency(self):
"""
The currency code of the interest rate curve
:return: str
"""
return self._get_parameter("currency")
@currency.setter
def currency(self, value):
self._set_parameter("currency", value)
@property
def discounting_tenor(self):
"""
Mono currency discounting tenor
:return: str
"""
return self._get_parameter("discountingTenor")
@discounting_tenor.setter
def discounting_tenor(self, value):
self._set_parameter("discountingTenor", value)
@property
def id(self):
"""
Id of the curve definition
:return: str
"""
return self._get_parameter("id")
@id.setter
def id(self, value):
self._set_parameter("id", value)
@property
def index_name(self):
"""
:return: str
"""
return self._get_parameter("indexName")
@index_name.setter
def index_name(self, value):
self._set_parameter("indexName", value)
@property
def name(self):
"""
The name of the interest rate curve
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value)
@property
def source(self):
"""
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value)
@property
def constituent_override_mode(self):
"""
A method to use the default constituents. the possible values are:
* replacedefinition: replace the default constituents by the user
constituents from the input request,
* mergewithdefinition: merge the default constituents and the user
constituents from the input request, the default value is 'replacedefinition'.
If the ignore_existing_definition is true, the constituent_override_mode
is set to 'replacedefinition'.
:return: enum ConstituentOverrideMode
"""
return self._get_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode")
@constituent_override_mode.setter
def constituent_override_mode(self, value):
self._set_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode", value)
@property
def cross_currency_definitions(self):
"""
The list of the cross currency definition attributes used for pricing the
adjusted interest rate curve. if not set in the request the definition matching
the currencies, index names and the isnondeliverable flag are retrieved.
:return: list CrossCurrencyCurveDefinitionPricing
"""
return self._get_list_parameter(CrossCurrencyCurveDefinitionPricing, "crossCurrencyDefinitions")
@cross_currency_definitions.setter
def cross_currency_definitions(self, value):
self._set_list_parameter(CrossCurrencyCurveDefinitionPricing, "crossCurrencyDefinitions", value)
@property
def curve_tenors(self):
"""
The list of user-defined tenors or dates for which curvepoints to be computed.
The values are expressed in:
* time period code for tenors (e.g., '1m', '6m', '4y'),
* iso 8601 format 'yyyy-mm-dd' for dates (e.g., '2021-01-01').
:return: list string
"""
return self._get_list_parameter(str, "curveTenors")
@curve_tenors.setter
def curve_tenors(self, value):
self._set_list_parameter(str, "curveTenors", value)
@property
def ignore_existing_definition(self):
"""
An indicator whether default definitions are used to get curve parameters and
constituents.
The possible values are:
* True: default definitions are not used (definitions and constituents must
be set in the request),
* False: default definitions are used.
:return: bool
"""
return self._get_parameter("ignoreExistingDefinition")
@ignore_existing_definition.setter
def ignore_existing_definition(self, value):
self._set_parameter("ignoreExistingDefinition", value)
@property
def is_non_deliverable(self):
"""
An indicator whether the instrument is non-deliverable.
The possible values are:
* True: the instrument is non-deliverable,
* False: the instrument is not non-deliverable.
This parameter may be used to specify the use of crosscurrencydefinitions made
of non-deliverable or deliverable instruments. When this parameters isn't
specified, the default crosscurrencydefinitions is used. this definition with
'isfallbackforfxcurvedefinition'=True is returned by the
crosscurrencydefinitions curve search.
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def market_data_location(self):
"""
The identifier of the market place from which constituents come from. currently
the following values are supported: 'onshore' and 'emea'. the list of values can
be extended by a user when creating a curve.
:return: str
"""
return self._get_parameter("marketDataLocation")
@market_data_location.setter
def market_data_location(self, value):
self._set_parameter("marketDataLocation", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_zc_curve_definitions.py | 0.937569 | 0.459864 | _zc_curve_definitions.py | pypi |
from itertools import product
import pandas as pd
from ...._tools._dataframe import convert_df_columns_to_datetime, convert_dtypes, convert_df_columns_to_datetime_by_idx
def bond_curve_build_df(raw, **kwargs):
"""
Parameters
----------
raw : dict
Returns
-------
DataFrame
Examples
-------
>>> raw
... {
... "data": [
... {
... "error": {
... "id": "b6f9797d-72c8-4baa-84eb-6a079fc40ec5/b6f9797d-72c8-4baa-84eb-6a079fc40ec5",
... "code": "QPS-Curves.6",
... "message": "Invalid input: curveDefinition is missing",
... }
... },
... {
... "curveTag": "test_curve",
... "curveParameters": {
... "interestCalculationMethod": "Dcb_Actual_Actual",
... "priceSide": "Mid",
... "calendarAdjustment": "Calendar",
... "calendars": ["EMU_FI"],
... "compoundingType": "Compounded",
... "useConvexityAdjustment": True,
... "useSteps": False,
... "valuationDate": "2022-02-09",
... },
... "curveDefinition": {
... "availableTenors": ["OIS", "1M", "3M", "6M", "1Y"],
... "availableDiscountingTenors": ["OIS", "1M", "3M", "6M", "1Y"],
... "currency": "EUR",
... "mainConstituentAssetClass": "Swap",
... "riskType": "InterestRate",
... "indexName": "EURIBOR",
... "source": "Refinitiv",
... "name": "EUR EURIBOR Swap ZC Curve",
... "id": "9d619112-9ab3-45c9-b83c-eb04cbec382e",
... "discountingTenor": "OIS",
... "ignoreExistingDefinition": False,
... "owner": "Refinitiv",
... },
... "curvePoints": [
... {
... "endDate": "2021-02-01",
... "startDate": "2021-02-01",
... "discountFactor": 1.0,
... "ratePercent": 7.040811073443143,
... "tenor": "0D",
... },
... {
... "endDate": "2021-02-04",
... "startDate": "2021-02-01",
... "discountFactor": 0.999442450671571,
... "ratePercent": 7.040811073443143,
... "tenor": "1D",
... },
... ],
... },
... ]
... }
"""
datas = raw.get("data", [])
datas = datas or []
dfs = []
for data in datas:
error = data.get("error")
if error:
continue
curve_points = data.get("curvePoints")
for curve_point in curve_points:
d = {}
for key, value in curve_point.items():
values = d.setdefault(key, [])
values.append(value)
df = pd.DataFrame(d)
df = df.convert_dtypes()
dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
df = convert_df_columns_to_datetime(df, "Date", utc=True, delete_tz=True)
df = convert_dtypes(df)
return df
def cross_currency_curves_curve_build_df(raw, **kwargs):
"""
Parameters
----------
raw : dict
Returns
-------
DataFrame
Examples
-------
>>> raw
... {
... 'data':
... [
... {
... "error": {
... "id": "b6f9797d-72c8-4baa-84eb-6a079fc40ec5/b6f9797d-72c8-4baa-84eb-6a079fc40ec5",
... "code": "QPS-Curves.6",
... "message": "Invalid input: curveDefinition is missing",
... }
... },
... {
... 'curveDefinition': {
... 'baseCurrency': 'EUR', 'baseIndexName': 'ESTR',
... 'quotedCurrency': 'USD', 'quotedIndexName': 'SOFR',
... 'crossCurrencyDefinitions': [
... {
... 'baseCurrency': 'EUR', 'baseIndexName': 'ESTR',
... 'name': 'EUR ESTR/USD SOFR FxCross',
... 'quotedCurrency': 'USD', 'quotedIndexName': 'SOFR',
... 'source': 'Refinitiv', 'isNonDeliverable': False,
... 'mainConstituentAssetClass': 'Swap',
... 'riskType': 'CrossCurrency',
... 'id': 'c9f2e9fb-b04b-4140-8377-8b7e47391486',
... 'ignoreExistingDefinition': False
... }
... ]
... },
... 'curveParameters': {
... 'valuationDate': '2021-10-06',
... 'interpolationMode': 'Linear',
... 'extrapolationMode': 'Constant', 'turnAdjustments': {},
... 'ignorePivotCurrencyHolidays': False,
... 'useDelayedDataIfDenied': False,
... 'ignoreInvalidInstrument': True,
... 'marketDataLookBack': {'value': 10, 'unit': 'CalendarDay'}
... },
... 'curve': {
... 'fxCrossScalingFactor': 1.0, 'fxSwapPointScalingFactor': 10000.0,
... 'curvePoints': [
... {
... 'tenor': 'SPOT', 'startDate': '2021-10-08',
... 'endDate': '2021-10-08',
... 'swapPoint': {'bid': 0.0, 'ask': 0.0, 'mid': 0.0},
... 'outright': {'bid': 1.1556, 'ask': 1.156, 'mid': 1.1558}
... },
... {
... 'tenor': 'SN', 'startDate': '2021-10-08',
... 'endDate': '2021-10-12',
... 'instruments': [{'instrumentCode': 'EURSN='}],
... 'swapPoint': {
... 'bid': 0.8399999999997299,
... 'ask': 0.8800000000008801,
... 'mid': 0.860000000000305
... },
... 'outright': {'bid': 1.155684, 'ask': 1.156088,
... 'mid': 1.155886}
... }
... ]
... }
... }
... ]
... }
"""
datas = raw.get("data", [])
datas = datas or []
get_curve = (data["curve"] for data in datas if "curve" in data)
columns_have_level_1 = ("swapPoint", "outright")
level_1 = ("bid", "ask", "mid")
curve = next(get_curve, {})
curve_points = curve.get("curvePoints", [])
curve_point = max(curve_points, key=lambda x: len(x))
columns = [key for key in curve_point]
data_df = _create_data_for_df(curve_points, columns, columns_have_level_1, level_1)
allcolumns = []
for name in columns:
if name in columns_have_level_1:
allcolumns.extend(list(product([name], level_1)))
else:
allcolumns.append((name, ""))
columns_date_idxs = [index for index, value in enumerate(allcolumns) if "date" in value[0].lower()]
columns = pd.MultiIndex.from_tuples(allcolumns)
df = pd.DataFrame(data_df, columns=columns)
df = convert_df_columns_to_datetime_by_idx(df, columns_date_idxs, utc=True, delete_tz=True)
df = convert_dtypes(df)
return df
def _create_data_for_df(curve_points, columns, columns_have_level_1, columns_level_1):
data_df = []
for curve_point in curve_points:
row_data = []
for name in columns:
value = curve_point.get(name, pd.NA)
if name == "instruments" and not pd.isna(value):
value = [v["instrumentCode"] for v in value if "instrumentCode" in v]
value = value.pop() if len(value) == 1 else value
if name in columns_have_level_1:
value = [value.get(i, pd.NA) for i in columns_level_1]
row_data.extend(value)
else:
row_data.append(value)
data_df.append(row_data)
return data_df
def zc_curves_build_df(raw, **kwargs):
"""
Parameters
----------
raw : dict
Returns
-------
DataFrame
>>> raw
... {
... "data": [
... {
... "curveTag": "TAG",
... "error": {
... "id": "9fef13f4-6d11-4d71-a388-824ddcc8a95a/9fef13f4-6d11-4d71-a388-824ddcc8a95a",
... "code": "QPS-Curves.7",
... "message": "The service failed to find the curve definition",
... },
... },
... {
... "curveParameters": {
... "extrapolationMode": "None",
... "interpolationMode": "CubicDiscount",
... "interestCalculationMethod": "Dcb_Actual_Actual",
... "priceSide": "Mid",
... "calendarAdjustment": "Calendar",
... "calendars": ["EMU_FI"],
... "compoundingType": "Compounded",
... "useMultiDimensionalSolver": True,
... "useConvexityAdjustment": True,
... "useSteps": False,
... "convexityAdjustment": {
... "meanReversionPercent": 3.9012,
... "volatilityPercent": 0.863,
... },
... "valuationDate": "2022-02-09",
... },
... "curveDefinition": {
... "availableTenors": ["OIS", "1M", "3M", "6M", "1Y"],
... "availableDiscountingTenors": ["OIS", "1M", "3M", "6M", "1Y"],
... "currency": "EUR",
... "mainConstituentAssetClass": "Swap",
... "riskType": "InterestRate",
... "indexName": "EURIBOR",
... "source": "Refinitiv",
... "name": "EUR EURIBOR Swap ZC Curve",
... "id": "9d619112-9ab3-45c9-b83c-eb04cbec382e",
... "discountingTenor": "OIS",
... "ignoreExistingDefinition": False,
... "owner": "Refinitiv",
... "indexTenors": ["OIS", "1M", "3M", "6M", "1Y"],
... },
... "curves": {
... "OIS": {
... "curvePoints": [
... {
... "endDate": "2022-02-09",
... "startDate": "2022-02-09",
... "discountFactor": 1.0,
... "ratePercent": -0.49456799906775206,
... "tenor": "0D",
... },
... {
... "endDate": "2022-02-10",
... "startDate": "2022-02-09",
... "discountFactor": 1.0000135835178428,
... "ratePercent": -0.49456799906775206,
... "tenor": "ON",
... "instruments": [{"instrumentCode": "EUROSTR="}],
... },
... ],
... "isDiscountCurve": True,
... },
... "1M": {
... "curvePoints": [
... {
... "endDate": "2022-02-09",
... "startDate": "2022-02-09",
... "discountFactor": 1.0,
... "ratePercent": -0.5560912053716005,
... "tenor": "0D",
... },
... {
... "endDate": "2022-02-10",
... "startDate": "2022-02-09",
... "discountFactor": 1.0000152780111917,
... "ratePercent": -0.5560912053716005,
... "tenor": "ON",
... "instruments": [{"instrumentCode": "EUROND="}],
... },
... ],
... "isDiscountCurve": False,
... },
... "3M": {
... "curvePoints": [
... {
... "endDate": "2022-02-09",
... "startDate": "2022-02-09",
... "discountFactor": 1.0,
... "ratePercent": -0.5560912053716005,
... "tenor": "0D",
... },
... {
... "endDate": "2022-02-10",
... "startDate": "2022-02-09",
... "discountFactor": 1.0000152780111917,
... "ratePercent": -0.5560912053716005,
... "tenor": "ON",
... "instruments": [{"instrumentCode": "EUROND="}],
... },
... ],
... "isDiscountCurve": False,
... },
... "6M": {
... "curvePoints": [
... {
... "endDate": "2022-02-09",
... "startDate": "2022-02-09",
... "discountFactor": 1.0,
... "ratePercent": -0.5560912053716005,
... "tenor": "0D",
... },
... {
... "endDate": "2022-02-10",
... "startDate": "2022-02-09",
... "discountFactor": 1.0000152780111917,
... "ratePercent": -0.5560912053716005,
... "tenor": "ON",
... "instruments": [{"instrumentCode": "EUROND="}],
... },
... ],
... "isDiscountCurve": False,
... },
... "1Y": {
... "curvePoints": [
... {
... "endDate": "2022-02-09",
... "startDate": "2022-02-09",
... "discountFactor": 1.0,
... "ratePercent": -0.5560912053716005,
... "tenor": "0D",
... },
... {
... "endDate": "2022-02-10",
... "startDate": "2022-02-09",
... "discountFactor": 1.0000152780111917,
... "ratePercent": -0.5560912053716005,
... "tenor": "ON",
... "instruments": [{"instrumentCode": "EUROND="}],
... },
... ],
... "isDiscountCurve": False,
... },
... },
... },
... ]
... }
"""
datas = raw.get("data", [])
datas = datas or []
dfs = []
for data in datas:
error = data.get("error")
if error:
continue
curves = data.get("curves")
for value in curves.values():
curve_points = value.get("curvePoints")
d = {}
for curve_point in curve_points:
for key, value in curve_point.items():
values = d.setdefault(key, [])
values.append(value)
d.pop("instruments", None)
df = pd.DataFrame(d)
dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
df = convert_df_columns_to_datetime(df, "Date", utc=True, delete_tz=True)
df = convert_dtypes(df)
return df
def forward_curve_build_df(raw, **kwargs):
"""
Parameters
----------
raw : dict
Returns
-------
DataFrame
Examples
-------
>>> raw
... {
... "data": [
... {
... "error": {
... "id": "b6f9797d-72c8-4baa-84eb-6a079fc40ec5/b6f9797d-72c8-4baa-84eb-6a079fc40ec5",
... "code": "QPS-Curves.6",
... "message": "Invalid input: curveDefinition is missing",
... }
... },
... {
... "curveTag": "test_curve",
... "curveParameters": {
... "interestCalculationMethod": "Dcb_Actual_Actual",
... "priceSide": "Mid",
... "calendarAdjustment": "Calendar",
... "calendars": ["EMU_FI"],
... "compoundingType": "Compounded",
... "useConvexityAdjustment": True,
... "useSteps": False,
... "valuationDate": "2022-02-09",
... },
... "curveDefinition": {
... "availableTenors": ["OIS", "1M", "3M", "6M", "1Y"],
... "availableDiscountingTenors": ["OIS", "1M", "3M", "6M", "1Y"],
... "currency": "EUR",
... "mainConstituentAssetClass": "Swap",
... "riskType": "InterestRate",
... "indexName": "EURIBOR",
... "source": "Refinitiv",
... "name": "EUR EURIBOR Swap ZC Curve",
... "id": "9d619112-9ab3-45c9-b83c-eb04cbec382e",
... "discountingTenor": "OIS",
... "ignoreExistingDefinition": False,
... "owner": "Refinitiv",
... },
... "forwardCurves": [
... {
... "curvePoints": [
... {
... "endDate": "2021-02-01",
... "startDate": "2021-02-01",
... "discountFactor": 1.0,
... "ratePercent": 7.040811073443143,
... "tenor": "0D",
... },
... {
... "endDate": "2021-02-04",
... "startDate": "2021-02-01",
... "discountFactor": 0.999442450671571,
... "ratePercent": 7.040811073443143,
... "tenor": "1D",
... },
... ],
... "forwardCurveTag": "ForwardTag",
... "forwardStart": "2021-02-01",
... "indexTenor": "3M",
... }
... ],
... },
... ]
... }
"""
datas = raw.get("data", [])
datas = datas or []
dfs = []
for data in datas:
if data.get("error"):
continue
forward_curves = data.get("forwardCurves")
for forward_curve in forward_curves:
if forward_curve.get("error"):
continue
curve_points = forward_curve.get("curvePoints")
d = {}
for curve_point in curve_points:
for key, value in curve_point.items():
values = d.setdefault(key, [])
values.append(value)
df = pd.DataFrame(d)
df = df.convert_dtypes()
dfs.append(df)
if not dfs:
df = pd.DataFrame()
else:
df = pd.concat(dfs, ignore_index=True)
df = convert_df_columns_to_datetime(df, "Date", utc=True, delete_tz=True)
df = convert_dtypes(df)
return df
def zc_curve_definitions_build_df(raw, **kwargs):
data = raw.get("data", [])
data = data or []
curve_definitions = [d for d in data if d for d in d.get("curveDefinitions")]
df = pd.DataFrame(curve_definitions)
if not df.empty:
df = convert_df_columns_to_datetime(df, "Date", utc=True, delete_tz=True)
df = convert_dtypes(df)
return df
def cross_currency_curves_definitions_search_build_df(raw, **kwargs):
return zc_curve_definitions_build_df(raw) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_curves_builder_df.py | 0.807537 | 0.428652 | _curves_builder_df.py | pypi |
from dataclasses import dataclass
from typing import Any, Callable, List, TYPE_CHECKING
import numpy as np
from numpy import iterable
from ._models._curve import Curve, ForwardCurve, ZcCurve
from .._content_provider import (
CrossCurrencyCurvesDefinitionsRequestFactory,
CurvesAndSurfacesRequestFactory,
get_type_by_axis,
)
from .._ipa_content_validator import IPAContentValidator
from ..curves._cross_currency_curves.definitions._data_classes import CurveDefinitionData
from ..curves._cross_currency_curves.triangulate_definitions._data_provider import TriangulateDefinitionsData
from ..._content_data import Data
from ..._content_data_provider import ContentDataProvider
from ..._content_response_factory import ContentResponseFactory
from ...._content_type import ContentType
from ...._tools import cached_property
from ....delivery._data._data_provider import DataProvider, ValidatorContainer
from ....delivery._data._response_factory import ResponseFactory
if TYPE_CHECKING:
from ....delivery._data._data_provider import ParsedData
# ---------------------------------------------------------------------------
# ContentValidator
# ---------------------------------------------------------------------------
class CurvesContentValidator(IPAContentValidator):
@cached_property
def validators(self) -> List[Callable[["ParsedData"], bool]]:
return [self.content_data_is_not_none, self.any_element_have_no_error]
class CurveDefinitionContentValidator(CurvesContentValidator):
_NAME_DATA = "curveDefinition"
class ForwardCurvesContentValidator(CurvesContentValidator):
@classmethod
def any_forward_curves_have_no_error(cls, data: "ParsedData") -> bool:
elements = data.content_data.get(cls._NAME_DATA)
if isinstance(elements, list):
counter = len(elements) or 1
for element in elements:
for forward_curve in element.get("forwardCurves", []):
error = forward_curve.get("error")
if error:
counter -= 1
data.error_codes.append(error.get("code"))
data.error_messages.append(error.get("message"))
if counter == 0:
return False
return True
@cached_property
def validators(self) -> List[Callable[["ParsedData"], bool]]:
return [self.content_data_is_not_none, self.any_element_have_no_error, self.any_forward_curves_have_no_error]
# ---------------------------------------------------------------------------
# Content data
# ---------------------------------------------------------------------------
@dataclass
class OneCurveData(Data):
_create_curves: Callable = None
_curve: Curve = None
@property
def curve(self) -> Curve:
if self._curve is None:
curve = self._create_curves(self.raw)
self._curve = curve[0]
return self._curve
@dataclass
class CurvesData(Data):
_create_curves: Callable = None
_curves: List[Curve] = None
@property
def curves(self) -> List[Curve]:
if self._curves is None:
self._curves = self._create_curves(self.raw)
return self._curves
def make_create_forward_curves(x_axis: str, y_axis: str) -> Callable:
"""
Parameters
----------
x_axis: str
Name of key in curve point data for build X axis
y_axis: str
Name of key in curve point data for build Y axis
Returns
-------
Callable
"""
def create_forward_curves(raw: dict) -> list:
"""
Curve point in "curvePoints":
{
"discountFactor": 1.0,
"endDate": "2021-02-01",
"ratePercent": -2.330761285491212,
"startDate": "2021-02-01",
"tenor": "0D"
}
Parameters
----------
raw
Returns
-------
list of ForwardCurve
"""
curves = []
for data in raw.get("data", []):
for forward_curve in data.get("forwardCurves", []):
x, y = [], []
for point in forward_curve.get("curvePoints"):
end_date = point.get(x_axis)
x.append(end_date)
discount_factor = point.get(y_axis)
y.append(discount_factor)
x = np.array(x, dtype=get_type_by_axis(x_axis))
y = np.array(y, dtype=get_type_by_axis(y_axis))
curve = ForwardCurve(x, y, **forward_curve)
curves.append(curve)
return curves
return create_forward_curves
def make_create_bond_curves(x_axis: str, y_axis: str) -> Callable:
"""
Parameters
----------
x_axis: str
Name of key in curve point data for build X axis
y_axis: str
Name of key in curve point data for build Y axis
Returns
-------
Callable
"""
def create_bond_curves(raw: dict) -> list:
"""
Curve point in "curvePoints":
{
"discountFactor": 1.0,
"endDate": "2021-02-01",
"ratePercent": -2.330761285491212,
"startDate": "2021-02-01",
"tenor": "0D"
}
Parameters
----------
raw
Returns
-------
list of Curve
"""
curves = []
for data in raw.get("data", []):
x, y = [], []
for point in data.get("curvePoints"):
end_date = point.get(x_axis)
x.append(end_date)
discount_factor = point.get(y_axis)
y.append(discount_factor)
x = np.array(x, dtype=get_type_by_axis(x_axis))
y = np.array(y, dtype=get_type_by_axis(y_axis))
curve = Curve(x, y)
curves.append(curve)
return curves
return create_bond_curves
def make_create_zc_curves(x_axis: str, y_axis: str) -> Callable:
"""
Parameters
----------
x_axis: str
Name of key in curve point data for build X axis
y_axis: str
Name of key in curve point data for build Y axis
Returns
-------
Callable
"""
def create_zc_curves(raw: dict) -> list:
"""
Curve point in "curvePoints":
{
"discountFactor": 1.0,
"endDate": "2021-07-27",
"ratePercent": -0.7359148312458879,
"startDate": "2021-07-27",
"tenor": "ON",
"instruments": [
{
"instrumentCode": "SARON.S"
}
]
}
Parameters
----------
raw
Returns
-------
list of ZcCurve
"""
curves = []
for data in raw.get("data", []):
for index_tenor, zc_curve in data.get("curves", {}).items():
x, y = [], []
for point in zc_curve.get("curvePoints"):
end_date = point.get(x_axis)
x.append(end_date)
discount_factor = point.get(y_axis)
y.append(discount_factor)
x = np.array(x, dtype=get_type_by_axis(x_axis))
y = np.array(y, dtype=get_type_by_axis(y_axis))
curve = ZcCurve(x, y, index_tenor, **zc_curve)
curves.append(curve)
return curves
return create_zc_curves
curves_maker_by_content_type = {
ContentType.FORWARD_CURVE: make_create_forward_curves(x_axis="endDate", y_axis="discountFactor"),
ContentType.BOND_CURVE: make_create_bond_curves(x_axis="endDate", y_axis="discountFactor"),
ContentType.ZC_CURVES: make_create_zc_curves(x_axis="endDate", y_axis="discountFactor"),
}
def get_curves_maker(content_type):
curves_maker = curves_maker_by_content_type.get(content_type)
if not curves_maker:
raise ValueError(f"Cannot find curves_maker for content_type={content_type}")
return curves_maker
# ---------------------------------------------------------------------------
# Response factory
# ---------------------------------------------------------------------------
class CurvesResponseFactory(ContentResponseFactory):
def create_data_success(self, raw: Any, **kwargs) -> Data:
return self._do_create_data(raw, **kwargs)
def create_data_fail(self, raw: Any, **kwargs) -> Data:
return self._do_create_data({}, **kwargs)
def _do_create_data(self, raw: Any, universe=None, **kwargs):
content_type = kwargs.get("__content_type__")
dfbuilder = self.get_dfbuilder(content_type, **kwargs)
if content_type is ContentType.ZC_CURVE_DEFINITIONS:
data = Data(raw, _dfbuilder=dfbuilder)
else:
curves_maker = get_curves_maker(content_type)
if iterable(universe):
data = CurvesData(
raw=raw,
_dfbuilder=dfbuilder,
_create_curves=curves_maker,
)
else:
data = OneCurveData(raw=raw, _dfbuilder=dfbuilder, _create_curves=curves_maker)
return data
# ---------------------------------------------------------------------------
# Data provider
# ---------------------------------------------------------------------------
curves_data_provider = ContentDataProvider(
request=CurvesAndSurfacesRequestFactory(),
response=CurvesResponseFactory(),
validator=ValidatorContainer(content_validator=CurvesContentValidator()),
)
forward_curves_data_provider = ContentDataProvider(
request=CurvesAndSurfacesRequestFactory(),
response=CurvesResponseFactory(),
validator=ValidatorContainer(content_validator=ForwardCurvesContentValidator()),
)
curve_data_provider = ContentDataProvider(
request=CurvesAndSurfacesRequestFactory(),
validator=ValidatorContainer(content_validator=CurvesContentValidator()),
)
cross_currency_curves_triangulate_definitions_data_provider = DataProvider(
request=CurvesAndSurfacesRequestFactory(),
response=ResponseFactory(data_class=TriangulateDefinitionsData),
validator=ValidatorContainer(content_validator=CurvesContentValidator()),
)
cross_currency_curves_definitions_data_provider = DataProvider(
request=CrossCurrencyCurvesDefinitionsRequestFactory(),
response=ResponseFactory(data_class=CurveDefinitionData),
validator=ValidatorContainer(content_validator=CurveDefinitionContentValidator()),
)
cross_currency_curves_definitions_delete_data_provider = DataProvider(
request=CrossCurrencyCurvesDefinitionsRequestFactory(),
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_curves_data_provider.py | 0.91555 | 0.257958 | _curves_data_provider.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._enums import MarketDataAccessDeniedFallback
from ._models import InterestRateCurveParameters, ValuationTime
from .._object_definition import ObjectDefinition
from ._enums import (
DayCountBasis,
InterpolationMode,
CalendarAdjustment,
PriceSide,
CompoundingType,
ExtrapolationMode,
)
from ._models import (
ConvexityAdjustment,
Step,
Turn,
)
from ...._types import Strings, OptBool, OptStr, OptDateTime
from ...._tools import create_repr, try_copy_to_list
if TYPE_CHECKING:
from ._forward_curve_types import Steps, Turns
class SwapZcCurveParameters(ObjectDefinition):
"""
Parameters
----------
interest_calculation_method : InterestCalculationMethod, optional
Day count basis of the calculated zero coupon rates.
Default value is: Dcb_Actual_Actual
calendar_adjustment : CalendarAdjustment, optional
Cash flow adjustment according to a calendar
No:
Null:
Weekend: for cash flow pricing using the calendar
WeekendCalendar: for cash flow pricing using the calendar defined
by the parameter 'calendars'.
calendars : string, optional
A list of one or more calendar codes used to define non-working days and to
adjust coupon dates and values.
compounding_type : CompoundingType, optional
convexity_adjustment : ConvexityAdjustment, optional
extrapolation_mode : ExtrapolationMode, optional
None: no extrapolation
Constant: constant extrapolation
Linear: linear extrapolation
interpolation_mode : InterpolationMode, optional
Interpolation method used in swap zero curve bootstrap.
Default value is: CubicSpline
CubicDiscount: local cubic interpolation of discount factors
CubicRate: local cubic interpolation of rates
CubicSpline: a natural cubic spline
Linear: linear interpolation
Log: log linear interpolation
ForwardMonotoneConvex
price_side : SwapPriceSide, optional
Defines which data is used for the rate surface computation.
Default value is: Mid
steps : Step, optional
Use to calculate the swap rate surface discount curve, when OIS is selected as
discount curve.
The steps can specify overnight index stepped dates or/and rates.
turns : Turn, optional
Used to include end period rates/turns when calculating swap rate surfaces
reference_tenor : str, optional
Root tenor(s) for the xIbor dependencies
use_convexity_adjustment : bool, optional
false / true
Default value is: true.
It indicates if the system needs to retrieve the convexity adjustment
use_multi_dimensional_solver : bool, optional
false / true
Default value is: true.
Specifies the use of the multi-dimensional solver for yield curve bootstrapping.
This solving method is required because the bootstrapping method sometimes
creates a ZC curve which does not accurately reprice the input instruments used
to build it.
The multi-dimensional solver is recommended when cubic interpolation methods
are used in building the curve
(in other cases, performance might be inferior to the regular bootstrapping
method).
- true: to use multi-dimensional solver for yield curve bootstrapping
- false: not to use multi-dimensional solver for yield curve bootstrapping
use_steps : bool, optional
false / true
Default value is: false.
It indicates if the system needs to retrieve the overnight index
stepped dates or/and rates
valuation_date : str or date, optional
The valuation date
Default value is the current date
market_data_access_denied_fallback : MarketDataAccessDeniedFallback, optional
If at leat one constituent access is denied:
* returnerror: dont price the surface and return an error (default value)
* ignoreconstituents: price the surface without the error market data
* usedelayeddata: use delayed market data if possible
pivot_curve_parameters : list of InterestRateCurveParameters, optional
The list of parameters used to define the pivot curve which is used for
evaluation of the adjusted zero coupon curve. for example, eur zero curve
adjusted with gbp curve, using usd as a pivot.
reference_curve_parameters : list of InterestRateCurveParameters, optional
The list of parameters used to define the reference curve which is used for
evaluation of the adjusted zero coupon curve. for example, eur zero curve is
adjusted with gbp curve.
valuation_time : ValuationTime, optional
The time identified by offsets at which the zero coupon curve is generated.
ignore_invalid_instrument : bool, optional
Ignore invalid instrument to calculate the curve.
If false and some instrument are invlide, the curve is not calculated
and an error is returned. the default value is 'True'.
use_delayed_data_if_denied : bool, optional
Use delayed ric to retrieve data when not permissioned on constituent ric. The
default value is 'False'.
valuation_date_time : str or date or datetime or timedelta, optional
The date and time at which the zero coupon curve is generated.
The value is expressed in iso 8601 format: yyyy-mm-ddt00:00:00z
(e.g., '2021-01-01t14:00:00z' or '2021-01-01t14:00:00+02:00').
Only one parameter of valuation_date and valuation_date_time must be specified.
"""
_ignore_existing_definition = None
def __init__(
self,
interest_calculation_method: Optional[DayCountBasis] = None,
calendar_adjustment: Optional[CalendarAdjustment] = None,
calendars: Strings = None,
compounding_type: Optional[CompoundingType] = None,
convexity_adjustment: Optional[ConvexityAdjustment] = None,
extrapolation_mode: Optional[ExtrapolationMode] = None,
interpolation_mode: Optional[InterpolationMode] = None,
price_side: Optional[PriceSide] = None,
steps: "Steps" = None,
turns: "Turns" = None,
ignore_existing_definition: OptBool = None,
reference_tenor: OptStr = None,
use_convexity_adjustment: OptBool = None,
use_multi_dimensional_solver: OptBool = None,
use_steps: OptBool = None,
valuation_date: "OptDateTime" = None,
market_data_access_denied_fallback: Optional[MarketDataAccessDeniedFallback] = None,
pivot_curve_parameters: Optional[InterestRateCurveParameters] = None,
reference_curve_parameters: Optional[InterestRateCurveParameters] = None,
valuation_time: Optional[ValuationTime] = None,
ignore_invalid_instrument: OptBool = None,
use_delayed_data_if_denied: OptBool = None,
valuation_date_time: "OptDateTime" = None,
) -> None:
super().__init__()
self.interest_calculation_method = interest_calculation_method
self.calendar_adjustment = calendar_adjustment
self.calendars = try_copy_to_list(calendars)
self.compounding_type = compounding_type
self.convexity_adjustment = convexity_adjustment
self.extrapolation_mode = extrapolation_mode
self.interpolation_mode = interpolation_mode
self.price_side = price_side
self.steps = try_copy_to_list(steps)
self.turns = try_copy_to_list(turns)
self.ignore_existing_definition = ignore_existing_definition
self.reference_tenor = reference_tenor
self.use_convexity_adjustment = use_convexity_adjustment
self.use_multi_dimensional_solver = use_multi_dimensional_solver
self.use_steps = use_steps
self.valuation_date = valuation_date
self.market_data_access_denied_fallback = market_data_access_denied_fallback
self.pivot_curve_parameters = try_copy_to_list(pivot_curve_parameters)
self.reference_curve_parameters = try_copy_to_list(reference_curve_parameters)
self.valuation_time = valuation_time
self.ignore_invalid_instrument = ignore_invalid_instrument
self.use_delayed_data_if_denied = use_delayed_data_if_denied
self.valuation_date_time = valuation_date_time
def __repr__(self):
return create_repr(
self,
middle_path="curves.forward_curves",
class_name=self.__class__.__name__,
)
@property
def calendar_adjustment(self):
"""
Cash flow adjustment according to a calendar
No:
Null:
Weekend: for cash flow pricing using the calendar
WeekendCalendar: for cash flow pricing using the calendar defined
by the parameter 'calendars'.
:return: enum CalendarAdjustment
"""
return self._get_enum_parameter(CalendarAdjustment, "calendarAdjustment")
@calendar_adjustment.setter
def calendar_adjustment(self, value):
self._set_enum_parameter(CalendarAdjustment, "calendarAdjustment", value)
@property
def calendars(self):
"""
A list of one or more calendar codes used to define non-working days and to
adjust coupon dates and values.
:return: list string
"""
return self._get_list_parameter(str, "calendars")
@calendars.setter
def calendars(self, value):
self._set_list_parameter(str, "calendars", value)
@property
def compounding_type(self):
"""
:return: enum CompoundingType
"""
return self._get_enum_parameter(CompoundingType, "compoundingType")
@compounding_type.setter
def compounding_type(self, value):
self._set_enum_parameter(CompoundingType, "compoundingType", value)
@property
def convexity_adjustment(self):
"""
:return: object ConvexityAdjustment
"""
return self._get_object_parameter(ConvexityAdjustment, "convexityAdjustment")
@convexity_adjustment.setter
def convexity_adjustment(self, value):
self._set_object_parameter(ConvexityAdjustment, "convexityAdjustment", value)
@property
def extrapolation_mode(self):
"""
None: no extrapolation
Constant: constant extrapolation
Linear: linear extrapolation
:return: enum ExtrapolationMode
"""
return self._get_enum_parameter(ExtrapolationMode, "extrapolationMode")
@extrapolation_mode.setter
def extrapolation_mode(self, value):
self._set_enum_parameter(ExtrapolationMode, "extrapolationMode", value)
@property
def interest_calculation_method(self):
"""
Day count basis of the calculated zero coupon rates.
Default value is: Dcb_Actual_Actual
:return: enum DayCountBasis
"""
return self._get_enum_parameter(DayCountBasis, "interestCalculationMethod")
@interest_calculation_method.setter
def interest_calculation_method(self, value):
self._set_enum_parameter(DayCountBasis, "interestCalculationMethod", value)
@property
def interpolation_mode(self):
"""
Interpolation method used in swap zero curve bootstrap.
Default value is: CubicSpline
CubicDiscount: local cubic interpolation of discount factors
CubicRate: local cubic interpolation of rates
CubicSpline: a natural cubic spline
Linear: linear interpolation
Log: log linear interpolation
ForwardMonotoneConvex
:return: enum InterpolationMode
"""
return self._get_enum_parameter(InterpolationMode, "interpolationMode")
@interpolation_mode.setter
def interpolation_mode(self, value):
self._set_enum_parameter(InterpolationMode, "interpolationMode", value)
@property
def price_side(self):
"""
Defines which data is used for the rate surface computation.
Default value is: Mid
:return: enum PriceSide
"""
return self._get_enum_parameter(PriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(PriceSide, "priceSide", value)
@property
def steps(self):
"""
Use to calculate the swap rate surface discount curve, when OIS is selected as
discount curve.
The steps can specify overnight index stepped dates or/and rates.
:return: list Step
"""
return self._get_list_parameter(Step, "steps")
@steps.setter
def steps(self, value):
self._set_list_parameter(Step, "steps", value)
@property
def turns(self):
"""
Used to include end period rates/turns when calculating swap rate surfaces
:return: list Turn
"""
return self._get_list_parameter(Turn, "turns")
@turns.setter
def turns(self, value):
self._set_list_parameter(Turn, "turns", value)
@property
def ignore_existing_definition(self):
return self._ignore_existing_definition
@ignore_existing_definition.setter
def ignore_existing_definition(self, value):
self._ignore_existing_definition = value
@property
def reference_tenor(self):
"""
Root tenor(s) for the xIbor dependencies
:return: str
"""
return self._get_parameter("referenceTenor")
@reference_tenor.setter
def reference_tenor(self, value):
self._set_parameter("referenceTenor", value)
@property
def use_convexity_adjustment(self):
"""
false / true
Default value is: true.
It indicates if the system needs to retrieve the convexity adjustment
:return: bool
"""
return self._get_parameter("useConvexityAdjustment")
@use_convexity_adjustment.setter
def use_convexity_adjustment(self, value):
self._set_parameter("useConvexityAdjustment", value)
@property
def use_multi_dimensional_solver(self):
"""
false / true
Default value is: true.
Specifies the use of the multi-dimensional solver for yield curve bootstrapping.
This solving method is required because the bootstrapping method sometimes
creates a ZC curve which does not accurately reprice the input instruments used
to build it.
The multi-dimensional solver is recommended when cubic interpolation methods
are used in building the curve
(in other cases, performance might be inferior to the regular bootstrapping
method).
- true: to use multi-dimensional solver for yield curve bootstrapping
- false: not to use multi-dimensional solver for yield curve bootstrapping
:return: bool
"""
return self._get_parameter("useMultiDimensionalSolver")
@use_multi_dimensional_solver.setter
def use_multi_dimensional_solver(self, value):
self._set_parameter("useMultiDimensionalSolver", value)
@property
def use_steps(self):
"""
false / true
Default value is: false.
It indicates if the system needs to retrieve the overnight index
stepped dates or/and rates
:return: bool
"""
return self._get_parameter("useSteps")
@use_steps.setter
def use_steps(self, value):
self._set_parameter("useSteps", value)
@property
def valuation_date(self):
"""
The valuation date
Default value is the current date
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_date_parameter("valuationDate", value)
@property
def market_data_access_denied_fallback(self):
"""
If at leat one constituent access is denied:
* returnerror: dont price the surface and return an error (default value)
* ignoreconstituents: price the surface without the error market data
* usedelayeddata: use delayed market data if possible
:return: enum MarketDataAccessDeniedFallback
"""
return self._get_enum_parameter(MarketDataAccessDeniedFallback, "marketDataAccessDeniedFallback")
@market_data_access_denied_fallback.setter
def market_data_access_denied_fallback(self, value):
self._set_enum_parameter(MarketDataAccessDeniedFallback, "marketDataAccessDeniedFallback", value)
@property
def pivot_curve_parameters(self):
"""
The list of parameters used to define the pivot curve which is used for
evaluation of the adjusted zero coupon curve. for example, eur zero curve
adjusted with gbp curve, using usd as a pivot.
:return: list InterestRateCurveParameters
"""
return self._get_list_parameter(InterestRateCurveParameters, "pivotCurveParameters")
@pivot_curve_parameters.setter
def pivot_curve_parameters(self, value):
self._set_list_parameter(InterestRateCurveParameters, "pivotCurveParameters", value)
@property
def reference_curve_parameters(self):
"""
The list of parameters used to define the reference curve which is used for
evaluation of the adjusted zero coupon curve. for example, eur zero curve is
adjusted with gbp curve.
:return: object InterestRateCurveParameters
"""
return self._get_list_parameter(InterestRateCurveParameters, "referenceCurveParameters")
@reference_curve_parameters.setter
def reference_curve_parameters(self, value):
self._set_list_parameter(InterestRateCurveParameters, "referenceCurveParameters", value)
@property
def valuation_time(self):
"""
The time identified by offsets at which the zero coupon curve is generated.
:return: object ValuationTime
"""
return self._get_object_parameter(ValuationTime, "valuationTime")
@valuation_time.setter
def valuation_time(self, value):
self._set_object_parameter(ValuationTime, "valuationTime", value)
@property
def ignore_invalid_instrument(self):
"""
Ignore invalid instrument to calculate the curve. if false and some instrument
are invlide, the curve is not calculated and an error is returned. the default
value is 'true'.
:return: bool
"""
return self._get_parameter("ignoreInvalidInstrument")
@ignore_invalid_instrument.setter
def ignore_invalid_instrument(self, value):
self._set_parameter("ignoreInvalidInstrument", value)
@property
def use_delayed_data_if_denied(self):
"""
Use delayed ric to retrieve data when not permissioned on constituent ric. the
default value is 'false'.
:return: bool
"""
return self._get_parameter("useDelayedDataIfDenied")
@use_delayed_data_if_denied.setter
def use_delayed_data_if_denied(self, value):
self._set_parameter("useDelayedDataIfDenied", value)
@property
def valuation_date_time(self):
"""
The date and time at which the zero coupon curve is generated.
The value is expressed in iso 8601 format: yyyy-mm-ddt00:00:00z
(e.g., '2021-01-01t14:00:00z' or '2021-01-01t14:00:00+02:00').
Only one parameter of valuation_date and valuation_date_time must be specified.
:return: str
"""
return self._get_parameter("valuationDateTime")
@valuation_date_time.setter
def valuation_date_time(self, value):
self._set_datetime_parameter("valuationDateTime", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_swap_zc_curve_parameters.py | 0.954605 | 0.545286 | _swap_zc_curve_parameters.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._enums import (
CalendarAdjustment,
CompoundingType,
ExtrapolationMode,
DayCountBasis,
MarketDataAccessDeniedFallback,
SwapPriceSide,
ZcInterpolationMode,
)
from ._models import (
Step,
Turn,
InterestRateCurveParameters,
ConvexityAdjustment,
ValuationTime,
)
from .._object_definition import ObjectDefinition
from ...._tools import create_repr, try_copy_to_list
from ...._types import OptBool, OptStr, Strings, OptDateTime
if TYPE_CHECKING:
from ._zc_curve_types import Steps, Turns
class ZcCurveParameters(ObjectDefinition):
"""
Parameters
----------
interest_calculation_method : DayCountBasis, optional
Day count basis of the calculated zero coupon rates
calendar_adjustment : CalendarAdjustment, optional
Cash flow adjustment according to a calendar.
- No: for analytic pricing (i.e. from the bond structure)
- Null: for cash flow pricing using the calendar null
- Weekend: for cash flow pricing using the calendar weekend
- Calendar: for cash flow pricing using the calendar defined
by the parameter calendars.
calendars : string, optional
A list of one or more calendar codes used to define non-working days and to
adjust coupon dates and values.
compounding_type : CompoundingType, optional
Output rates yield type. Values can be:
- Continuous: continuous rate (default value)
- MoneyMarket: money market rate
- Compounded: compounded rate
- Discounted: discounted rate
convexity_adjustment : ConvexityAdjustment, optional
extrapolation_mode : ExtrapolationMode, optional
Extrapolation method for the curve
- None: no extrapolation
- Constant: constant extrapolation
- Linear: linear extrapolation
interpolation_mode : ZcInterpolationMode, optional
Interpolation method for the curve. Available values are:
- CubicDiscount: local cubic interpolation of discount factors
- CubicRate: local cubic interpolation of rates
- CubicSpline: a natural cubic spline
- ForwardMonotoneConvex: forward mMonotone Convexc interpolation
- Linear: linear interpolation
- Log: log-linear interpolation
- Hermite: hermite (bessel) interpolation
- AkimaMethod: the Akima method
(a smoother variant of local cubic interpolation)
- FritschButlandMethod: the Fritsch-Butland method (a monotonic cubic variant)
- KrugerMethod: the Kruger method (a monotonic cubic variant)
- MonotonicCubicNaturalSpline: a monotonic natural cubic spline
- MonotonicHermiteCubic: monotonic hermite (Bessel) cubic interpolation
- TensionSpline: a tension spline
market_data_access_denied_fallback : MarketDataAccessDeniedFallback, optional
- ReturnError: dont price the surface and return an error (Default value)
- IgnoreConstituents: price the surface without the error market data
- UseDelayedData: use delayed Market Data if possible
pivot_curve_parameters : InterestRateCurveParameters, optional
price_side : SwapPriceSide, optional
Price side of the instrument to be used. default value is: mid
reference_curve_parameters : InterestRateCurveParameters, optional
steps : list of Step, optional
turns : list of Turn, optional
Used to include end period rates/turns when calculating swap rate surfaces
reference_tenor : str, optional
Root tenor(s) for the xIbor dependencies
use_convexity_adjustment : bool, optional
use_multi_dimensional_solver : bool, optional
Specifies the use of the multi-dimensional solver for yield curve bootstrapping.
This solving method is required because the bootstrapping method sometimes
creates a ZC curve which does not accurately reprice the input instruments used
to build it. The multi-dimensional solver is recommended when cubic
interpolation methods are used in building the curve (in other cases,
performance might be inferior to the regular bootstrapping method). When use for
Credit Curve it is only used when the calibrationModel is set to Bootstrap.
- true: to use multi-dimensional solver for yield curve bootstrapping
- false: not to use multi-dimensional solver for yield curve bootstrapping
use_steps : bool, optional
valuation_date : str or date or datetime or timedelta, optional
The valuation date. The default value is the current date.
valuation_time : ValuationTime, optional
The time identified by offsets at which the zero coupon curve is generated.
ignore_invalid_instrument : bool, optional
Ignore invalid instrument to calculate the curve.
if False and some instrument are invlide, the curve is not calculated and an
error is returned.
The default value is 'True'.
use_delayed_data_if_denied : bool, optional
Use delayed ric to retrieve data when not permissioned on constituent ric.
The default value is 'False'.
valuation_date_time : str or date or datetime or timedelta, optional
The date and time at which the zero coupon curve is generated. the value is
expressed in iso 8601 format: yyyy-mm-ddt00:00:00z (e.g., '2021-01-01t14:00:00z'
or '2021-01-01t14:00:00+02:00'). Only one parameter of valuation_date and
valuation_date_time must be specified.
"""
_ignore_existing_definition = None
def __init__(
self,
interest_calculation_method: Optional[DayCountBasis] = None,
calendar_adjustment: Optional[CalendarAdjustment] = None,
calendars: Strings = None,
compounding_type: Optional[CompoundingType] = None,
convexity_adjustment: Optional[ConvexityAdjustment] = None,
extrapolation_mode: Optional[ExtrapolationMode] = None,
interpolation_mode: Optional[ZcInterpolationMode] = None,
market_data_access_denied_fallback: Optional[MarketDataAccessDeniedFallback] = None,
pivot_curve_parameters: Optional[InterestRateCurveParameters] = None,
price_side: Optional[SwapPriceSide] = None,
reference_curve_parameters: Optional[InterestRateCurveParameters] = None,
steps: "Steps" = None,
turns: "Turns" = None,
ignore_existing_definition: OptBool = None,
reference_tenor: OptStr = None,
use_convexity_adjustment: OptBool = None,
use_multi_dimensional_solver: OptBool = None,
use_steps: OptBool = None,
valuation_date: "OptDateTime" = None,
valuation_time: Optional[ValuationTime] = None,
ignore_invalid_instrument: OptBool = None,
use_delayed_data_if_denied: OptBool = None,
valuation_date_time: "OptDateTime" = None,
) -> None:
super().__init__()
self.interest_calculation_method = interest_calculation_method
self.calendar_adjustment = calendar_adjustment
self.calendars = try_copy_to_list(calendars)
self.compounding_type = compounding_type
self.convexity_adjustment = convexity_adjustment
self.extrapolation_mode = extrapolation_mode
self.interpolation_mode = interpolation_mode
self.market_data_access_denied_fallback = market_data_access_denied_fallback
self.pivot_curve_parameters = pivot_curve_parameters
self.price_side = price_side
self.reference_curve_parameters = reference_curve_parameters
self.steps = try_copy_to_list(steps)
self.turns = try_copy_to_list(turns)
self.ignore_existing_definition = ignore_existing_definition
self.reference_tenor = reference_tenor
self.use_convexity_adjustment = use_convexity_adjustment
self.use_multi_dimensional_solver = use_multi_dimensional_solver
self.use_steps = use_steps
self.valuation_date = valuation_date
self.valuation_time = valuation_time
self.ignore_invalid_instrument = ignore_invalid_instrument
self.use_delayed_data_if_denied = use_delayed_data_if_denied
self.valuation_date_time = valuation_date_time
def __repr__(self):
return create_repr(
self,
middle_path="curves.zc_curves",
class_name=self.__class__.__name__,
)
@property
def calendar_adjustment(self):
"""
Cash flow adjustment according to a calendar.
- No: for analytic pricing (i.e. from the bond structure)
- Null: for cash flow pricing using the calendar null
- Weekend: for cash flow pricing using the calendar weekend
- Calendar: for cash flow pricing using the calendar defined
by the parameter calendars.
:return: enum CalendarAdjustment
"""
return self._get_enum_parameter(CalendarAdjustment, "calendarAdjustment")
@calendar_adjustment.setter
def calendar_adjustment(self, value):
self._set_enum_parameter(CalendarAdjustment, "calendarAdjustment", value)
@property
def calendars(self):
"""
A list of one or more calendar codes used to define non-working days and to
adjust coupon dates and values.
:return: list string
"""
return self._get_list_parameter(str, "calendars")
@calendars.setter
def calendars(self, value):
self._set_list_parameter(str, "calendars", value)
@property
def compounding_type(self):
"""
Output rates yield type. Values can be:
- Continuous: continuous rate (default value)
- MoneyMarket: money market rate
- Compounded: compounded rate
- Discounted: discounted rate
:return: enum CompoundingType
"""
return self._get_enum_parameter(CompoundingType, "compoundingType")
@compounding_type.setter
def compounding_type(self, value):
self._set_enum_parameter(CompoundingType, "compoundingType", value)
@property
def convexity_adjustment(self):
"""
:return: object ConvexityAdjustment
"""
return self._get_object_parameter(ConvexityAdjustment, "convexityAdjustment")
@convexity_adjustment.setter
def convexity_adjustment(self, value):
self._set_object_parameter(ConvexityAdjustment, "convexityAdjustment", value)
@property
def extrapolation_mode(self):
"""
Extrapolation method for the curve
- None: no extrapolation
- Constant: constant extrapolation
- Linear: linear extrapolation
:return: enum ExtrapolationMode
"""
return self._get_enum_parameter(ExtrapolationMode, "extrapolationMode")
@extrapolation_mode.setter
def extrapolation_mode(self, value):
self._set_enum_parameter(ExtrapolationMode, "extrapolationMode", value)
@property
def interest_calculation_method(self):
"""
Day count basis of the calculated zero coupon rates
:return: enum DayCountBasis
"""
return self._get_enum_parameter(DayCountBasis, "interestCalculationMethod")
@interest_calculation_method.setter
def interest_calculation_method(self, value):
self._set_enum_parameter(DayCountBasis, "interestCalculationMethod", value)
@property
def interpolation_mode(self):
"""
Interpolation method for the curve.
Available values are:
- CubicDiscount: local cubic interpolation of discount factors
- CubicRate: local cubic interpolation of rates
- CubicSpline: a natural cubic spline
- ForwardMonotoneConvex: forward mMonotone Convexc interpolation
- Linear: linear interpolation
- Log: log-linear interpolation
- Hermite: Hermite (Bessel) interpolation
- AkimaMethod: the Akima method (a smoother variant of local cubic interpolation)
- FritschButlandMethod: the Fritsch-Butland method (a monotonic cubic variant)
- KrugerMethod: the Kruger method (a monotonic cubic variant)
- MonotonicCubicNaturalSpline: a monotonic natural cubic spline
- MonotonicHermiteCubic: monotonic Hermite (Bessel) cubic interpolation
- TensionSpline: a tension spline
:return: enum ZcInterpolationMode
"""
return self._get_enum_parameter(ZcInterpolationMode, "interpolationMode")
@interpolation_mode.setter
def interpolation_mode(self, value):
self._set_enum_parameter(ZcInterpolationMode, "interpolationMode", value)
@property
def market_data_access_denied_fallback(self):
"""
- ReturnError: dont price the surface and return an error (Default value)
- IgnoreConstituents: price the surface without the error market data
- UseDelayedData: use delayed Market Data if possible
:return: enum MarketDataAccessDeniedFallback
"""
return self._get_enum_parameter(MarketDataAccessDeniedFallback, "marketDataAccessDeniedFallback")
@market_data_access_denied_fallback.setter
def market_data_access_denied_fallback(self, value):
self._set_enum_parameter(MarketDataAccessDeniedFallback, "marketDataAccessDeniedFallback", value)
@property
def pivot_curve_parameters(self):
"""
:return: object InterestRateCurveParameters
"""
return self._get_object_parameter(InterestRateCurveParameters, "pivotCurveParameters")
@pivot_curve_parameters.setter
def pivot_curve_parameters(self, value):
self._set_object_parameter(InterestRateCurveParameters, "pivotCurveParameters", value)
@property
def price_side(self):
"""
Price side of the instrument to be used. Default value is: Mid
:return: enum SwapPriceSide
"""
return self._get_enum_parameter(SwapPriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(SwapPriceSide, "priceSide", value)
@property
def reference_curve_parameters(self):
"""
:return: object InterestRateCurveParameters
"""
return self._get_object_parameter(InterestRateCurveParameters, "referenceCurveParameters")
@reference_curve_parameters.setter
def reference_curve_parameters(self, value):
self._set_object_parameter(InterestRateCurveParameters, "referenceCurveParameters", value)
@property
def steps(self):
"""
:return: list Step
"""
return self._get_list_parameter(Step, "steps")
@steps.setter
def steps(self, value):
self._set_list_parameter(Step, "steps", value)
@property
def turns(self):
"""
Used to include end period rates/turns when calculating swap rate surfaces
:return: list Turn
"""
return self._get_list_parameter(Turn, "turns")
@turns.setter
def turns(self, value):
self._set_list_parameter(Turn, "turns", value)
@property
def ignore_existing_definition(self):
return self._ignore_existing_definition
@ignore_existing_definition.setter
def ignore_existing_definition(self, value):
self._ignore_existing_definition = value
@property
def reference_tenor(self):
"""
Root tenor(s) for the xIbor dependencies
:return: str
"""
return self._get_parameter("referenceTenor")
@reference_tenor.setter
def reference_tenor(self, value):
self._set_parameter("referenceTenor", value)
@property
def use_convexity_adjustment(self):
"""
:return: bool
"""
return self._get_parameter("useConvexityAdjustment")
@use_convexity_adjustment.setter
def use_convexity_adjustment(self, value):
self._set_parameter("useConvexityAdjustment", value)
@property
def use_multi_dimensional_solver(self):
"""
Specifies the use of the multi-dimensional solver for yield curve bootstrapping.
This solving method is required because the bootstrapping method sometimes
creates a ZC curve which does not accurately reprice the input instruments used
to build it. The multi-dimensional solver is recommended when cubic
interpolation methods are used in building the curve (in other cases,
performance might be inferior to the regular bootstrapping method). When use for
Credit Curve it is only used when the calibrationModel is set to Bootstrap.
- true: to use multi-dimensional solver for yield curve bootstrapping
- false: not to use multi-dimensional solver for yield curve bootstrapping
:return: bool
"""
return self._get_parameter("useMultiDimensionalSolver")
@use_multi_dimensional_solver.setter
def use_multi_dimensional_solver(self, value):
self._set_parameter("useMultiDimensionalSolver", value)
@property
def use_steps(self):
"""
:return: bool
"""
return self._get_parameter("useSteps")
@use_steps.setter
def use_steps(self, value):
self._set_parameter("useSteps", value)
@property
def valuation_date(self):
"""
The valuation date. The default value is the current date.
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_date_parameter("valuationDate", value)
@property
def valuation_time(self):
"""
The time identified by offsets at which the zero coupon curve is generated.
:return: object ValuationTime
"""
return self._get_object_parameter(ValuationTime, "valuationTime")
@valuation_time.setter
def valuation_time(self, value):
self._set_object_parameter(ValuationTime, "valuationTime", value)
@property
def ignore_invalid_instrument(self):
"""
Ignore invalid instrument to calculate the curve. if false and some instrument
are invlide, the curve is not calculated and an error is returned. the default
value is 'true'.
:return: bool
"""
return self._get_parameter("ignoreInvalidInstrument")
@ignore_invalid_instrument.setter
def ignore_invalid_instrument(self, value):
self._set_parameter("ignoreInvalidInstrument", value)
@property
def use_delayed_data_if_denied(self):
"""
Use delayed ric to retrieve data when not permissioned on constituent ric. the
default value is 'False'.
:return: bool
"""
return self._get_parameter("useDelayedDataIfDenied")
@use_delayed_data_if_denied.setter
def use_delayed_data_if_denied(self, value):
self._set_parameter("useDelayedDataIfDenied", value)
@property
def valuation_date_time(self):
"""
The date and time at which the zero coupon curve is generated. the value is
expressed in iso 8601 format: yyyy-mm-ddt00:00:00z (e.g., '2021-01-01t14:00:00z'
or '2021-01-01t14:00:00+02:00'). only one parameter of valuation_date and
valuation_date_time must be specified.
:return: str
"""
return self._get_parameter("valuationDateTime")
@valuation_date_time.setter
def valuation_date_time(self, value):
self._set_datetime_parameter("valuationDateTime", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_zc_curve_parameters.py | 0.944919 | 0.602793 | _zc_curve_parameters.py | pypi |
from typing import Optional
from .._object_definition import ObjectDefinition
from ._enums import AssetClass, RiskType, ConstituentOverrideMode
from ...._types import Strings, OptStr, OptStrings, OptBool
from ...._tools import create_repr, try_copy_to_list
class SwapZcCurveDefinition(ObjectDefinition):
"""
Parameters
----------
index_name : str, optional
main_constituent_asset_class : MainConstituentAssetClass, optional
risk_type : RiskType, optional
currency : str, optional
discounting_tenor : str, optional
id : str, optional
Id of the curve definition to get
market_data_location : str, optional
name : str, optional
source : str, optional
available_discounting_tenors : string, optional
The list of discounting tenors available when using a given interest rate curve.
the values come from availabletenors list (e.g., '[ois, 1m, 3m, 6m, 1y]').
available_tenors : string, optional
The list of tenors which can be priced with curvedefinitions (e.g., '[ois, 1m,
3m, 6m, 1y]'
constituent_override_mode : ConstituentOverrideMode, optional
The possible values are:
* replacedefinition: replace the default constituents by the user constituents
from the input request,
* mergewithdefinition: merge the default constituents and the user constituents
from the input request, the default value is 'replacedefinition'.
If the ignoreexistingdefinition is true, the constituentoverridemode is set
to replacedefinition.
ignore_existing_definition : bool, optional
An indicator whether default definitions are used to get curve parameters and
constituents.
The possible values are:
* True: default definitions are not used (definitions and constituents must
be set in the request),
* False: default definitions are used.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable:
* True: the instrument is non-deliverable,
* False: the instrument is not non-deliverable.
This parameter may be used to specify the use of crosscurrencydefinitions made
of non-deliverable or deliverable instruments. When this parameters isn't
specified, the default crosscurrencydefinitions is used. This definition with
'isfallbackforfxcurvedefinition'=True is returned by the
crosscurrencydefinitions curve search.
owner : str, optional
Uuid of the curve definition owner for none refinitiv curve
"""
_index_tenors = None
def __init__(
self,
index_name: OptStr = None,
index_tenors: Strings = None,
main_constituent_asset_class: Optional[AssetClass] = None,
risk_type: Optional[RiskType] = None,
currency: OptStr = None,
discounting_tenor: OptStr = None,
id: OptStr = None,
market_data_location: OptStr = None,
name: OptStr = None,
source: OptStr = None,
available_discounting_tenors: OptStrings = None,
available_tenors: OptStrings = None,
constituent_override_mode: Optional[ConstituentOverrideMode] = None,
ignore_existing_definition: OptBool = None,
is_non_deliverable: OptBool = None,
owner: OptStr = None,
) -> None:
super().__init__()
self.index_name = index_name
self.index_tenors = index_tenors
self.main_constituent_asset_class = main_constituent_asset_class
self.risk_type = risk_type
self.currency = currency
self.discounting_tenor = discounting_tenor
self.id = id
self.market_data_location = market_data_location
self.name = name
self.source = source
self.available_discounting_tenors = try_copy_to_list(available_discounting_tenors)
self.available_tenors = try_copy_to_list(available_tenors)
self.constituent_override_mode = constituent_override_mode
self.ignore_existing_definition = ignore_existing_definition
self.is_non_deliverable = is_non_deliverable
self.owner = owner
def __repr__(self):
return create_repr(
self,
middle_path="curves.forward_curves",
class_name=self.__class__.__name__,
)
@property
def index_tenors(self):
return self._index_tenors
@index_tenors.setter
def index_tenors(self, value):
self._index_tenors = value
@property
def main_constituent_asset_class(self):
"""
:return: enum AssetClass
"""
return self._get_enum_parameter(AssetClass, "mainConstituentAssetClass")
@main_constituent_asset_class.setter
def main_constituent_asset_class(self, value):
self._set_enum_parameter(AssetClass, "mainConstituentAssetClass", value)
@property
def risk_type(self):
"""
:return: enum RiskType
"""
return self._get_enum_parameter(RiskType, "riskType")
@risk_type.setter
def risk_type(self, value):
self._set_enum_parameter(RiskType, "riskType", value)
@property
def currency(self):
"""
:return: str
"""
return self._get_parameter("currency")
@currency.setter
def currency(self, value):
self._set_parameter("currency", value)
@property
def discounting_tenor(self):
"""
:return: str
"""
return self._get_parameter("discountingTenor")
@discounting_tenor.setter
def discounting_tenor(self, value):
self._set_parameter("discountingTenor", value)
@property
def id(self):
"""
Id of the curve definition to get
:return: str
"""
return self._get_parameter("id")
@id.setter
def id(self, value):
self._set_parameter("id", value)
@property
def index_name(self):
"""
:return: str
"""
return self._get_parameter("indexName")
@index_name.setter
def index_name(self, value):
self._set_parameter("indexName", value)
@property
def market_data_location(self):
"""
:return: str
"""
return self._get_parameter("marketDataLocation")
@market_data_location.setter
def market_data_location(self, value):
self._set_parameter("marketDataLocation", value)
@property
def name(self):
"""
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value)
@property
def source(self):
"""
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value)
@property
def available_discounting_tenors(self):
"""
The list of discounting tenors available when using a given interest rate curve.
the values come from availabletenors list (e.g., '[ois, 1m, 3m, 6m, 1y]').
:return: list string
"""
return self._get_list_parameter(str, "availableDiscountingTenors")
@available_discounting_tenors.setter
def available_discounting_tenors(self, value):
self._set_list_parameter(str, "availableDiscountingTenors", value)
@property
def available_tenors(self):
"""
The list of tenors which can be priced with curvedefinitions (e.g., '[ois, 1m,
3m, 6m, 1y]').
:return: list str
"""
return self._get_list_parameter(str, "availableTenors")
@available_tenors.setter
def available_tenors(self, value):
self._set_list_parameter(str, "availableTenors", value)
@property
def constituent_override_mode(self):
"""
A method to use the default constituents. the possible values are:
* replacedefinition: replace the default constituents by the user
constituents from the input request,
* mergewithdefinition: merge the default constituents and the user
constituents from the input request, the default value is 'replacedefinition'.
If the ignore_existing_definition is true, the constituent_override_mode
is set to 'replacedefinition'.
:return: enum ConstituentOverrideMode
"""
return self._get_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode")
@constituent_override_mode.setter
def constituent_override_mode(self, value):
self._set_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode", value)
@property
def ignore_existing_definition(self):
"""
An indicator whether default definitions are used to get curve parameters and
constituents. the possible values are: * true: default definitions are not
used (definitions and constituents must be set in the request), * false:
default definitions are used.
:return: bool
"""
return self._get_parameter("ignoreExistingDefinition")
@ignore_existing_definition.setter
def ignore_existing_definition(self, value):
self._set_parameter("ignoreExistingDefinition", value)
@property
def is_non_deliverable(self):
"""
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. this
parameter may be used to specify the use of crosscurrencydefinitions made of
non-deliverable or deliverable instruments. when this parameters isn't
specified, the default crosscurrencydefinitions is used. this definition with
'isfallbackforfxcurvedefinition'=true is returned by the
crosscurrencydefinitions curve search.
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def owner(self):
"""
Uuid of the curve definition owner for none refinitiv curve
:return: str
"""
return self._get_parameter("owner")
@owner.setter
def owner(self, value):
self._set_parameter("owner", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_swap_zc_curve_definition.py | 0.944035 | 0.400515 | _swap_zc_curve_definition.py | pypi |
from typing import Optional, TYPE_CHECKING
from .._object_definition import ObjectDefinition
from ._enums import (
AssetClass,
RiskType,
ConstituentOverrideMode,
)
if TYPE_CHECKING:
from ...._types import OptStr, OptBool
class ZcCurveDefinition(ObjectDefinition):
"""
Parameters
----------
index_name : str, optional
main_constituent_asset_class : AssetClass, optional
risk_type : RiskType, optional
currency : str, optional
The currency code of the interest rate curve
discounting_tenor : str, optional
Mono currency discounting tenor
id : str, optional
Id of the curve definition
name : str, optional
The name of the interest rate curve
source : str, optional
constituent_override_mode : ConstituentOverrideMode, optional
The possible values are:
* replacedefinition: replace the default constituents by the user
constituents from the input request,
* mergewithdefinition: merge the default constituents and the user
constituents from the input request, the default value is 'replacedefinition'.
If the ignore_existing_definition is true, the constituent_override_mode
is set to 'replacedefinition'.
ignore_existing_definition : bool, optional
An indicator whether default definitions are used to get curve parameters and
constituents.
The possible values are:
* True: default definitions are not used (definitions and constituents
must be set in the request),
* False: default definitions are used.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable.
The possible values are:
* True: the instrument is non-deliverable,
* False: the instrument is not non-deliverable.
This parameter may be used to specify the use of crosscurrencydefinitions made
of non-deliverable or deliverable instruments. When this parameters isn't
specified, the default crosscurrencydefinitions is used. this definition with
'isfallbackforfxcurvedefinition'=True is returned by the
crosscurrencydefinitions curve search.
market_data_location : str, optional
The identifier of the market place from which constituents come from. currently
the following values are supported: 'onshore' and 'emea'. the list of values can
be extended by a user when creating a curve.
"""
def __init__(
self,
index_name: "OptStr" = None,
main_constituent_asset_class: Optional[AssetClass] = None,
risk_type: Optional[RiskType] = None,
currency: "OptStr" = None,
discounting_tenor: "OptStr" = None,
id: "OptStr" = None,
name: "OptStr" = None,
source: "OptStr" = None,
constituent_override_mode: Optional[ConstituentOverrideMode] = None,
ignore_existing_definition: "OptBool" = None,
is_non_deliverable: "OptBool" = None,
market_data_location: "OptStr" = None,
) -> None:
super().__init__()
self.index_name = index_name
self.main_constituent_asset_class = main_constituent_asset_class
self.risk_type = risk_type
self.currency = currency
self.discounting_tenor = discounting_tenor
self.id = id
self.name = name
self.source = source
self.constituent_override_mode = constituent_override_mode
self.ignore_existing_definition = ignore_existing_definition
self.is_non_deliverable = is_non_deliverable
self.market_data_location = market_data_location
@property
def main_constituent_asset_class(self):
"""
:return: enum AssetClass
"""
return self._get_enum_parameter(AssetClass, "mainConstituentAssetClass")
@main_constituent_asset_class.setter
def main_constituent_asset_class(self, value):
self._set_enum_parameter(AssetClass, "mainConstituentAssetClass", value)
@property
def risk_type(self):
"""
:return: enum RiskType
"""
return self._get_enum_parameter(RiskType, "riskType")
@risk_type.setter
def risk_type(self, value):
self._set_enum_parameter(RiskType, "riskType", value)
@property
def currency(self):
"""
The currency code of the interest rate curve
:return: str
"""
return self._get_parameter("currency")
@currency.setter
def currency(self, value):
self._set_parameter("currency", value)
@property
def discounting_tenor(self):
"""
Mono currency discounting tenor
:return: str
"""
return self._get_parameter("discountingTenor")
@discounting_tenor.setter
def discounting_tenor(self, value):
self._set_parameter("discountingTenor", value)
@property
def id(self):
"""
Id of the curve definition
:return: str
"""
return self._get_parameter("id")
@id.setter
def id(self, value):
self._set_parameter("id", value)
@property
def index_name(self):
"""
:return: str
"""
return self._get_parameter("indexName")
@index_name.setter
def index_name(self, value):
self._set_parameter("indexName", value)
@property
def name(self):
"""
The name of the interest rate curve
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value)
@property
def source(self):
"""
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value)
@property
def constituent_override_mode(self):
"""
A method to use the default constituents. the possible values are:
* replacedefinition: replace the default constituents by the user
constituents from the input request,
* mergewithdefinition: merge the default constituents and the user
constituents from the input request, the default value is 'replacedefinition'.
If the ignore_existing_definition is true, the constituent_override_mode
is set to 'replacedefinition'.
:return: enum ConstituentOverrideMode
"""
return self._get_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode")
@constituent_override_mode.setter
def constituent_override_mode(self, value):
self._set_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode", value)
@property
def ignore_existing_definition(self):
"""
An indicator whether default definitions are used to get curve parameters and
constituents.
The possible values are:
* True: default definitions are not used (definitions and constituents
must be set in the request),
* False: default definitions are used.
:return: bool
"""
return self._get_parameter("ignoreExistingDefinition")
@ignore_existing_definition.setter
def ignore_existing_definition(self, value):
self._set_parameter("ignoreExistingDefinition", value)
@property
def is_non_deliverable(self):
"""
An indicator whether the instrument is non-deliverable.
The possible values are:
* True: the instrument is non-deliverable,
* False: the instrument is not non-deliverable.
This parameter may be used to specify the use of crosscurrencydefinitions made
of non-deliverable or deliverable instruments. When this parameters isn't
specified, the default crosscurrencydefinitions is used. this definition with
'isfallbackforfxcurvedefinition'=True is returned by the
crosscurrencydefinitions curve search.
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def market_data_location(self):
"""
The identifier of the market place from which constituents come from. currently
the following values are supported: 'onshore' and 'emea'. the list of values can
be extended by a user when creating a curve.
:return: str
"""
return self._get_parameter("marketDataLocation")
@market_data_location.setter
def market_data_location(self, value):
self._set_parameter("marketDataLocation", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_zc_curve_definition.py | 0.937009 | 0.410815 | _zc_curve_definition.py | pypi |
from typing import TYPE_CHECKING, Any, Union
from ._shift_scenario import ShiftScenario
from ._forward_curve_definition import ForwardCurveDefinition
from ._swap_zc_curve_definition import SwapZcCurveDefinition
from ._swap_zc_curve_parameters import SwapZcCurveParameters
from .._object_definition import ObjectDefinition
from ...._tools import ArgsParser
if TYPE_CHECKING:
from ...._types import OptStr
from ._forward_curve_types import (
ShiftScenarios,
CurveDefinition,
CurveParameters,
ForwardCurveDefinitions,
)
def parse_objects(param: object) -> Union[list, Any]:
if not param:
return param
if not isinstance(param, list):
param = [param]
return param
object_arg_parser = ArgsParser(parse_objects)
class ForwardCurveRequestItem(ObjectDefinition):
"""
Parameters
----------
curve_definition : SwapZcCurveDefinition, optional
curve_parameters : SwapZcCurveParameters, optional
forward_curve_definitions : list of ForwardCurveDefinition, optional
curve_tag : str, optionalx
shift_scenarios : list of ShiftScenario, optional
"""
def __init__(
self,
curve_definition: "CurveDefinition" = None,
forward_curve_definitions: "ForwardCurveDefinitions" = None,
curve_parameters: "CurveParameters" = None,
curve_tag: "OptStr" = None,
shift_scenarios: "ShiftScenarios" = None,
) -> None:
super().__init__()
self.curve_definition = curve_definition
self.curve_parameters = curve_parameters
self.forward_curve_definitions = object_arg_parser.parse(forward_curve_definitions)
self.curve_tag = curve_tag
self.shift_scenarios = object_arg_parser.parse(shift_scenarios)
@property
def curve_definition(self):
"""
:return: object SwapZcCurveDefinition
"""
return self._get_object_parameter(SwapZcCurveDefinition, "curveDefinition")
@curve_definition.setter
def curve_definition(self, value):
self._set_object_parameter(SwapZcCurveDefinition, "curveDefinition", value)
@property
def curve_parameters(self):
"""
:return: object SwapZcCurveParameters
"""
return self._get_object_parameter(SwapZcCurveParameters, "curveParameters")
@curve_parameters.setter
def curve_parameters(self, value):
self._set_object_parameter(SwapZcCurveParameters, "curveParameters", value)
@property
def forward_curve_definitions(self):
"""
:return: list ForwardCurveDefinition
"""
return self._get_list_parameter(ForwardCurveDefinition, "forwardCurveDefinitions")
@forward_curve_definitions.setter
def forward_curve_definitions(self, value):
self._set_list_parameter(ForwardCurveDefinition, "forwardCurveDefinitions", value)
@property
def curve_tag(self):
"""
:return: str
"""
return self._get_parameter("curveTag")
@curve_tag.setter
def curve_tag(self, value):
self._set_parameter("curveTag", value)
@property
def shift_scenarios(self):
"""
:return: list ShiftScenario
"""
return self._get_list_parameter(ShiftScenario, "shiftScenarios")
@shift_scenarios.setter
def shift_scenarios(self, value):
self._set_list_parameter(ShiftScenario, "shiftScenarios", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_forward_curve_request_item.py | 0.954984 | 0.163512 | _forward_curve_request_item.py | pypi |
from typing import Optional
from ._models._par_rate_shift import ParRateShift
from .._object_definition import ObjectDefinition
class ShiftScenario(ObjectDefinition):
"""
Parameters
----------
par_rate_shift : ParRateShift, optional
Scenario of par rates shift (shift applied to constituents).
shift_tag : str, optional
User defined string to identify the shift scenario tag. it can be used to link
output curve to the shift scenario. only alphabetic, numeric and '- _.#=@'
characters are supported. optional.
zc_curve_shift : dict, optional
Collection of shift parameters tenor. "all" selector supported as well.
"""
def __init__(
self,
*,
par_rate_shift: Optional[ParRateShift] = None,
shift_tag: Optional[str] = None,
zc_curve_shift: Optional[dict] = None,
) -> None:
super().__init__()
self.par_rate_shift = par_rate_shift
self.shift_tag = shift_tag
self.zc_curve_shift = zc_curve_shift
@property
def par_rate_shift(self):
"""
Scenario of par rates shift (shift applied to constituents).
:return: object ParRateShift
"""
return self._get_object_parameter(ParRateShift, "parRateShift")
@par_rate_shift.setter
def par_rate_shift(self, value):
self._set_object_parameter(ParRateShift, "parRateShift", value)
@property
def shift_tag(self):
"""
User defined string to identify the shift scenario tag. it can be used to link
output curve to the shift scenario. only alphabetic, numeric and '- _.#=@'
characters are supported. optional.
:return: str
"""
return self._get_parameter("shiftTag")
@shift_tag.setter
def shift_tag(self, value):
self._set_parameter("shiftTag", value)
@property
def zc_curve_shift(self):
"""
Collection of shift parameters tenor. "all" selector supported as well.
:return: dict
"""
return self._get_parameter("zcCurveShift")
@zc_curve_shift.setter
def zc_curve_shift(self, value):
self._set_parameter("zcCurveShift", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_shift_scenario.py | 0.960212 | 0.345795 | _shift_scenario.py | pypi |
from .._object_definition import ObjectDefinition
from ...._tools import try_copy_to_list
from ...._types import OptStr, OptStrings, OptDateTime
class ForwardCurveDefinition(ObjectDefinition):
"""
Parameters
----------
index_tenor : str, optional
forward_curve_tenors : list of str, optional
Defines expected forward rate surface tenor/slices
forward_curve_tag : str, optional
forward_start_date : str or date or datetime or timedelta, optional
Defines the forward start date by date format
forward_start_tenor : str, optional
Defines the forward start date by tenor format: "Spot" / "1M" / ...
"""
def __init__(
self,
index_tenor: OptStr = None,
forward_curve_tag: OptStr = None,
forward_curve_tenors: OptStrings = None,
forward_start_date: "OptDateTime" = None,
forward_start_tenor: OptStr = None,
) -> None:
super().__init__()
self.index_tenor = index_tenor
self.forward_curve_tenors = try_copy_to_list(forward_curve_tenors)
self.forward_curve_tag = forward_curve_tag
self.forward_start_date = forward_start_date
self.forward_start_tenor = forward_start_tenor
@property
def forward_curve_tenors(self):
"""
Defines expected forward rate surface tenor/slices
:return: list string
"""
return self._get_list_parameter(str, "forwardCurveTenors")
@forward_curve_tenors.setter
def forward_curve_tenors(self, value):
self._set_list_parameter(str, "forwardCurveTenors", value)
@property
def forward_curve_tag(self):
"""
:return: str
"""
return self._get_parameter("forwardCurveTag")
@forward_curve_tag.setter
def forward_curve_tag(self, value):
self._set_parameter("forwardCurveTag", value)
@property
def forward_start_date(self):
"""
Defines the forward start date by date format
:return: str
"""
return self._get_parameter("forwardStartDate")
@forward_start_date.setter
def forward_start_date(self, value):
self._set_date_parameter("forwardStartDate", value)
@property
def forward_start_tenor(self):
"""
Defines the forward start date by tenor format: "Spot" / "1M" / ...
:return: str
"""
return self._get_parameter("forwardStartTenor")
@forward_start_tenor.setter
def forward_start_tenor(self, value):
self._set_parameter("forwardStartTenor", value)
@property
def index_tenor(self):
"""
:return: str
"""
return self._get_parameter("indexTenor")
@index_tenor.setter
def index_tenor(self, value):
self._set_parameter("indexTenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_forward_curve_definition.py | 0.913975 | 0.377655 | _forward_curve_definition.py | pypi |
from typing import TYPE_CHECKING
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStr, OptDateTime
class RequestItem(ObjectDefinition):
"""
Gets the Cross Currency curve definitions who can be used with provided criterias.
Parameters
----------
base_currency : str, optional
base_index_name : str, optional
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
quoted_currency : str, optional
quoted_index_name : str, optional
valuation_date : str or date or datetime or timedelta, optional
The date used to define a list of curves or a unique curve that can be priced
at this date. The value is expressed in ISO 8601 format: YYYY-MM-DD
"""
def __init__(
self,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
curve_tag: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
valuation_date: "OptDateTime" = None,
) -> None:
super().__init__()
self.base_currency = base_currency
self.base_index_name = base_index_name
self.curve_tag = curve_tag
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.valuation_date = valuation_date
@property
def base_currency(self):
"""
:return: str
"""
return self._get_parameter("baseCurrency")
@base_currency.setter
def base_currency(self, value):
self._set_parameter("baseCurrency", value)
@property
def base_index_name(self):
"""
:return: str
"""
return self._get_parameter("baseIndexName")
@base_index_name.setter
def base_index_name(self, value):
self._set_parameter("baseIndexName", value)
@property
def curve_tag(self):
"""
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
:return: str
"""
return self._get_parameter("curveTag")
@curve_tag.setter
def curve_tag(self, value):
self._set_parameter("curveTag", value)
@property
def quoted_currency(self):
"""
:return: str
"""
return self._get_parameter("quotedCurrency")
@quoted_currency.setter
def quoted_currency(self, value):
self._set_parameter("quotedCurrency", value)
@property
def quoted_index_name(self):
"""
:return: str
"""
return self._get_parameter("quotedIndexName")
@quoted_index_name.setter
def quoted_index_name(self, value):
self._set_parameter("quotedIndexName", value)
@property
def valuation_date(self):
"""
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_date_parameter("valuationDate", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_triangulate_definitions/_request.py | 0.951176 | 0.325614 | _request.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptStr, OptFloat
class ButterflyShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
pivot_tenor : str, optional
The code indicating the curve point which is not shifted (e.g., '1m', '6m',
'4y').
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
pivot_tenor: "OptStr" = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
self.pivot_tenor = pivot_tenor
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value)
@property
def pivot_tenor(self):
"""
The code indicating the curve point which is not shifted (e.g., '1m', '6m',
'4y').
:return: str
"""
return self._get_parameter("pivotTenor")
@pivot_tenor.setter
def pivot_tenor(self, value):
self._set_parameter("pivotTenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_butterfly_shift.py | 0.971497 | 0.641801 | _butterfly_shift.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptFloat, OptStr
class TimeBucketShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
end_tenor : str, optional
The code indicating the end tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
start_tenor : str, optional
The code indicating the start tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
end_tenor: "OptStr" = None,
start_tenor: "OptStr" = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
self.end_tenor = end_tenor
self.start_tenor = start_tenor
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value)
@property
def end_tenor(self):
"""
The code indicating the end tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
:return: str
"""
return self._get_parameter("endTenor")
@end_tenor.setter
def end_tenor(self, value):
self._set_parameter("endTenor", value)
@property
def start_tenor(self):
"""
The code indicating the start tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
:return: str
"""
return self._get_parameter("startTenor")
@start_tenor.setter
def start_tenor(self, value):
self._set_parameter("startTenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_time_bucket_shift.py | 0.964221 | 0.692843 | _time_bucket_shift.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptFloat
class ShortEndShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_short_end_shift.py | 0.969003 | 0.639694 | _short_end_shift.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptFloat, OptStr
class TwistShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
pivot_tenor : str, optional
The code indicating the curve point which is not shifted (e.g., '1m', '6m',
'4y').
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
pivot_tenor: "OptStr" = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
self.pivot_tenor = pivot_tenor
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value)
@property
def pivot_tenor(self):
"""
The code indicating the curve point which is not shifted (e.g., '1m', '6m',
'4y').
:return: str
"""
return self._get_parameter("pivotTenor")
@pivot_tenor.setter
def pivot_tenor(self, value):
self._set_parameter("pivotTenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_twist_shift.py | 0.971238 | 0.639004 | _twist_shift.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptFloat
class ParallelShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_parallel_shift.py | 0.969032 | 0.643735 | _parallel_shift.py | pypi |
from typing import Optional, List
from ._butterfly_shift import ButterflyShift
from ._combined_shift import CombinedShift
from ._flattening_shift import FlatteningShift
from ._long_end_shift import LongEndShift
from ._parallel_shift import ParallelShift
from ._short_end_shift import ShortEndShift
from ._time_bucket_shift import TimeBucketShift
from ._twist_shift import TwistShift
from ...._object_definition import ObjectDefinition
from ......_tools import try_copy_to_list
class ShiftDefinition(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
butterfly_shift : ButterflyShift, optional
The definition of attributes for butterfly shift scenario. the start and end
curve points are shifted by amount. the curve point at pivot tenor is not
shifted.
combined_shifts : list of CombinedShift, optional
The definition of attributes for combined shifts scenario. each element of the
combined shifts scenario describes separate shift scenario applied to curve
points. if one scenario follows the other, they are added to each other.
flattening_shift : FlatteningShift, optional
The definition of attributes for flattening / steepening shift scenario. the
start curve point is shifted by [amount / 2], the end curve point is shifted by
[-amount / 2].
long_end_shift : LongEndShift, optional
The definition of attributes for long end shift scenario. the end curve point is
shifted by amount. the start curve point is not shifted. the shift rises from 0
to amount between the start and the end curve point.
parallel_shift : ParallelShift, optional
The definition of attributes for parallel shift scenario. each curve point is
shifted by amount.
short_end_shift : ShortEndShift, optional
The definition of attributes for short end shift scenario. the start curve point
is shifted by amount. the end curve point is not shifted. the shift decreases
from 0 to amount between the start and the end curve point
time_bucket_shifts : list of TimeBucketShift, optional
The definition of attributes for time bucket shift scenario. each element of
timebucketshifts describes the separate parallel shift. this shift applies from
starttenor to endtenor.
twist_shift : TwistShift, optional
The definition of attributes for twist shift scenario. the start and end curve
points are shifted by amount. the curve point at pivot tenor is not shifted.
"""
def __init__(
self,
butterfly_shift: Optional[ButterflyShift] = None,
combined_shifts: Optional[List[CombinedShift]] = None,
flattening_shift: Optional[FlatteningShift] = None,
long_end_shift: Optional[LongEndShift] = None,
parallel_shift: Optional[ParallelShift] = None,
short_end_shift: Optional[ShortEndShift] = None,
time_bucket_shifts: Optional[List[TimeBucketShift]] = None,
twist_shift: Optional[TwistShift] = None,
) -> None:
super().__init__()
self.butterfly_shift = butterfly_shift
self.combined_shifts = try_copy_to_list(combined_shifts)
self.flattening_shift = flattening_shift
self.long_end_shift = long_end_shift
self.parallel_shift = parallel_shift
self.short_end_shift = short_end_shift
self.time_bucket_shifts = try_copy_to_list(time_bucket_shifts)
self.twist_shift = twist_shift
@property
def butterfly_shift(self):
"""
The definition of attributes for butterfly shift scenario. the start and end
curve points are shifted by amount. the curve point at pivot tenor is not
shifted.
:return: object ButterflyShift
"""
return self._get_object_parameter(ButterflyShift, "butterflyShift")
@butterfly_shift.setter
def butterfly_shift(self, value):
self._set_object_parameter(ButterflyShift, "butterflyShift", value)
@property
def combined_shifts(self):
"""
The definition of attributes for combined shifts scenario. each element of the
combined shifts scenario describes separate shift scenario applied to curve
points. if one scenario follows the other, they are added to each other.
:return: list CombinedShift
"""
return self._get_list_parameter(CombinedShift, "combinedShifts")
@combined_shifts.setter
def combined_shifts(self, value):
self._set_list_parameter(CombinedShift, "combinedShifts", value)
@property
def flattening_shift(self):
"""
The definition of attributes for flattening / steepening shift scenario. the
start curve point is shifted by [amount / 2], the end curve point is shifted by
[-amount / 2].
:return: object FlatteningShift
"""
return self._get_object_parameter(FlatteningShift, "flatteningShift")
@flattening_shift.setter
def flattening_shift(self, value):
self._set_object_parameter(FlatteningShift, "flatteningShift", value)
@property
def long_end_shift(self):
"""
The definition of attributes for long end shift scenario. the end curve point is
shifted by amount. the start curve point is not shifted. the shift rises from 0
to amount between the start and the end curve point.
:return: object LongEndShift
"""
return self._get_object_parameter(LongEndShift, "longEndShift")
@long_end_shift.setter
def long_end_shift(self, value):
self._set_object_parameter(LongEndShift, "longEndShift", value)
@property
def parallel_shift(self):
"""
The definition of attributes for parallel shift scenario. each curve point is
shifted by amount.
:return: object ParallelShift
"""
return self._get_object_parameter(ParallelShift, "parallelShift")
@parallel_shift.setter
def parallel_shift(self, value):
self._set_object_parameter(ParallelShift, "parallelShift", value)
@property
def short_end_shift(self):
"""
The definition of attributes for short end shift scenario. the start curve point
is shifted by amount. the end curve point is not shifted. the shift decreases
from 0 to amount between the start and the end curve point
:return: object ShortEndShift
"""
return self._get_object_parameter(ShortEndShift, "shortEndShift")
@short_end_shift.setter
def short_end_shift(self, value):
self._set_object_parameter(ShortEndShift, "shortEndShift", value)
@property
def time_bucket_shifts(self):
"""
The definition of attributes for time bucket shift scenario. each element of
timebucketshifts describes the separate parallel shift. this shift applies from
starttenor to endtenor.
:return: list TimeBucketShift
"""
return self._get_list_parameter(TimeBucketShift, "timeBucketShifts")
@time_bucket_shifts.setter
def time_bucket_shifts(self, value):
self._set_list_parameter(TimeBucketShift, "timeBucketShifts", value)
@property
def twist_shift(self):
"""
The definition of attributes for twist shift scenario. the start and end curve
points are shifted by amount. the curve point at pivot tenor is not shifted.
:return: object TwistShift
"""
return self._get_object_parameter(TwistShift, "twistShift")
@twist_shift.setter
def twist_shift(self, value):
self._set_object_parameter(TwistShift, "twistShift", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_shift_definition.py | 0.965503 | 0.425784 | _shift_definition.py | pypi |
from typing import Optional, TYPE_CHECKING
from .._enums import MainConstituentAssetClass, RiskType
from ...._object_definition import ObjectDefinition
from ._enums import ConstituentOverrideMode
if TYPE_CHECKING:
from ......_types import OptStr, OptBool
class CrossCurrencyCurveDefinitionPricing(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
constituent_override_mode : ConstituentOverrideMode, optional
A method to use the default constituents. the possible values are: *
replacedefinition: replace the default constituents by the user constituents
from the input request, * mergewithdefinition: merge the default constituents
and the user constituents from the input request, the default value is
'replacedefinition'. if the ignoreexistingdefinition is true, the
constituentoverridemode is set to replacedefinition.
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
id : str, optional
The identifier of the cross currency definitions.
ignore_existing_definition : bool, optional
An indicator whether default definitions are used to get curve parameters and
constituents. the possible values are: * true: default definitions are not
used (definitions and constituents must be set in the request), * false:
default definitions are used.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
"""
def __init__(
self,
constituent_override_mode: Optional[ConstituentOverrideMode] = None,
main_constituent_asset_class: Optional[MainConstituentAssetClass] = None,
risk_type: Optional[RiskType] = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
id: "OptStr" = None,
ignore_existing_definition: "OptBool" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
) -> None:
super().__init__()
self.constituent_override_mode = constituent_override_mode
self.main_constituent_asset_class = main_constituent_asset_class
self.risk_type = risk_type
self.base_currency = base_currency
self.base_index_name = base_index_name
self.id = id
self.ignore_existing_definition = ignore_existing_definition
self.is_non_deliverable = is_non_deliverable
self.name = name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.source = source
@property
def constituent_override_mode(self):
"""
A method to use the default constituents. the possible values are: *
replacedefinition: replace the default constituents by the user constituents
from the input request, * mergewithdefinition: merge the default constituents
and the user constituents from the input request, the default value is
'replacedefinition'. if the ignoreexistingdefinition is true, the
constituentoverridemode is set to replacedefinition.
:return: enum ConstituentOverrideMode
"""
return self._get_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode")
@constituent_override_mode.setter
def constituent_override_mode(self, value):
self._set_enum_parameter(ConstituentOverrideMode, "constituentOverrideMode", value)
@property
def main_constituent_asset_class(self):
"""
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
:return: enum MainConstituentAssetClass
"""
return self._get_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass")
@main_constituent_asset_class.setter
def main_constituent_asset_class(self, value):
self._set_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass", value)
@property
def risk_type(self):
"""
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
:return: enum RiskType
"""
return self._get_enum_parameter(RiskType, "riskType")
@risk_type.setter
def risk_type(self, value):
self._set_enum_parameter(RiskType, "riskType", value)
@property
def base_currency(self):
"""
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
:return: str
"""
return self._get_parameter("baseCurrency")
@base_currency.setter
def base_currency(self, value):
self._set_parameter("baseCurrency", value)
@property
def base_index_name(self):
"""
The name of the floating rate index (e.g., 'estr') applied to the base currency.
:return: str
"""
return self._get_parameter("baseIndexName")
@base_index_name.setter
def base_index_name(self, value):
self._set_parameter("baseIndexName", value)
@property
def id(self):
"""
The identifier of the cross currency definitions.
:return: str
"""
return self._get_parameter("id")
@id.setter
def id(self, value):
self._set_parameter("id", value)
@property
def ignore_existing_definition(self):
"""
An indicator whether default definitions are used to get curve parameters and
constituents. the possible values are: * true: default definitions are not
used (definitions and constituents must be set in the request), * false:
default definitions are used.
:return: bool
"""
return self._get_parameter("ignoreExistingDefinition")
@ignore_existing_definition.setter
def ignore_existing_definition(self, value):
self._set_parameter("ignoreExistingDefinition", value)
@property
def is_non_deliverable(self):
"""
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def name(self):
"""
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value)
@property
def quoted_currency(self):
"""
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
:return: str
"""
return self._get_parameter("quotedCurrency")
@quoted_currency.setter
def quoted_currency(self, value):
self._set_parameter("quotedCurrency", value)
@property
def quoted_index_name(self):
"""
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
:return: str
"""
return self._get_parameter("quotedIndexName")
@quoted_index_name.setter
def quoted_index_name(self, value):
self._set_parameter("quotedIndexName", value)
@property
def source(self):
"""
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_curve_definition_pricing.py | 0.936176 | 0.409929 | _curve_definition_pricing.py | pypi |
from typing import TYPE_CHECKING, Optional
from ._fx_forward_constituents import FxForwardConstituents
from ._fx_forward_curve_definition import FxForwardCurveDefinition
from ._fx_forward_curve_parameters import FxForwardCurveParameters
from ._fx_shift_scenario import FxShiftScenario
from ...._object_definition import ObjectDefinition
from ......_tools import try_copy_to_list
if TYPE_CHECKING:
from ......_types import OptStr
from ._types import CurveDefinition, CurveParameters, ShiftScenarios
class RequestItem(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
constituents : FxForwardConstituents, optional
curve_definition : FxForwardCurveDefinition, optional
curve_parameters : FxForwardCurveParameters, optional
shift_scenarios : list of FxShiftScenario, optional
The list of attributes applied to the curve shift scenarios.
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
"""
def __init__(
self,
constituents: Optional[FxForwardConstituents] = None,
curve_definition: "CurveDefinition" = None,
curve_parameters: "CurveParameters" = None,
shift_scenarios: "ShiftScenarios" = None,
curve_tag: "OptStr" = None,
) -> None:
super().__init__()
self.constituents = constituents
self.curve_definition = curve_definition
self.curve_parameters = curve_parameters
self.shift_scenarios = try_copy_to_list(shift_scenarios)
self.curve_tag = curve_tag
@property
def constituents(self):
"""
:return: object FxForwardConstituents
"""
return self._get_object_parameter(FxForwardConstituents, "constituents")
@constituents.setter
def constituents(self, value):
self._set_object_parameter(FxForwardConstituents, "constituents", value)
@property
def curve_definition(self):
"""
:return: object FxForwardCurveDefinition
"""
return self._get_object_parameter(FxForwardCurveDefinition, "curveDefinition")
@curve_definition.setter
def curve_definition(self, value):
self._set_object_parameter(FxForwardCurveDefinition, "curveDefinition", value)
@property
def curve_parameters(self):
"""
:return: object FxForwardCurveParameters
"""
return self._get_object_parameter(FxForwardCurveParameters, "curveParameters")
@curve_parameters.setter
def curve_parameters(self, value):
self._set_object_parameter(FxForwardCurveParameters, "curveParameters", value)
@property
def shift_scenarios(self):
"""
The list of attributes applied to the curve shift scenarios.
:return: list FxShiftScenario
"""
return self._get_list_parameter(FxShiftScenario, "shiftScenarios")
@shift_scenarios.setter
def shift_scenarios(self, value):
self._set_list_parameter(FxShiftScenario, "shiftScenarios", value)
@property
def curve_tag(self):
"""
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
:return: str
"""
return self._get_parameter("curveTag")
@curve_tag.setter
def curve_tag(self, value):
self._set_parameter("curveTag", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_request.py | 0.964288 | 0.201204 | _request.py | pypi |
from typing import Optional, TYPE_CHECKING
from ..._models import ValuationTime
from ...._enums._extrapolation_mode import ExtrapolationMode
from ...._enums._interpolation_mode import InterpolationMode
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptBool, OptDateTime
class FxForwardCurveParameters(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
extrapolation_mode : ExtrapolationMode, optional
interpolation_mode : InterpolationMode, optional
valuation_time : ValuationTime, optional
The time identified by offsets at which the zero coupon curve is generated.
ignore_invalid_instrument : bool, optional
Ignore invalid instrument to calculate the curve. if false and some instrument
are invlide, the curve is not calculated and an error is returned. the default
value is 'true'.
ignore_pivot_currency_holidays : bool, optional
use_delayed_data_if_denied : bool, optional
Use delayed ric to retrieve data when not permissioned on constituent ric. the
default value is 'false'.
valuation_date : str or date or datetime or timedelta, optional
valuation_date_time : str or date or datetime or timedelta, optional
The date and time at which the zero coupon curve is generated. the value is
expressed in iso 8601 format: yyyy-mm-ddt00:00:00z (e.g., '2021-01-01t14:00:00z'
or '2021-01-01t14:00:00+02:00'). only one parameter of valuationdate and
valuationdatetime must be specified.
"""
def __init__(
self,
extrapolation_mode: Optional[ExtrapolationMode] = None,
interpolation_mode: Optional[InterpolationMode] = None,
valuation_time: Optional[ValuationTime] = None,
ignore_invalid_instrument: "OptBool" = None,
ignore_pivot_currency_holidays: "OptBool" = None,
use_delayed_data_if_denied: "OptBool" = None,
valuation_date: "OptDateTime" = None,
valuation_date_time: "OptDateTime" = None,
) -> None:
super().__init__()
self.extrapolation_mode = extrapolation_mode
self.interpolation_mode = interpolation_mode
self.valuation_time = valuation_time
self.ignore_invalid_instrument = ignore_invalid_instrument
self.ignore_pivot_currency_holidays = ignore_pivot_currency_holidays
self.use_delayed_data_if_denied = use_delayed_data_if_denied
self.valuation_date = valuation_date
self.valuation_date_time = valuation_date_time
@property
def extrapolation_mode(self):
"""
:return: enum ExtrapolationMode
"""
return self._get_enum_parameter(ExtrapolationMode, "extrapolationMode")
@extrapolation_mode.setter
def extrapolation_mode(self, value):
self._set_enum_parameter(ExtrapolationMode, "extrapolationMode", value)
@property
def interpolation_mode(self):
"""
:return: enum InterpolationMode
"""
return self._get_enum_parameter(InterpolationMode, "interpolationMode")
@interpolation_mode.setter
def interpolation_mode(self, value):
self._set_enum_parameter(InterpolationMode, "interpolationMode", value)
@property
def valuation_time(self):
"""
The time identified by offsets at which the zero coupon curve is generated.
:return: object ValuationTime
"""
return self._get_object_parameter(ValuationTime, "valuationTime")
@valuation_time.setter
def valuation_time(self, value):
self._set_object_parameter(ValuationTime, "valuationTime", value)
@property
def ignore_invalid_instrument(self):
"""
Ignore invalid instrument to calculate the curve. if false and some instrument
are invlide, the curve is not calculated and an error is returned. the default
value is 'true'.
:return: bool
"""
return self._get_parameter("ignoreInvalidInstrument")
@ignore_invalid_instrument.setter
def ignore_invalid_instrument(self, value):
self._set_parameter("ignoreInvalidInstrument", value)
@property
def ignore_pivot_currency_holidays(self):
"""
:return: bool
"""
return self._get_parameter("ignorePivotCurrencyHolidays")
@ignore_pivot_currency_holidays.setter
def ignore_pivot_currency_holidays(self, value):
self._set_parameter("ignorePivotCurrencyHolidays", value)
@property
def use_delayed_data_if_denied(self):
"""
Use delayed ric to retrieve data when not permissioned on constituent ric. the
default value is 'false'.
:return: bool
"""
return self._get_parameter("useDelayedDataIfDenied")
@use_delayed_data_if_denied.setter
def use_delayed_data_if_denied(self, value):
self._set_parameter("useDelayedDataIfDenied", value)
@property
def valuation_date(self):
"""
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_date_parameter("valuationDate", value)
@property
def valuation_date_time(self):
"""
The date and time at which the zero coupon curve is generated. the value is
expressed in iso 8601 format: yyyy-mm-ddt00:00:00z (e.g., '2021-01-01t14:00:00z'
or '2021-01-01t14:00:00+02:00'). only one parameter of valuationdate and
valuationdatetime must be specified.
:return: str
"""
return self._get_parameter("valuationDateTime")
@valuation_date_time.setter
def valuation_date_time(self, value):
self._set_datetime_parameter("valuationDateTime", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_fx_forward_curve_parameters.py | 0.949482 | 0.364664 | _fx_forward_curve_parameters.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptFloat
class FlatteningShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_flattening_shift.py | 0.969281 | 0.648035 | _flattening_shift.py | pypi |
from typing import Optional, TYPE_CHECKING, List
from ._curve_definition_pricing import (
CrossCurrencyCurveDefinitionPricing,
)
from ..._zc_curve_definition import ZcCurveDefinition
from ...._object_definition import ObjectDefinition
from ......_tools import try_copy_to_list
if TYPE_CHECKING:
from ......_types import OptStr, OptBool, OptStrings
class FxForwardCurveDefinition(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
cross_currency_definitions : list of CrossCurrencyCurveDefinitionPricing, optional
curve_tenors : string, optional
List of user-defined curve tenors or dates to be computed.
interest_rate_curve_definitions : list of ZcCurveDefinition, optional
base_currency : str, optional
base_index_name : str, optional
is_non_deliverable : bool, optional
If true, non deliverable cross currency definition is used. default value is
false
pivot_currency : str, optional
pivot_index_name : str, optional
quoted_currency : str, optional
quoted_index_name : str, optional
"""
def __init__(
self,
cross_currency_definitions: Optional[List[CrossCurrencyCurveDefinitionPricing]] = None,
curve_tenors: "OptStrings" = None,
interest_rate_curve_definitions: Optional[List[ZcCurveDefinition]] = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
is_non_deliverable: "OptBool" = None,
pivot_currency: "OptStr" = None,
pivot_index_name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
) -> None:
super().__init__()
self.cross_currency_definitions = try_copy_to_list(cross_currency_definitions)
self.curve_tenors = curve_tenors
self.interest_rate_curve_definitions = try_copy_to_list(interest_rate_curve_definitions)
self.base_currency = base_currency
self.base_index_name = base_index_name
self.is_non_deliverable = is_non_deliverable
self.pivot_currency = pivot_currency
self.pivot_index_name = pivot_index_name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
@property
def cross_currency_definitions(self):
"""
:return: list CrossCurrencyCurveDefinitionPricing
"""
return self._get_list_parameter(CrossCurrencyCurveDefinitionPricing, "crossCurrencyDefinitions")
@cross_currency_definitions.setter
def cross_currency_definitions(self, value):
self._set_list_parameter(CrossCurrencyCurveDefinitionPricing, "crossCurrencyDefinitions", value)
@property
def curve_tenors(self):
"""
List of user-defined curve tenors or dates to be computed.
:return: list string
"""
return self._get_list_parameter(str, "curveTenors")
@curve_tenors.setter
def curve_tenors(self, value):
self._set_list_parameter(str, "curveTenors", value)
@property
def interest_rate_curve_definitions(self):
"""
:return: list ZcCurveDefinition
"""
return self._get_list_parameter(ZcCurveDefinition, "interestRateCurveDefinitions")
@interest_rate_curve_definitions.setter
def interest_rate_curve_definitions(self, value):
self._set_list_parameter(ZcCurveDefinition, "interestRateCurveDefinitions", value)
@property
def base_currency(self):
"""
:return: str
"""
return self._get_parameter("baseCurrency")
@base_currency.setter
def base_currency(self, value):
self._set_parameter("baseCurrency", value)
@property
def base_index_name(self):
"""
:return: str
"""
return self._get_parameter("baseIndexName")
@base_index_name.setter
def base_index_name(self, value):
self._set_parameter("baseIndexName", value)
@property
def is_non_deliverable(self):
"""
If true, non deliverable cross currency definition is used. default value is
false
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def pivot_currency(self):
"""
:return: str
"""
return self._get_parameter("pivotCurrency")
@pivot_currency.setter
def pivot_currency(self, value):
self._set_parameter("pivotCurrency", value)
@property
def pivot_index_name(self):
"""
:return: str
"""
return self._get_parameter("pivotIndexName")
@pivot_index_name.setter
def pivot_index_name(self, value):
self._set_parameter("pivotIndexName", value)
@property
def quoted_currency(self):
"""
:return: str
"""
return self._get_parameter("quotedCurrency")
@quoted_currency.setter
def quoted_currency(self, value):
self._set_parameter("quotedCurrency", value)
@property
def quoted_index_name(self):
"""
:return: str
"""
return self._get_parameter("quotedIndexName")
@quoted_index_name.setter
def quoted_index_name(self, value):
self._set_parameter("quotedIndexName", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_fx_forward_curve_definition.py | 0.959183 | 0.335582 | _fx_forward_curve_definition.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptStr, OptFloat
class CombinedShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
end_tenor : str, optional
The code indicating the end tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
start_tenor : str, optional
The code indicating the start tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
end_tenor: "OptStr" = None,
start_tenor: "OptStr" = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
self.end_tenor = end_tenor
self.start_tenor = start_tenor
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value)
@property
def end_tenor(self):
"""
The code indicating the end tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
:return: str
"""
return self._get_parameter("endTenor")
@end_tenor.setter
def end_tenor(self, value):
self._set_parameter("endTenor", value)
@property
def start_tenor(self):
"""
The code indicating the start tenor from which the combined shifts scenario is
applied to curve points. when starttenor equals endtenor: * shift equals 0 for
tenor less than starttenor, * shift equals amount for tenor is equal and
greater than endtenor. when starttenor less than endtenor: * shift equals 0
for tenor which is less or equal starttenor, * shift rises from 0 to amount in
period from starttenor to endtenor. shift equals amount for tenor greater than
endtenor.
:return: str
"""
return self._get_parameter("startTenor")
@start_tenor.setter
def start_tenor(self, value):
self._set_parameter("startTenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_combined_shift.py | 0.964372 | 0.694905 | _combined_shift.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import (
ShiftType,
ShiftUnit,
)
if TYPE_CHECKING:
from ......_types import OptFloat
class LongEndShift(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
amount : float, optional
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
shift_type : ShiftType, optional
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
shift_unit : ShiftUnit, optional
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
"""
def __init__(
self,
amount: "OptFloat" = None,
shift_type: Optional[ShiftType] = None,
shift_unit: Optional[ShiftUnit] = None,
) -> None:
super().__init__()
self.amount = amount
self.shift_type = shift_type
self.shift_unit = shift_unit
@property
def shift_type(self):
"""
The type of shifting. the possible values are: * additive: the amount of
shifting is added to the corresponding curve point, * relative: the curve
point is multiplied by the amount of shifting (e.g., if amount = 1, the curve
point value will be doubled), * relativepercent: the curve point is multiplied
by the amount expressed in percentages (e.g., if amount = 1, the curve point
value will multiplied by [1+1%]), * scaled: the curve point is scaled by the
value of the shifting amount (e.g., if amount = 1.1, the curve point value will
multiplied by this value).
:return: enum ShiftType
"""
return self._get_enum_parameter(ShiftType, "shiftType")
@shift_type.setter
def shift_type(self, value):
self._set_enum_parameter(ShiftType, "shiftType", value)
@property
def shift_unit(self):
"""
The unit that describes the amount of shifting. the possible values are: * bp:
the amount of shifting is expressed in basis points, * percent: the amount of
shifting is expressed in percentages, * absolute: the amount of shifting is
expressed in absolute value.
:return: enum ShiftUnit
"""
return self._get_enum_parameter(ShiftUnit, "shiftUnit")
@shift_unit.setter
def shift_unit(self, value):
self._set_enum_parameter(ShiftUnit, "shiftUnit", value)
@property
def amount(self):
"""
Amount of shifting, applied to points depending on shift method selected.<br/>
can be measured in basis points/percents/future price based points.<br/> also
can be expressed as multiplier for relative shift type.<br/>
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_long_end_shift.py | 0.969003 | 0.640341 | _long_end_shift.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._shift_definition import ShiftDefinition
from ..._models import ParRateShift
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStr
class FxShiftScenario(ObjectDefinition):
"""
Generates the Cross Currency curves for the definitions provided
Parameters
----------
fx_curve_shift : ShiftDefinition, optional
Collection of shift parameters tenor. "all" selector supported as well.
par_rate_shift : ParRateShift, optional
Scenario of par rates shift (shift applied to constituents).
shift_tag : str, optional
User defined string to identify the shift scenario tag. it can be used to link
output curve to the shift scenario. only alphabetic, numeric and '- _.#=@'
characters are supported. optional.
"""
def __init__(
self,
fx_curve_shift: Optional[ShiftDefinition] = None,
par_rate_shift: Optional[ParRateShift] = None,
shift_tag: "OptStr" = None,
) -> None:
super().__init__()
self.fx_curve_shift = fx_curve_shift
self.par_rate_shift = par_rate_shift
self.shift_tag = shift_tag
@property
def fx_curve_shift(self):
"""
Collection of shift parameters tenor. "all" selector supported as well.
:return: object ShiftDefinition
"""
return self._get_object_parameter(ShiftDefinition, "fxCurveShift")
@fx_curve_shift.setter
def fx_curve_shift(self, value):
self._set_object_parameter(ShiftDefinition, "fxCurveShift", value)
@property
def par_rate_shift(self):
"""
Scenario of par rates shift (shift applied to constituents).
:return: object ParRateShift
"""
return self._get_object_parameter(ParRateShift, "parRateShift")
@par_rate_shift.setter
def par_rate_shift(self, value):
self._set_object_parameter(ParRateShift, "parRateShift", value)
@property
def shift_tag(self):
"""
User defined string to identify the shift scenario tag. it can be used to link
output curve to the shift scenario. only alphabetic, numeric and '- _.#=@'
characters are supported. optional.
:return: str
"""
return self._get_parameter("shiftTag")
@shift_tag.setter
def shift_tag(self, value):
self._set_parameter("shiftTag", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_curves/_fx_shift_scenario.py | 0.960268 | 0.279245 | _fx_shift_scenario.py | pypi |
from typing import Optional, TYPE_CHECKING, List
from ._bid_ask_fields_description import BidAskFieldsDescription
from ._formula_parameter_description import FormulaParameterDescription
from ._fx_spot_instrument_definition import FxSpotInstrumentDefinition
from ...._object_definition import ObjectDefinition
from ......_tools import try_copy_to_list
if TYPE_CHECKING:
from ......_types import OptStr
class FxSpotInstrumentDescription(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
fields : BidAskFieldsDescription, optional
formula_parameters : list of FormulaParameterDescription, optional
instrument_definition : FxSpotInstrumentDefinition, optional
formula : str, optional
"""
def __init__(
self,
fields: Optional[BidAskFieldsDescription] = None,
formula_parameters: Optional[List[FormulaParameterDescription]] = None,
instrument_definition: Optional[FxSpotInstrumentDefinition] = None,
formula: "OptStr" = None,
) -> None:
super().__init__()
self.fields = fields
self.formula_parameters = try_copy_to_list(formula_parameters)
self.instrument_definition = instrument_definition
self.formula = formula
@property
def fields(self):
"""
:return: object BidAskFieldsDescription
"""
return self._get_object_parameter(BidAskFieldsDescription, "fields")
@fields.setter
def fields(self, value):
self._set_object_parameter(BidAskFieldsDescription, "fields", value)
@property
def formula_parameters(self):
"""
:return: list FormulaParameterDescription
"""
return self._get_list_parameter(FormulaParameterDescription, "formulaParameters")
@formula_parameters.setter
def formula_parameters(self, value):
self._set_list_parameter(FormulaParameterDescription, "formulaParameters", value)
@property
def instrument_definition(self):
"""
:return: object FxSpotInstrumentDefinition
"""
return self._get_object_parameter(FxSpotInstrumentDefinition, "instrumentDefinition")
@instrument_definition.setter
def instrument_definition(self, value):
self._set_object_parameter(FxSpotInstrumentDefinition, "instrumentDefinition", value)
@property
def formula(self):
"""
:return: str
"""
return self._get_parameter("formula")
@formula.setter
def formula(self, value):
self._set_parameter("formula", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_fx_spot_instrument_description.py | 0.938548 | 0.295433 | _fx_spot_instrument_description.py | pypi |
from typing import Optional, List
from ......_tools import try_copy_to_list
from ._instrument_description import CrossCurrencyInstrumentDescription
from ._fx_forward_instrument_description import FxForwardInstrumentDescription
from ._fx_spot_instrument_description import FxSpotInstrumentDescription
from ...._object_definition import ObjectDefinition
class CrossCurrencyConstituentsDescription(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
cross_currency_swaps : list of CrossCurrencyInstrumentDescription, optional
fx_forwards : list of FxForwardInstrumentDescription, optional
fx_spot : FxSpotInstrumentDescription, optional
interest_rate_swaps : list of CrossCurrencyInstrumentDescription, optional
overnight_index_swaps : list of CrossCurrencyInstrumentDescription, optional
"""
def __init__(
self,
cross_currency_swaps: Optional[List[CrossCurrencyInstrumentDescription]] = None,
fx_forwards: Optional[List[FxForwardInstrumentDescription]] = None,
fx_spot: Optional[FxSpotInstrumentDescription] = None,
interest_rate_swaps: Optional[List[CrossCurrencyInstrumentDescription]] = None,
overnight_index_swaps: Optional[List[CrossCurrencyInstrumentDescription]] = None,
) -> None:
super().__init__()
self.cross_currency_swaps = try_copy_to_list(cross_currency_swaps)
self.fx_forwards = try_copy_to_list(fx_forwards)
self.fx_spot = fx_spot
self.interest_rate_swaps = try_copy_to_list(interest_rate_swaps)
self.overnight_index_swaps = try_copy_to_list(overnight_index_swaps)
@property
def cross_currency_swaps(self):
"""
:return: list CrossCurrencyInstrumentDescription
"""
return self._get_list_parameter(CrossCurrencyInstrumentDescription, "crossCurrencySwaps")
@cross_currency_swaps.setter
def cross_currency_swaps(self, value):
self._set_list_parameter(CrossCurrencyInstrumentDescription, "crossCurrencySwaps", value)
@property
def fx_forwards(self):
"""
:return: list FxForwardInstrumentDescription
"""
return self._get_list_parameter(FxForwardInstrumentDescription, "fxForwards")
@fx_forwards.setter
def fx_forwards(self, value):
self._set_list_parameter(FxForwardInstrumentDescription, "fxForwards", value)
@property
def fx_spot(self):
"""
:return: object FxSpotInstrumentDescription
"""
return self._get_object_parameter(FxSpotInstrumentDescription, "fxSpot")
@fx_spot.setter
def fx_spot(self, value):
self._set_object_parameter(FxSpotInstrumentDescription, "fxSpot", value)
@property
def interest_rate_swaps(self):
"""
:return: list CrossCurrencyInstrumentDescription
"""
return self._get_list_parameter(CrossCurrencyInstrumentDescription, "interestRateSwaps")
@interest_rate_swaps.setter
def interest_rate_swaps(self, value):
self._set_list_parameter(CrossCurrencyInstrumentDescription, "interestRateSwaps", value)
@property
def overnight_index_swaps(self):
"""
:return: list CrossCurrencyInstrumentDescription
"""
return self._get_list_parameter(CrossCurrencyInstrumentDescription, "overnightIndexSwaps")
@overnight_index_swaps.setter
def overnight_index_swaps(self, value):
self._set_list_parameter(CrossCurrencyInstrumentDescription, "overnightIndexSwaps", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_constituents_description.py | 0.949295 | 0.380788 | _constituents_description.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._bid_ask_fields_formula_description import BidAskFieldsFormulaDescription
from ..._enums import InstrumentType
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStr
class FormulaParameterDescription(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
instrument_type : InstrumentType, optional
instrument_code : str, optional
fields : BidAskFieldsFormulaDescription, optional
name : str, optional
"""
def __init__(
self,
instrument_type: Optional[InstrumentType] = None,
instrument_code: "OptStr" = None,
fields: Optional[BidAskFieldsFormulaDescription] = None,
name: "OptStr" = None,
) -> None:
super().__init__()
self.instrument_type = instrument_type
self.instrument_code = instrument_code
self.fields = fields
self.name = name
@property
def fields(self):
"""
:return: object BidAskFieldsFormulaDescription
"""
return self._get_object_parameter(BidAskFieldsFormulaDescription, "fields")
@fields.setter
def fields(self, value):
self._set_object_parameter(BidAskFieldsFormulaDescription, "fields", value)
@property
def instrument_type(self):
"""
:return: enum InstrumentType
"""
return self._get_enum_parameter(InstrumentType, "instrumentType")
@instrument_type.setter
def instrument_type(self, value):
self._set_enum_parameter(InstrumentType, "instrumentType", value)
@property
def instrument_code(self):
"""
:return: str
"""
return self._get_parameter("instrumentCode")
@instrument_code.setter
def instrument_code(self, value):
self._set_parameter("instrumentCode", value)
@property
def name(self):
"""
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_formula_parameter_description.py | 0.93196 | 0.300848 | _formula_parameter_description.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._constituents_description import (
CrossCurrencyConstituentsDescription,
)
from ._curve_parameters import CrossCurrencyCurveParameters
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptDateTime
class CrossCurrencyInstrumentsSegment(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
start_date : str or date or datetime or timedelta, optional
constituents : CrossCurrencyConstituentsDescription, optional
curve_parameters : CrossCurrencyCurveParameters, optional
"""
def __init__(
self,
start_date: "OptDateTime" = None,
constituents: Optional[CrossCurrencyConstituentsDescription] = None,
curve_parameters: Optional[CrossCurrencyCurveParameters] = None,
) -> None:
super().__init__()
self.start_date = start_date
self.constituents = constituents
self.curve_parameters = curve_parameters
@property
def constituents(self):
"""
:return: object CrossCurrencyConstituentsDescription
"""
return self._get_object_parameter(CrossCurrencyConstituentsDescription, "constituents")
@constituents.setter
def constituents(self, value):
self._set_object_parameter(CrossCurrencyConstituentsDescription, "constituents", value)
@property
def curve_parameters(self):
"""
:return: object CrossCurrencyCurveParameters
"""
return self._get_object_parameter(CrossCurrencyCurveParameters, "curveParameters")
@curve_parameters.setter
def curve_parameters(self, value):
self._set_object_parameter(CrossCurrencyCurveParameters, "curveParameters", value)
@property
def start_date(self):
"""
:return: str
"""
return self._get_parameter("startDate")
@start_date.setter
def start_date(self, value):
self._set_datetime_parameter("startDate", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_instruments_segment.py | 0.958128 | 0.292431 | _instruments_segment.py | pypi |
from typing import TYPE_CHECKING
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStr, OptBool
class CrossCurrencyInstrumentDefinition(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
instrument_code : str, optional
The code used to define the instrument.
tenor : str, optional
The code indicating the instrument tenor (e.g., '6m', '1y').
is_non_deliverable : bool, optional
True if the instrument is non deliverable
synthetic_instrument_code : str, optional
The code used to define the formula.
template : str, optional
A reference to a style used to define the instrument.
"""
def __init__(
self,
instrument_code: "OptStr" = None,
tenor: "OptStr" = None,
is_non_deliverable: "OptBool" = None,
synthetic_instrument_code: "OptStr" = None,
template: "OptStr" = None,
) -> None:
super().__init__()
self.instrument_code = instrument_code
self.tenor = tenor
self.is_non_deliverable = is_non_deliverable
self.synthetic_instrument_code = synthetic_instrument_code
self.template = template
@property
def instrument_code(self):
"""
The code used to define the instrument.
:return: str
"""
return self._get_parameter("instrumentCode")
@instrument_code.setter
def instrument_code(self, value):
self._set_parameter("instrumentCode", value)
@property
def is_non_deliverable(self):
"""
True if the instrument is non deliverable
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def synthetic_instrument_code(self):
"""
The code used to define the formula.
:return: str
"""
return self._get_parameter("syntheticInstrumentCode")
@synthetic_instrument_code.setter
def synthetic_instrument_code(self, value):
self._set_parameter("syntheticInstrumentCode", value)
@property
def template(self):
"""
A reference to a style used to define the instrument.
:return: str
"""
return self._get_parameter("template")
@template.setter
def template(self, value):
self._set_parameter("template", value)
@property
def tenor(self):
"""
The code indicating the instrument tenor (e.g., '6m', '1y').
:return: str
"""
return self._get_parameter("tenor")
@tenor.setter
def tenor(self, value):
self._set_parameter("tenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_instrument_definition.py | 0.946769 | 0.55917 | _instrument_definition.py | pypi |
from typing import Optional, TYPE_CHECKING
from ...._object_definition import ObjectDefinition
from ._enums import QuotationMode
if TYPE_CHECKING:
from ......_types import OptStr, OptBool
class FxForwardInstrumentDefinition(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
instrument_code : str, optional
The code used to define the instrument.
tenor : str, optional
The code indicating the instrument tenor (e.g., '6m', '1y').
quotation_mode : QuotationMode, optional
The quotation defining the price type of the instrument. the possible values
are: * swappoint * outright
is_non_deliverable : bool, optional
True if the instrument is non deliverable
synthetic_instrument_code : str, optional
The code used to define the formula.
template : str, optional
A reference to a style used to define the instrument.
"""
def __init__(
self,
instrument_code: "OptStr" = None,
tenor: "OptStr" = None,
quotation_mode: Optional[QuotationMode] = None,
is_non_deliverable: "OptBool" = None,
synthetic_instrument_code: "OptStr" = None,
template: "OptStr" = None,
) -> None:
super().__init__()
self.instrument_code = instrument_code
self.tenor = tenor
self.quotation_mode = quotation_mode
self.is_non_deliverable = is_non_deliverable
self.synthetic_instrument_code = synthetic_instrument_code
self.template = template
@property
def quotation_mode(self):
"""
The quotation defining the price type of the instrument. the possible values
are: * swappoint * outright
:return: enum QuotationMode
"""
return self._get_enum_parameter(QuotationMode, "quotationMode")
@quotation_mode.setter
def quotation_mode(self, value):
self._set_enum_parameter(QuotationMode, "quotationMode", value)
@property
def instrument_code(self):
"""
The code used to define the instrument.
:return: str
"""
return self._get_parameter("instrumentCode")
@instrument_code.setter
def instrument_code(self, value):
self._set_parameter("instrumentCode", value)
@property
def is_non_deliverable(self):
"""
True if the instrument is non deliverable
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def synthetic_instrument_code(self):
"""
The code used to define the formula.
:return: str
"""
return self._get_parameter("syntheticInstrumentCode")
@synthetic_instrument_code.setter
def synthetic_instrument_code(self, value):
self._set_parameter("syntheticInstrumentCode", value)
@property
def template(self):
"""
A reference to a style used to define the instrument.
:return: str
"""
return self._get_parameter("template")
@template.setter
def template(self, value):
self._set_parameter("template", value)
@property
def tenor(self):
"""
The code indicating the instrument tenor (e.g., '6m', '1y').
:return: str
"""
return self._get_parameter("tenor")
@tenor.setter
def tenor(self, value):
self._set_parameter("tenor", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_fx_forward_instrument_definition.py | 0.949867 | 0.552178 | _fx_forward_instrument_definition.py | pypi |
from typing import TYPE_CHECKING
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStrings, OptStr
class FieldFormulaDescription(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
historical_fid_priority : string, optional
The list of historical fid (field identifier) name used to get the market data.
real_time_fid_priority : string, optional
The list of real-time fid (field identifier) name used to get the market data.
formula : str, optional
The formula name used to adjust the market data value.
"""
def __init__(
self,
historical_fid_priority: "OptStrings" = None,
real_time_fid_priority: "OptStrings" = None,
formula: "OptStr" = None,
) -> None:
super().__init__()
self.historical_fid_priority = historical_fid_priority
self.real_time_fid_priority = real_time_fid_priority
self.formula = formula
@property
def historical_fid_priority(self):
"""
The list of historical fid (field identifier) name used to get the market data.
:return: list string
"""
return self._get_list_parameter(str, "historicalFidPriority")
@historical_fid_priority.setter
def historical_fid_priority(self, value):
self._set_list_parameter(str, "historicalFidPriority", value)
@property
def real_time_fid_priority(self):
"""
The list of real-time fid (field identifier) name used to get the market data.
:return: list string
"""
return self._get_list_parameter(str, "realTimeFidPriority")
@real_time_fid_priority.setter
def real_time_fid_priority(self, value):
self._set_list_parameter(str, "realTimeFidPriority", value)
@property
def formula(self):
"""
The formula name used to adjust the market data value.
:return: str
"""
return self._get_parameter("formula")
@formula.setter
def formula(self, value):
self._set_parameter("formula", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_field_formula_description.py | 0.927091 | 0.280713 | _field_formula_description.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._fx_forward_turn_fields import FxForwardTurnFields
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStr, OptDateTime
class OverrideFxForwardTurn(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
start_date : str or date or datetime or timedelta, optional
end_date : str or date or datetime or timedelta, optional
fields : FxForwardTurnFields, optional
date : "OptDateTime"
turn_tag : str, optional
"""
def __init__(
self,
start_date: "OptDateTime" = None,
end_date: "OptDateTime" = None,
fields: Optional[FxForwardTurnFields] = None,
date: "OptDateTime" = None,
turn_tag: "OptStr" = None,
) -> None:
super().__init__()
self.start_date = start_date
self.end_date = end_date
self.fields = fields
self.date = date
self.turn_tag = turn_tag
@property
def fields(self):
"""
:return: object FxForwardTurnFields
"""
return self._get_object_parameter(FxForwardTurnFields, "fields")
@fields.setter
def fields(self, value):
self._set_object_parameter(FxForwardTurnFields, "fields", value)
@property
def date(self):
"""
:return: str
"""
return self._get_parameter("date")
@date.setter
def date(self, value):
self._set_date_parameter("date", value)
@property
def end_date(self):
"""
:return: str
"""
return self._get_parameter("endDate")
@end_date.setter
def end_date(self, value):
self._set_date_parameter("endDate", value)
@property
def start_date(self):
"""
:return: str
"""
return self._get_parameter("startDate")
@start_date.setter
def start_date(self, value):
self._set_date_parameter("startDate", value)
@property
def turn_tag(self):
"""
:return: str
"""
return self._get_parameter("turnTag")
@turn_tag.setter
def turn_tag(self, value):
self._set_parameter("turnTag", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_override_fx_forward_turn.py | 0.95193 | 0.21213 | _override_fx_forward_turn.py | pypi |
from typing import Optional, TYPE_CHECKING, List
from ._bid_ask_fields_description import BidAskFieldsDescription
from ._instrument_definition import CrossCurrencyInstrumentDefinition
from ._formula_parameter_description import FormulaParameterDescription
from ...._object_definition import ObjectDefinition
from ......_tools import try_copy_to_list
if TYPE_CHECKING:
from ......_types import OptStr
class CrossCurrencyInstrumentDescription(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
fields : BidAskFieldsDescription, optional
formula_parameters : list of FormulaParameterDescription, optional
instrument_definition : CrossCurrencyInstrumentDefinition, optional
formula : str, optional
"""
def __init__(
self,
fields: Optional[BidAskFieldsDescription] = None,
formula_parameters: Optional[List[FormulaParameterDescription]] = None,
instrument_definition: Optional[CrossCurrencyInstrumentDefinition] = None,
formula: "OptStr" = None,
) -> None:
super().__init__()
self.fields = fields
self.formula_parameters = try_copy_to_list(formula_parameters)
self.instrument_definition = instrument_definition
self.formula = formula
@property
def fields(self):
"""
:return: object BidAskFieldsDescription
"""
return self._get_object_parameter(BidAskFieldsDescription, "fields")
@fields.setter
def fields(self, value):
self._set_object_parameter(BidAskFieldsDescription, "fields", value)
@property
def formula_parameters(self):
"""
:return: list FormulaParameterDescription
"""
return self._get_list_parameter(FormulaParameterDescription, "formulaParameters")
@formula_parameters.setter
def formula_parameters(self, value):
self._set_list_parameter(FormulaParameterDescription, "formulaParameters", value)
@property
def instrument_definition(self):
"""
:return: object CrossCurrencyInstrumentDefinition
"""
return self._get_object_parameter(CrossCurrencyInstrumentDefinition, "instrumentDefinition")
@instrument_definition.setter
def instrument_definition(self, value):
self._set_object_parameter(CrossCurrencyInstrumentDefinition, "instrumentDefinition", value)
@property
def formula(self):
"""
:return: str
"""
return self._get_parameter("formula")
@formula.setter
def formula(self, value):
self._set_parameter("formula", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_instrument_description.py | 0.9462 | 0.354182 | _instrument_description.py | pypi |
from typing import Optional, TYPE_CHECKING
from ._bid_ask_fields_description import BidAskFieldsDescription
from ._formula_parameter_description import FormulaParameterDescription
from ._fx_forward_instrument_definition import FxForwardInstrumentDefinition
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStr
class FxForwardInstrumentDescription(ObjectDefinition):
"""
Creates the Cross Currency curve definition with the definition provided.
Parameters
----------
fields : BidAskFieldsDescription, optional
formula_parameters : FormulaParameterDescription, optional
instrument_definition : FxForwardInstrumentDefinition, optional
formula : str, optional
"""
def __init__(
self,
fields: Optional[BidAskFieldsDescription] = None,
formula_parameters: Optional[FormulaParameterDescription] = None,
instrument_definition: Optional[FxForwardInstrumentDefinition] = None,
formula: "OptStr" = None,
) -> None:
super().__init__()
self.fields = fields
self.formula_parameters = formula_parameters
self.instrument_definition = instrument_definition
self.formula = formula
@property
def fields(self):
"""
:return: object BidAskFieldsDescription
"""
return self._get_object_parameter(BidAskFieldsDescription, "fields")
@fields.setter
def fields(self, value):
self._set_object_parameter(BidAskFieldsDescription, "fields", value)
@property
def formula_parameters(self):
"""
:return: list FormulaParameterDescription
"""
return self._get_list_parameter(FormulaParameterDescription, "formulaParameters")
@formula_parameters.setter
def formula_parameters(self, value):
self._set_list_parameter(FormulaParameterDescription, "formulaParameters", value)
@property
def instrument_definition(self):
"""
:return: object FxForwardInstrumentDefinition
"""
return self._get_object_parameter(FxForwardInstrumentDefinition, "instrumentDefinition")
@instrument_definition.setter
def instrument_definition(self, value):
self._set_object_parameter(FxForwardInstrumentDefinition, "instrumentDefinition", value)
@property
def formula(self):
"""
:return: str
"""
return self._get_parameter("formula")
@formula.setter
def formula(self, value):
self._set_parameter("formula", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_fx_forward_instrument_description.py | 0.943034 | 0.298958 | _fx_forward_instrument_description.py | pypi |
from typing import TYPE_CHECKING
from ..._enums import MainConstituentAssetClass, RiskType
from ....._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ..._types import OptMainConstituentAssetClass, OptRiskType
from ......._types import OptStr, OptBool
class CrossCurrencyCurveDefinitionKeys(ObjectDefinition):
"""
Get a Commodity & Energy curve definition
Parameters
----------
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
id : str, optional
The identifier of the cross currency definitions.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
"""
def __init__(
self,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
id: "OptStr" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
) -> None:
super().__init__()
self.main_constituent_asset_class = main_constituent_asset_class
self.risk_type = risk_type
self.base_currency = base_currency
self.base_index_name = base_index_name
self.id = id
self.is_non_deliverable = is_non_deliverable
self.name = name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.source = source
@property
def main_constituent_asset_class(self):
"""
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
:return: enum MainConstituentAssetClass
"""
return self._get_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass")
@main_constituent_asset_class.setter
def main_constituent_asset_class(self, value):
self._set_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass", value)
@property
def risk_type(self):
"""
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
:return: enum RiskType
"""
return self._get_enum_parameter(RiskType, "riskType")
@risk_type.setter
def risk_type(self, value):
self._set_enum_parameter(RiskType, "riskType", value)
@property
def base_currency(self):
"""
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
:return: str
"""
return self._get_parameter("baseCurrency")
@base_currency.setter
def base_currency(self, value):
self._set_parameter("baseCurrency", value)
@property
def base_index_name(self):
"""
The name of the floating rate index (e.g., 'estr') applied to the base currency.
:return: str
"""
return self._get_parameter("baseIndexName")
@base_index_name.setter
def base_index_name(self, value):
self._set_parameter("baseIndexName", value)
@property
def id(self):
"""
The identifier of the cross currency definitions.
:return: str
"""
return self._get_parameter("id")
@id.setter
def id(self, value):
self._set_parameter("id", value)
@property
def is_non_deliverable(self):
"""
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def name(self):
"""
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value)
@property
def quoted_currency(self):
"""
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
:return: str
"""
return self._get_parameter("quotedCurrency")
@quoted_currency.setter
def quoted_currency(self, value):
self._set_parameter("quotedCurrency", value)
@property
def quoted_index_name(self):
"""
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
:return: str
"""
return self._get_parameter("quotedIndexName")
@quoted_index_name.setter
def quoted_index_name(self, value):
self._set_parameter("quotedIndexName", value)
@property
def source(self):
"""
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_get/_curve_definition_keys.py | 0.924257 | 0.396944 | _curve_definition_keys.py | pypi |
from typing import TYPE_CHECKING
from ....._object_definition import ObjectDefinition
from ..._enums import MainConstituentAssetClass, RiskType
if TYPE_CHECKING:
from ..._types import OptMainConstituentAssetClass, OptRiskType
from ......._types import OptStr, OptBool, OptDateTime
class CrossCurrencyCurveGetDefinitionItem(ObjectDefinition):
"""
Returns the definitions of the available commodity and energy forward curves for
the filters selected (e.g. currency, source…).
Parameters
----------
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
id : str, optional
The identifier of the cross currency definitions.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
valuation_date : str or date or datetime or timedelta, optional
The date used to define a list of curves or a unique cross currency curve that
can be priced at this date. the value is expressed in iso 8601 format:
yyyy-mm-dd (e.g., '2021-01-01').
"""
def __init__(
self,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
curve_tag: "OptStr" = None,
id: "OptStr" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
valuation_date: "OptDateTime" = None,
) -> None:
super().__init__()
self.main_constituent_asset_class = main_constituent_asset_class
self.risk_type = risk_type
self.base_currency = base_currency
self.base_index_name = base_index_name
self.curve_tag = curve_tag
self.id = id
self.is_non_deliverable = is_non_deliverable
self.name = name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.source = source
self.valuation_date = valuation_date
@property
def main_constituent_asset_class(self):
"""
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
:return: enum MainConstituentAssetClass
"""
return self._get_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass")
@main_constituent_asset_class.setter
def main_constituent_asset_class(self, value):
self._set_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass", value)
@property
def risk_type(self):
"""
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
:return: enum RiskType
"""
return self._get_enum_parameter(RiskType, "riskType")
@risk_type.setter
def risk_type(self, value):
self._set_enum_parameter(RiskType, "riskType", value)
@property
def base_currency(self):
"""
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
:return: str
"""
return self._get_parameter("baseCurrency")
@base_currency.setter
def base_currency(self, value):
self._set_parameter("baseCurrency", value)
@property
def base_index_name(self):
"""
The name of the floating rate index (e.g., 'estr') applied to the base currency.
:return: str
"""
return self._get_parameter("baseIndexName")
@base_index_name.setter
def base_index_name(self, value):
self._set_parameter("baseIndexName", value)
@property
def curve_tag(self):
"""
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
:return: str
"""
return self._get_parameter("curveTag")
@curve_tag.setter
def curve_tag(self, value):
self._set_parameter("curveTag", value)
@property
def id(self):
"""
The identifier of the cross currency definitions.
:return: str
"""
return self._get_parameter("id")
@id.setter
def id(self, value):
self._set_parameter("id", value)
@property
def is_non_deliverable(self):
"""
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
:return: bool
"""
return self._get_parameter("isNonDeliverable")
@is_non_deliverable.setter
def is_non_deliverable(self, value):
self._set_parameter("isNonDeliverable", value)
@property
def name(self):
"""
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value)
@property
def quoted_currency(self):
"""
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
:return: str
"""
return self._get_parameter("quotedCurrency")
@quoted_currency.setter
def quoted_currency(self, value):
self._set_parameter("quotedCurrency", value)
@property
def quoted_index_name(self):
"""
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
:return: str
"""
return self._get_parameter("quotedIndexName")
@quoted_index_name.setter
def quoted_index_name(self, value):
self._set_parameter("quotedIndexName", value)
@property
def source(self):
"""
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value)
@property
def valuation_date(self):
"""
The date used to define a list of curves or a unique cross currency curve that
can be priced at this date. the value is expressed in iso 8601 format:
yyyy-mm-dd (e.g., '2021-01-01').
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_date_parameter("valuationDate", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_search/_curve_get_definition_item.py | 0.929999 | 0.476945 | _curve_get_definition_item.py | pypi |
from typing import TYPE_CHECKING
from .._base_definition_mixin import BaseDefinitionMixin
if TYPE_CHECKING:
from ..._types import OptMainConstituentAssetClass, OptRiskType
from ......._types import OptStr, OptBool, OptDateTime
class CrossCurrencyCurveCreateDefinition(BaseDefinitionMixin):
"""
Create a cross currency curve definition
Parameters
----------
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
definition_expiry_date : str or date or datetime or timedelta, optional
The date after which curvedefinitions can not be used. the value is expressed in
iso 8601 format: yyyy-mm-dd (e.g., '2021-01-01').
is_fallback_for_fx_curve_definition : bool, optional
The indicator used to define the fallback logic for the fx curve definition. the
possible values are: * true: there's a fallback logic to use cross currency
curve definition for fx curve definition, * false: there's no fallback logic
to use cross currency curve definition for fx curve definition.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
"""
def __init__(
self,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
definition_expiry_date: "OptDateTime" = None,
is_fallback_for_fx_curve_definition: "OptBool" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
) -> None:
super().__init__()
self.main_constituent_asset_class = main_constituent_asset_class
self.risk_type = risk_type
self.base_currency = base_currency
self.base_index_name = base_index_name
self.definition_expiry_date = definition_expiry_date
self.is_fallback_for_fx_curve_definition = is_fallback_for_fx_curve_definition
self.is_non_deliverable = is_non_deliverable
self.name = name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.source = source | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_create/_curve_definition_description.py | 0.946436 | 0.488283 | _curve_definition_description.py | pypi |
from typing import TYPE_CHECKING
from .._base_definition_mixin import BaseWithIdDefinitionMixin
if TYPE_CHECKING:
from ..._types import OptMainConstituentAssetClass, OptRiskType
from ......._types import OptStr, OptBool, OptDateTime
class CrossCurrencyCurveUpdateDefinition(BaseWithIdDefinitionMixin):
"""
Update an existing cross currency curve definition
Parameters
----------
id : str
The identifier of the cross currency definition.
main_constituent_asset_class : MainConstituentAssetClass, optional
The asset class used to generate the zero coupon curve. the possible values are:
* fxforward * swap
risk_type : RiskType, optional
The risk type to which the generated cross currency curve is sensitive. the
possible value is: * 'crosscurrency'
base_currency : str, optional
The base currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'eur').
base_index_name : str, optional
The name of the floating rate index (e.g., 'estr') applied to the base currency.
definition_expiry_date : str or date or datetime or timedelta, optional
The date after which curvedefinitions can not be used. the value is expressed in
iso 8601 format: yyyy-mm-dd (e.g., '2021-01-01').
is_fallback_for_fx_curve_definition : bool, optional
The indicator used to define the fallback logic for the fx curve definition. the
possible values are: * true: there's a fallback logic to use cross currency
curve definition for fx curve definition, * false: there's no fallback logic
to use cross currency curve definition for fx curve definition.
is_non_deliverable : bool, optional
An indicator whether the instrument is non-deliverable: * true: the instrument
is non-deliverable, * false: the instrument is not non-deliverable. the
property can be used to retrieve cross currency definition for the adjusted
interest rate curve.
name : str, optional
The fxcross currency pair applied to the reference or pivot currency. it is
expressed in iso 4217 alphabetical format (e.g., 'eur usd fxcross').
quoted_currency : str, optional
The quoted currency in the fxcross currency pair. it is expressed in iso 4217
alphabetical format (e.g., 'usd').
quoted_index_name : str, optional
The name of the floating rate index (e.g., 'sofr') applied to the quoted
currency.
source : str, optional
A user-defined string that is provided by the creator of a curve. curves created
by refinitiv have the 'refinitiv' source.
"""
def __init__(
self,
id: str,
main_constituent_asset_class: "OptMainConstituentAssetClass" = None,
risk_type: "OptRiskType" = None,
base_currency: "OptStr" = None,
base_index_name: "OptStr" = None,
definition_expiry_date: "OptDateTime" = None,
is_fallback_for_fx_curve_definition: "OptBool" = None,
is_non_deliverable: "OptBool" = None,
name: "OptStr" = None,
quoted_currency: "OptStr" = None,
quoted_index_name: "OptStr" = None,
source: "OptStr" = None,
) -> None:
super().__init__()
self.id = id
self.main_constituent_asset_class = main_constituent_asset_class
self.risk_type = risk_type
self.base_currency = base_currency
self.base_index_name = base_index_name
self.definition_expiry_date = definition_expiry_date
self.is_fallback_for_fx_curve_definition = is_fallback_for_fx_curve_definition
self.is_non_deliverable = is_non_deliverable
self.name = name
self.quoted_currency = quoted_currency
self.quoted_index_name = quoted_index_name
self.source = source | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_cross_currency_curves/_definitions/_update/_curve_update_definition.py | 0.942692 | 0.477798 | _curve_update_definition.py | pypi |
from typing import Optional, TYPE_CHECKING
from ......_tools import try_copy_to_list
from .....ipa._enums._extrapolation_mode import ExtrapolationMode
from ...._curves._enums import CompoundingType
from ...._object_definition import ObjectDefinition
from ..._bond_curves._enums import (
BasisSplineSmoothModel,
CalendarAdjustment,
CalibrationModel,
InterestCalculationMethod,
InterpolationMode,
PriceSide,
)
if TYPE_CHECKING:
from ......_types import OptStrings, OptInt, OptBool, OptStr, OptDateTime
class CreditCurveParameters(ObjectDefinition):
"""
Generates the credit curves for the definition provided
Parameters
----------
interest_calculation_method : InterestCalculationMethod, optional
The day count basis method used to compute the points of the zero coupon curve.
the possible values are: * dcb_30_360 actual number of days in the coupon
period calculated on the basis of a year of 360 days with twelve 30-day months
unless: - the last day of the period is the 31st day of a month and the
first day of the period is a day other than the 30th or 31st day of a month, in
which case the month that includes the last day shall not be considered to be
shortened to a 30-day month, - the last day of the period is the last day of
the month of february, in which case the month of february shall not be
considered to be lengthened to a 30-day month. * dcb_30_actual the day
count is identical to 30/360 (us) and the year basis is identical to
actual/actual. * dcb_actual_360 the day count is the actual number of days
of the period. the year basis is 360. * dcb_actual_365 the day count is
the actual number of days of the period. the year basis is 365. *
dcb_actual_actual the dcb is calculated by actual days / year basis where:
- actual days are defined as the actual days between the starting date
(d1.m1.y1) and end date (d2.m2.y2). - year basis is defined as the actual
days between the start date (d1.m1.y1) and the next relevant interest payment
date (d3.m3.y3) multiplied by the instrument coupon frequency. *
dcb_actual_actual_isda similar to actual/365, except for a period that
includes days falling in a leap year. it is calculated by dcb = number of days
in a leap year/366 + number of days in a non-leap year/365. a convention is
also known as actual/365 isda. *dcb_30_360_isda for two dates (y1,m1,d1)
and (y2,m2,d2): - if d1 is 31, change it to 30, - if d2 is 31 and d1 is
30, change d2 to 30. then the date difference is
(y2-y1)x360+(m2-m1)*30+(d2-d1). * dcb_30_365_isda for two dates (y1,m1,d1)
and (y2,m2,d2): - if d1=31 then d1=30, - if d2=31 and d1=30 or 31 then
d2=30. then the date difference is (y2-y1)*365+(m2-m1)*30+(d2-d1) *
dcb_30_360_us for two dates (y1,m1,d1) and (y2,m2,d2): - if d1=31 then
d1=30, - if d2=31 and d1=30 or 31 then d2=30, - if d1 is the last day of
february then d1=30, - if d1 is the last day of february and d2 is the last
day of february then d2=30. the last day of february is february 29 in leap
years and february 28 in non leap years. the 30/360 us rule is identical to
30/360 isda when the eom (end-of-month) convention does not apply. this
indicates whether all coupon payment dates fall on the last day of the month. if
the investment is not eom, it will always pay on the same day of the month
(e.g., the 10th). then the date difference is
(y2-y1)x360+(m2-m1)*30+(d2-d1). * dcb_actual_actual_afb the dcb is
calculated by actual days / year basis where: actual days are defined as the
actual days between the start date (d1.m1.y1) and end date (d2.m2.y2). year
basis is either 365 if the calculation period does not contain 29th feb, or 366
if the calculation period includes 29th feb. * dcb_workingdays_252 the day
count is the actual number of business days of the period according to the
instrument calendars. the year basis is 252. commonly used in the brazilian
market. * dcb_actual_365l the day count is the actual number of days of
the period. the year basis is calculated in the following two rules: - if
the coupon frequency is annual, then year basis is 366 if the 29 feb. is
included in the interest period, else 365, - if the coupon frequency is not
annual, then year basis is 366 for each interest period where ending date falls
in a leap year, otherwise it is 365. * dcb_actualleapday_365 the day count
ignores 29th february when counting days. the year basis is 365 days. *
dcb_actualleapday_360 the day count ignores 29th february when counting
days. the year basis is 360 days. * dcb_actual_36525 the day count is the
actual number of days of the period. the year basis is 365.25. *
dcb_actual_365_canadianconvention follows the canadian domestic bond market
convention. the day count basis is computed as follows: - if the number of
days of a period is less than the actual number of days in a regular coupon
period the dcb_actual_365 convention is used, - otherwise: dcb = 1 -
daysremaininginperiod x frequency / 365. * dcb_30_360_german for two dates
(y1,m1,d1) and (y2,m2,d2): - if d1=31 then d1=30, - if d2=31 then d2=30,
- if d1 is the last day of february then d1=30, - if d2 is the last day of
february then d2=30. the last day of february is february 29 in leap years
and february 28 in non leap years. then the date difference is
(y2-y1)x360+(m2-m1)*30+(d2-d1). * dcb_30_365_german similar to 30/360
(german), except that the year basis is treated as 365 days. *
dcb_30_actual_german the day count is identical to 30/360 (german) and the
year basis is similar to actual/actual. this method was formerly used in the
eurobond markets. * dcb_30e_360_isma actual number of days in the coupon
period calculated on the basis of a year of 360 days with twelve 30-day months
(regardless of the date of the first day or last day of the period). *
dcb_actual_364 a special case of actual/actual (isma) when a coupon period
contains 91 or 182 days. actual/364 applies for some short-term instruments.
day count basis = 364. * dcb_30_actual_isda * dcb_30_365_brazil *
dcb_actual_365p * dcb_constant
basis_spline_smooth_model : BasisSplineSmoothModel, optional
Basis spline model. values can be: - mccullochlinearregression -
waggonersmoothingsplinemodel - andersonsmoothingsplinemodel
calendar_adjustment : CalendarAdjustment, optional
The cash flow adjustment according to a selected calendar. the possible values
are: * no * weekend: for the cash flow pricing using the calendar 'weekend'
* calendar: for the cash flow pricing using the calendar defined by the
parameter 'calendars'. the default value is 'calendar'.
calendars : string, optional
The list of comma-separated calendar codes used to define non-working days and
to adjust interest rate curve coupon dates and values (e.g., 'emu_fi'). by
default, the calendar code is derived from the interest rate curve currency.
calibration_model : CalibrationModel, optional
Bond zero coupon curve calibration method. values can be: - basisspline -
nelsonsiegelsvensson - bootstrap
compounding_type : CompoundingType, optional
The yield type of the interest rate curve. the possible values are: *
continuous * moneymarket * compounded * discounted the default value is
'compounded'.
extrapolation_mode : ExtrapolationMode, optional
The extrapolation method used in the zero coupon curve bootstrapping. the
possible values are: * none: no extrapolation, * constant: constant
extrapolation, * linear: linear extrapolation. the default value is 'none'.
interpolation_mode : InterpolationMode, optional
The interpolation method used in zero curve bootstrapping. the possible values
are: * cubicdiscount: local cubic interpolation of discount factors *
cubicrate: local cubic interpolation of rates * cubicspline: a natural cubic
spline * forwardmonotoneconvex: forward monotone convexc interpolation *
linear: linear interpolation * log: log-linear interpolation * hermite:
hermite (bessel) interpolation * akimamethod: the akima method (a smoother
variant of local cubic interpolation) * fritschbutlandmethod: the
fritsch-butland method (a monotonic cubic variant) * krugermethod: the kruger
method (a monotonic cubic variant) * monotoniccubicnaturalspline: a monotonic
natural cubic spline * monotonichermitecubic: monotonic hermite (bessel) cubic
interpolation * tensionspline: a tension spline
price_side : PriceSide, optional
The quoted price side of the instrument to be used for the zero coupon curve
construction. the possible values are: * bid * ask * mid the default value
is 'mid'.
basis_spline_knots : int, optional
Number of knots you can choose to build the yield curve when using the
basis-spline models
return_calibrated_parameters : bool, optional
If true, returns parametric model calibrated parameters
use_delayed_data_if_denied : bool, optional
Use delayed ric to retrieve data when not permissioned on constituent ric. the
default value is 'false'.
use_duration_weighted_minimization : bool, optional
Specifies the type of minimization of residual errors in the vasicek-fong model
and basis spline model: - true: minimize residual errors between market and
model prices weighted by the inverse of the modified duration of the bonds -
false: minimize residual errors between market and model prices
use_multi_dimensional_solver : bool, optional
An indicator whether the multi-dimensional solver for yield curve bootstrapping
must be used. this solving method is required because the bootstrapping method
sometimes creates a zero coupon curve which does not accurately reprice the
input instruments used to build it. the multi-dimensional solver is recommended
when cubic interpolation methods are used in building the curve (in other cases,
performance might be inferior to the regular bootstrapping method). when use for
credit curve it is only used when the calibrationmodel is set to 'bootstrap'.
the possible values are: * true: the multi-dimensional solver is used, *
false: the multi-dimensional solver is not used. the default value is 'true'.
valuation_date : str or date or timedelta, optional
Valuation date for this curve, that means the data at which instrument market
data is retrieved.
"""
def __init__(
self,
interest_calculation_method: Optional[InterestCalculationMethod] = None,
basis_spline_smooth_model: Optional[BasisSplineSmoothModel] = None,
calendar_adjustment: Optional[CalendarAdjustment] = None,
calendars: "OptStrings" = None,
calibration_model: Optional[CalibrationModel] = None,
compounding_type: Optional[CompoundingType] = None,
extrapolation_mode: Optional[ExtrapolationMode] = None,
interpolation_mode: Optional[InterpolationMode] = None,
price_side: Optional[PriceSide] = None,
basis_spline_knots: "OptInt" = None,
return_calibrated_parameters: "OptBool" = None,
use_delayed_data_if_denied: "OptBool" = None,
use_duration_weighted_minimization: "OptBool" = None,
use_multi_dimensional_solver: "OptBool" = None,
valuation_date: "OptDateTime" = None,
) -> None:
super().__init__()
self.interest_calculation_method = interest_calculation_method
self.basis_spline_smooth_model = basis_spline_smooth_model
self.calendar_adjustment = calendar_adjustment
self.calendars = try_copy_to_list(calendars)
self.calibration_model = calibration_model
self.compounding_type = compounding_type
self.extrapolation_mode = extrapolation_mode
self.interpolation_mode = interpolation_mode
self.price_side = price_side
self.basis_spline_knots = basis_spline_knots
self.return_calibrated_parameters = return_calibrated_parameters
self.use_delayed_data_if_denied = use_delayed_data_if_denied
self.use_duration_weighted_minimization = use_duration_weighted_minimization
self.use_multi_dimensional_solver = use_multi_dimensional_solver
self.valuation_date = valuation_date
@property
def basis_spline_smooth_model(self):
"""
Basis spline model. values can be: - mccullochlinearregression -
waggonersmoothingsplinemodel - andersonsmoothingsplinemodel
:return: enum BasisSplineSmoothModel
"""
return self._get_enum_parameter(BasisSplineSmoothModel, "basisSplineSmoothModel")
@basis_spline_smooth_model.setter
def basis_spline_smooth_model(self, value):
self._set_enum_parameter(BasisSplineSmoothModel, "basisSplineSmoothModel", value)
@property
def calendar_adjustment(self):
"""
The cash flow adjustment according to a selected calendar. the possible values
are: * no * weekend: for the cash flow pricing using the calendar 'weekend'
* calendar: for the cash flow pricing using the calendar defined by the
parameter 'calendars'. the default value is 'calendar'.
:return: enum CalendarAdjustment
"""
return self._get_enum_parameter(CalendarAdjustment, "calendarAdjustment")
@calendar_adjustment.setter
def calendar_adjustment(self, value):
self._set_enum_parameter(CalendarAdjustment, "calendarAdjustment", value)
@property
def calendars(self):
"""
The list of comma-separated calendar codes used to define non-working days and
to adjust interest rate curve coupon dates and values (e.g., 'emu_fi'). by
default, the calendar code is derived from the interest rate curve currency.
:return: list string
"""
return self._get_list_parameter(str, "calendars")
@calendars.setter
def calendars(self, value):
self._set_list_parameter(str, "calendars", value)
@property
def calibration_model(self):
"""
Bond zero coupon curve calibration method. values can be: - basisspline -
nelsonsiegelsvensson - bootstrap
:return: enum CalibrationModel
"""
return self._get_enum_parameter(CalibrationModel, "calibrationModel")
@calibration_model.setter
def calibration_model(self, value):
self._set_enum_parameter(CalibrationModel, "calibrationModel", value)
@property
def compounding_type(self):
"""
The yield type of the interest rate curve. the possible values are: *
continuous * moneymarket * compounded * discounted the default value is
'compounded'.
:return: enum CompoundingType
"""
return self._get_enum_parameter(CompoundingType, "compoundingType")
@compounding_type.setter
def compounding_type(self, value):
self._set_enum_parameter(CompoundingType, "compoundingType", value)
@property
def extrapolation_mode(self):
"""
The extrapolation method used in the zero coupon curve bootstrapping. the
possible values are: * none: no extrapolation, * constant: constant
extrapolation, * linear: linear extrapolation. the default value is 'none'.
:return: enum ExtrapolationMode
"""
return self._get_enum_parameter(ExtrapolationMode, "extrapolationMode")
@extrapolation_mode.setter
def extrapolation_mode(self, value):
self._set_enum_parameter(ExtrapolationMode, "extrapolationMode", value)
@property
def interest_calculation_method(self):
"""
The day count basis method used to compute the points of the zero coupon curve.
the possible values are: * dcb_30_360 actual number of days in the coupon
period calculated on the basis of a year of 360 days with twelve 30-day months
unless: - the last day of the period is the 31st day of a month and the
first day of the period is a day other than the 30th or 31st day of a month, in
which case the month that includes the last day shall not be considered to be
shortened to a 30-day month, - the last day of the period is the last day of
the month of february, in which case the month of february shall not be
considered to be lengthened to a 30-day month. * dcb_30_actual the day
count is identical to 30/360 (us) and the year basis is identical to
actual/actual. * dcb_actual_360 the day count is the actual number of days
of the period. the year basis is 360. * dcb_actual_365 the day count is
the actual number of days of the period. the year basis is 365. *
dcb_actual_actual the dcb is calculated by actual days / year basis where:
- actual days are defined as the actual days between the starting date
(d1.m1.y1) and end date (d2.m2.y2). - year basis is defined as the actual
days between the start date (d1.m1.y1) and the next relevant interest payment
date (d3.m3.y3) multiplied by the instrument coupon frequency. *
dcb_actual_actual_isda similar to actual/365, except for a period that
includes days falling in a leap year. it is calculated by dcb = number of days
in a leap year/366 + number of days in a non-leap year/365. a convention is
also known as actual/365 isda. *dcb_30_360_isda for two dates (y1,m1,d1)
and (y2,m2,d2): - if d1 is 31, change it to 30, - if d2 is 31 and d1 is
30, change d2 to 30. then the date difference is
(y2-y1)x360+(m2-m1)*30+(d2-d1). * dcb_30_365_isda for two dates (y1,m1,d1)
and (y2,m2,d2): - if d1=31 then d1=30, - if d2=31 and d1=30 or 31 then
d2=30. then the date difference is (y2-y1)*365+(m2-m1)*30+(d2-d1) *
dcb_30_360_us for two dates (y1,m1,d1) and (y2,m2,d2): - if d1=31 then
d1=30, - if d2=31 and d1=30 or 31 then d2=30, - if d1 is the last day of
february then d1=30, - if d1 is the last day of february and d2 is the last
day of february then d2=30. the last day of february is february 29 in leap
years and february 28 in non leap years. the 30/360 us rule is identical to
30/360 isda when the eom (end-of-month) convention does not apply. this
indicates whether all coupon payment dates fall on the last day of the month. if
the investment is not eom, it will always pay on the same day of the month
(e.g., the 10th). then the date difference is
(y2-y1)x360+(m2-m1)*30+(d2-d1). * dcb_actual_actual_afb the dcb is
calculated by actual days / year basis where: actual days are defined as the
actual days between the start date (d1.m1.y1) and end date (d2.m2.y2). year
basis is either 365 if the calculation period does not contain 29th feb, or 366
if the calculation period includes 29th feb. * dcb_workingdays_252 the day
count is the actual number of business days of the period according to the
instrument calendars. the year basis is 252. commonly used in the brazilian
market. * dcb_actual_365l the day count is the actual number of days of
the period. the year basis is calculated in the following two rules: - if
the coupon frequency is annual, then year basis is 366 if the 29 feb. is
included in the interest period, else 365, - if the coupon frequency is not
annual, then year basis is 366 for each interest period where ending date falls
in a leap year, otherwise it is 365. * dcb_actualleapday_365 the day count
ignores 29th february when counting days. the year basis is 365 days. *
dcb_actualleapday_360 the day count ignores 29th february when counting
days. the year basis is 360 days. * dcb_actual_36525 the day count is the
actual number of days of the period. the year basis is 365.25. *
dcb_actual_365_canadianconvention follows the canadian domestic bond market
convention. the day count basis is computed as follows: - if the number of
days of a period is less than the actual number of days in a regular coupon
period the dcb_actual_365 convention is used, - otherwise: dcb = 1 -
daysremaininginperiod x frequency / 365. * dcb_30_360_german for two dates
(y1,m1,d1) and (y2,m2,d2): - if d1=31 then d1=30, - if d2=31 then d2=30,
- if d1 is the last day of february then d1=30, - if d2 is the last day of
february then d2=30. the last day of february is february 29 in leap years
and february 28 in non leap years. then the date difference is
(y2-y1)x360+(m2-m1)*30+(d2-d1). * dcb_30_365_german similar to 30/360
(german), except that the year basis is treated as 365 days. *
dcb_30_actual_german the day count is identical to 30/360 (german) and the
year basis is similar to actual/actual. this method was formerly used in the
eurobond markets. * dcb_30e_360_isma actual number of days in the coupon
period calculated on the basis of a year of 360 days with twelve 30-day months
(regardless of the date of the first day or last day of the period). *
dcb_actual_364 a special case of actual/actual (isma) when a coupon period
contains 91 or 182 days. actual/364 applies for some short-term instruments.
day count basis = 364. * dcb_30_actual_isda * dcb_30_365_brazil *
dcb_actual_365p * dcb_constant
:return: enum InterestCalculationMethod
"""
return self._get_enum_parameter(InterestCalculationMethod, "interestCalculationMethod")
@interest_calculation_method.setter
def interest_calculation_method(self, value):
self._set_enum_parameter(InterestCalculationMethod, "interestCalculationMethod", value)
@property
def interpolation_mode(self):
"""
The interpolation method used in zero curve bootstrapping. the possible values
are: * cubicdiscount: local cubic interpolation of discount factors *
cubicrate: local cubic interpolation of rates * cubicspline: a natural cubic
spline * forwardmonotoneconvex: forward monotone convexc interpolation *
linear: linear interpolation * log: log-linear interpolation * hermite:
hermite (bessel) interpolation * akimamethod: the akima method (a smoother
variant of local cubic interpolation) * fritschbutlandmethod: the
fritsch-butland method (a monotonic cubic variant) * krugermethod: the kruger
method (a monotonic cubic variant) * monotoniccubicnaturalspline: a monotonic
natural cubic spline * monotonichermitecubic: monotonic hermite (bessel) cubic
interpolation * tensionspline: a tension spline
:return: enum InterpolationMode
"""
return self._get_enum_parameter(InterpolationMode, "interpolationMode")
@interpolation_mode.setter
def interpolation_mode(self, value):
self._set_enum_parameter(InterpolationMode, "interpolationMode", value)
@property
def price_side(self):
"""
The quoted price side of the instrument to be used for the zero coupon curve
construction. the possible values are: * bid * ask * mid the default value
is 'mid'.
:return: enum PriceSide
"""
return self._get_enum_parameter(PriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(PriceSide, "priceSide", value)
@property
def basis_spline_knots(self):
"""
Number of knots you can choose to build the yield curve when using the
basis-spline models
:return: int
"""
return self._get_parameter("basisSplineKnots")
@basis_spline_knots.setter
def basis_spline_knots(self, value):
self._set_parameter("basisSplineKnots", value)
@property
def return_calibrated_parameters(self):
"""
If true, returns parametric model calibrated parameters
:return: bool
"""
return self._get_parameter("returnCalibratedParameters")
@return_calibrated_parameters.setter
def return_calibrated_parameters(self, value):
self._set_parameter("returnCalibratedParameters", value)
@property
def use_delayed_data_if_denied(self):
"""
Use delayed ric to retrieve data when not permissioned on constituent ric. the
default value is 'false'.
:return: bool
"""
return self._get_parameter("useDelayedDataIfDenied")
@use_delayed_data_if_denied.setter
def use_delayed_data_if_denied(self, value):
self._set_parameter("useDelayedDataIfDenied", value)
@property
def use_duration_weighted_minimization(self):
"""
Specifies the type of minimization of residual errors in the vasicek-fong model
and basis spline model: - true: minimize residual errors between market and
model prices weighted by the inverse of the modified duration of the bonds -
false: minimize residual errors between market and model prices
:return: bool
"""
return self._get_parameter("useDurationWeightedMinimization")
@use_duration_weighted_minimization.setter
def use_duration_weighted_minimization(self, value):
self._set_parameter("useDurationWeightedMinimization", value)
@property
def use_multi_dimensional_solver(self):
"""
An indicator whether the multi-dimensional solver for yield curve bootstrapping
must be used. this solving method is required because the bootstrapping method
sometimes creates a zero coupon curve which does not accurately reprice the
input instruments used to build it. the multi-dimensional solver is recommended
when cubic interpolation methods are used in building the curve (in other cases,
performance might be inferior to the regular bootstrapping method). when use for
credit curve it is only used when the calibrationmodel is set to 'bootstrap'.
the possible values are: * true: the multi-dimensional solver is used, *
false: the multi-dimensional solver is not used. the default value is 'true'.
:return: bool
"""
return self._get_parameter("useMultiDimensionalSolver")
@use_multi_dimensional_solver.setter
def use_multi_dimensional_solver(self, value):
self._set_parameter("useMultiDimensionalSolver", value)
@property
def valuation_date(self):
"""
Valuation date for this curve, that means the data at which instrument market
data is retrieved.
:return: str
"""
return self._get_parameter("valuationDate")
@valuation_date.setter
def valuation_date(self, value):
self._set_date_parameter("valuationDate", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_bond_curves/_curves/_credit_curve_parameters.py | 0.906862 | 0.577525 | _credit_curve_parameters.py | pypi |
from typing import TYPE_CHECKING
from ._credit_constituents import CreditConstituents
from ...._object_definition import ObjectDefinition
from ._credit_curve_definition import CreditCurveDefinition
from ._credit_curve_parameters import CreditCurveParameters
if TYPE_CHECKING:
from ......_types import OptStr
from .._types import CurveDefinition, CurveParameters, OptCreditConstituents
class RequestItem(ObjectDefinition):
"""
Generates the credit curves for the definition provided
Parameters
----------
constituents : CreditConstituents, optional
curve_definition : CreditCurveDefinition, optional
curve_parameters : CreditCurveParameters, optional
curve_tag : str, optional
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
"""
def __init__(
self,
constituents: "OptCreditConstituents" = None,
curve_definition: "CurveDefinition" = None,
curve_parameters: "CurveParameters" = None,
curve_tag: "OptStr" = None,
) -> None:
super().__init__()
self.constituents = constituents
self.curve_definition = curve_definition
self.curve_parameters = curve_parameters
self.curve_tag = curve_tag
@property
def constituents(self):
"""
:return: object CreditConstituents
"""
return self._get_object_parameter(CreditConstituents, "constituents")
@constituents.setter
def constituents(self, value):
self._set_object_parameter(CreditConstituents, "constituents", value)
@property
def curve_definition(self):
"""
:return: object CreditCurveDefinition
"""
return self._get_object_parameter(CreditCurveDefinition, "curveDefinition")
@curve_definition.setter
def curve_definition(self, value):
self._set_object_parameter(CreditCurveDefinition, "curveDefinition", value)
@property
def curve_parameters(self):
"""
:return: object CreditCurveParameters
"""
return self._get_object_parameter(CreditCurveParameters, "curveParameters")
@curve_parameters.setter
def curve_parameters(self, value):
self._set_object_parameter(CreditCurveParameters, "curveParameters", value)
@property
def curve_tag(self):
"""
A user-defined string to identify the interest rate curve. it can be used to
link output results to the curve definition. limited to 40 characters. only
alphabetic, numeric and '- _.#=@' characters are supported.
:return: str
"""
return self._get_parameter("curveTag")
@curve_tag.setter
def curve_tag(self, value):
self._set_parameter("curveTag", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_bond_curves/_curves/_request.py | 0.959602 | 0.236538 | _request.py | pypi |
from typing import Optional, TYPE_CHECKING
from ......_tools import try_copy_to_list
from ..._bond_curves._enums import (
BusinessSector,
CurveSubType,
EconomicSector,
Industry,
IndustryGroup,
IssuerType,
MainConstituentAssetClass,
Rating,
RatingScaleSource,
ReferenceEntityType,
Seniority,
)
from ...._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ......_types import OptStrings, OptStr
class CreditCurveDefinition(ObjectDefinition):
"""
Generates the credit curves for the definition provided
Parameters
----------
business_sector : BusinessSector, optional
Trbc business sector of the economic sector.
credit_curve_type_fallback_logic : string, optional
Credit curve types list used to define the fallback logic in order to find the
best credit curve. curves types are ordered by priority.
curve_sub_type : CurveSubType, optional
curve_tenors : string, optional
User defined maturities to compute.
economic_sector : EconomicSector, optional
Trbc economic sector of the issuer. available values are: basicmaterials,
consumer cyclicals, consumer non-cyclicals, energy, financials, healthcare,
industrials, technology, utilities
industry : Industry, optional
Trbc industry of the industry group.
industry_group : IndustryGroup, optional
Trbc industry group of the business sector.
issuer_type : IssuerType, optional
Type of the issuer. available values are: agency, corporate, munis,
nonfinancials, sovereign, supranational
main_constituent_asset_class : MainConstituentAssetClass, optional
rating : Rating, optional
Rating of the issuer. the rating can be defined by using any of: "refinitiv",
"s&p", "moody's", "fitch", "dbrs" convention
rating_scale_source : RatingScaleSource, optional
reference_entity_type : ReferenceEntityType, optional
Type of the reference entity (mandatory if referenceentity is defined).
avialable values are: - chainric - bondisin - bondric - organisationid
- ticker
seniority : Seniority, optional
Type of seniority. available values are: senior preferred, subordinate
unsecured, senior non-preferred
country : str, optional
Country code of the issuer defined with alpha-2 code iso 3166 country code
convention
currency : str, optional
Bond curve currency code
id : str, optional
name : str, optional
reference_entity : str, optional
Code to define the reference entity.
source : str, optional
Source or contributor code default value is "refinitiv"
"""
def __init__(
self,
business_sector: Optional[BusinessSector] = None,
credit_curve_type_fallback_logic: "OptStrings" = None,
curve_sub_type: Optional[CurveSubType] = None,
curve_tenors: "OptStrings" = None,
economic_sector: Optional[EconomicSector] = None,
industry: Optional[Industry] = None,
industry_group: Optional[IndustryGroup] = None,
issuer_type: Optional[IssuerType] = None,
main_constituent_asset_class: Optional[MainConstituentAssetClass] = None,
rating: Optional[Rating] = None,
rating_scale_source: Optional[RatingScaleSource] = None,
reference_entity_type: Optional[ReferenceEntityType] = None,
seniority: Optional[Seniority] = None,
country: "OptStr" = None,
currency: "OptStr" = None,
id: "OptStr" = None,
name: "OptStr" = None,
reference_entity: "OptStr" = None,
source: "OptStr" = None,
) -> None:
super().__init__()
self.business_sector = business_sector
self.credit_curve_type_fallback_logic = credit_curve_type_fallback_logic
self.curve_sub_type = curve_sub_type
self.curve_tenors = try_copy_to_list(curve_tenors)
self.economic_sector = economic_sector
self.industry = industry
self.industry_group = industry_group
self.issuer_type = issuer_type
self.main_constituent_asset_class = main_constituent_asset_class
self.rating = rating
self.rating_scale_source = rating_scale_source
self.reference_entity_type = reference_entity_type
self.seniority = seniority
self.country = country
self.currency = currency
self.id = id
self.name = name
self.reference_entity = reference_entity
self.source = source
@property
def business_sector(self):
"""
Trbc business sector of the economic sector.
:return: enum BusinessSector
"""
return self._get_enum_parameter(BusinessSector, "businessSector")
@business_sector.setter
def business_sector(self, value):
self._set_enum_parameter(BusinessSector, "businessSector", value)
@property
def credit_curve_type_fallback_logic(self):
"""
Credit curve types list used to define the fallback logic in order to find the
best credit curve. curves types are ordered by priority.
:return: list string
"""
return self._get_list_parameter(str, "creditCurveTypeFallbackLogic")
@credit_curve_type_fallback_logic.setter
def credit_curve_type_fallback_logic(self, value):
self._set_list_parameter(str, "creditCurveTypeFallbackLogic", value)
@property
def curve_sub_type(self):
"""
:return: enum CurveSubType
"""
return self._get_enum_parameter(CurveSubType, "curveSubType")
@curve_sub_type.setter
def curve_sub_type(self, value):
self._set_enum_parameter(CurveSubType, "curveSubType", value)
@property
def curve_tenors(self):
"""
User defined maturities to compute.
:return: list string
"""
return self._get_list_parameter(str, "curveTenors")
@curve_tenors.setter
def curve_tenors(self, value):
self._set_list_parameter(str, "curveTenors", value)
@property
def economic_sector(self):
"""
Trbc economic sector of the issuer. available values are: basicmaterials,
consumer cyclicals, consumer non-cyclicals, energy, financials, healthcare,
industrials, technology, utilities
:return: enum EconomicSector
"""
return self._get_enum_parameter(EconomicSector, "economicSector")
@economic_sector.setter
def economic_sector(self, value):
self._set_enum_parameter(EconomicSector, "economicSector", value)
@property
def industry(self):
"""
Trbc industry of the industry group.
:return: enum Industry
"""
return self._get_enum_parameter(Industry, "industry")
@industry.setter
def industry(self, value):
self._set_enum_parameter(Industry, "industry", value)
@property
def industry_group(self):
"""
Trbc industry group of the business sector.
:return: enum IndustryGroup
"""
return self._get_enum_parameter(IndustryGroup, "industryGroup")
@industry_group.setter
def industry_group(self, value):
self._set_enum_parameter(IndustryGroup, "industryGroup", value)
@property
def issuer_type(self):
"""
Type of the issuer. available values are: agency, corporate, munis,
nonfinancials, sovereign, supranational
:return: enum IssuerType
"""
return self._get_enum_parameter(IssuerType, "issuerType")
@issuer_type.setter
def issuer_type(self, value):
self._set_enum_parameter(IssuerType, "issuerType", value)
@property
def main_constituent_asset_class(self):
"""
:return: enum MainConstituentAssetClass
"""
return self._get_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass")
@main_constituent_asset_class.setter
def main_constituent_asset_class(self, value):
self._set_enum_parameter(MainConstituentAssetClass, "mainConstituentAssetClass", value)
@property
def rating(self):
"""
Rating of the issuer. the rating can be defined by using any of: "refinitiv",
"s&p", "moody's", "fitch", "dbrs" convention
:return: enum Rating
"""
return self._get_enum_parameter(Rating, "rating")
@rating.setter
def rating(self, value):
self._set_enum_parameter(Rating, "rating", value)
@property
def rating_scale_source(self):
"""
:return: enum RatingScaleSource
"""
return self._get_enum_parameter(RatingScaleSource, "ratingScaleSource")
@rating_scale_source.setter
def rating_scale_source(self, value):
self._set_enum_parameter(RatingScaleSource, "ratingScaleSource", value)
@property
def reference_entity_type(self):
"""
Type of the reference entity (mandatory if referenceentity is defined).
avialable values are: - chainric - bondisin - bondric - organisationid
- ticker
:return: enum ReferenceEntityType
"""
return self._get_enum_parameter(ReferenceEntityType, "referenceEntityType")
@reference_entity_type.setter
def reference_entity_type(self, value):
self._set_enum_parameter(ReferenceEntityType, "referenceEntityType", value)
@property
def seniority(self):
"""
Type of seniority. available values are: senior preferred, subordinate
unsecured, senior non-preferred
:return: enum Seniority
"""
return self._get_enum_parameter(Seniority, "seniority")
@seniority.setter
def seniority(self, value):
self._set_enum_parameter(Seniority, "seniority", value)
@property
def country(self):
"""
Country code of the issuer defined with alpha-2 code iso 3166 country code
convention
:return: str
"""
return self._get_parameter("country")
@country.setter
def country(self, value):
self._set_parameter("country", value)
@property
def currency(self):
"""
Bond curve currency code
:return: str
"""
return self._get_parameter("currency")
@currency.setter
def currency(self, value):
self._set_parameter("currency", value)
@property
def id(self):
"""
:return: str
"""
return self._get_parameter("id")
@id.setter
def id(self, value):
self._set_parameter("id", value)
@property
def name(self):
"""
:return: str
"""
return self._get_parameter("name")
@name.setter
def name(self, value):
self._set_parameter("name", value)
@property
def reference_entity(self):
"""
Code to define the reference entity.
:return: str
"""
return self._get_parameter("referenceEntity")
@reference_entity.setter
def reference_entity(self, value):
self._set_parameter("referenceEntity", value)
@property
def source(self):
"""
Source or contributor code default value is "refinitiv"
:return: str
"""
return self._get_parameter("source")
@source.setter
def source(self, value):
self._set_parameter("source", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_bond_curves/_curves/_credit_curve_definition.py | 0.942414 | 0.338405 | _credit_curve_definition.py | pypi |
from typing import Union
import numpy as np
from scipy import interpolate
from . import CurvePoint
from ..._content_provider import value_arg_parser
from ..._enums import Axis
class Curve:
"""
Methods
-------
get_point(x, y): CurvePoint
Examples
-------
>>> from refinitiv.data.content.ipa.curves import forward_curve
>>> definition = forward_curve.Definition(
... curve_definition=forward_curve.SwapZcCurveDefinition(
... currency="EUR",
... index_name="EURIBOR",
... name="EUR EURIBOR Swap ZC Curve",
... discounting_tenor="OIS",
...
... ),
... forward_curve_definitions=[
... forward_curve.ForwardCurveDefinition(
... index_tenor="3M",
... forward_curve_tag="ForwardTag",
... forward_start_date="2021-02-01",
... forward_curve_tenors=[
... "0D",
... "1D",
... "2D",
... "3M",
... "6M",
... "9M",
... "1Y",
... "2Y",
... "3Y",
... "4Y",
... "5Y",
... "6Y",
... "7Y",
... "8Y",
... "9Y",
... "10Y",
... "15Y",
... "20Y",
... "25Y"
... ]
... )
... ]
...)
>>> response = definition.get_data()
>>> curve = response.data.curve
>>> point = curve.get_point("2021-02-02", Axis.X)
"""
def __init__(self, x: np.array, y: np.array) -> None:
self._x = x
self._y = y
@property
def x(self):
return self._x
@property
def y(self):
return self._y
def get_point(
self,
value: Union[str, float, np.datetime64],
axis: Union[Axis, str],
) -> CurvePoint:
"""
Parameters
----------
value: str, float, np.datetime64
axis: Axis
Returns
-------
CurvePoint
Raises
-------
ValueError
If cannot identify axis
"""
value = value_arg_parser.parse(value)
is_value_on_axis_x = axis == Axis.X
is_value_on_axis_y = axis == Axis.Y
value_as_float = value_arg_parser.get_float(value)
if is_value_on_axis_x:
f = interpolate.interp1d(
x=self._x.astype(float),
y=self._y.astype(float),
)
x = value
y = f(x=value_as_float)
y = float(y)
elif is_value_on_axis_y:
f = interpolate.interp1d(
x=self._y.astype(float),
y=self._x.astype(float),
)
x = f(x=value_as_float)
x = float(x)
y = value
else:
raise ValueError(f"Cannot identify axis={axis}")
return CurvePoint(x, y)
def __str__(self) -> str:
x = self._x
if np.iterable(self._x):
x = ", ".join(str(i) for i in self._x)
y = self._y
if np.iterable(self._y):
y = ", ".join(str(i) for i in self._y)
return f"X={x}\nY={y}"
class ForwardCurve(Curve):
def __init__(self, x: np.array, y: np.array, **kwargs) -> None:
super().__init__(x, y)
self.forward_curve_tag = kwargs.get("forwardCurveTag")
self.forward_start = kwargs.get("forwardStart")
self.index_tenor = kwargs.get("indexTenor")
class ZcCurve(Curve):
def __init__(self, x: np.array, y: np.array, index_tenor, **kwargs) -> None:
super().__init__(x, y)
self.index_tenor = index_tenor
self.is_discount_curve = kwargs.get("isDiscountCurve") | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_models/_curve.py | 0.943073 | 0.458773 | _curve.py | pypi |
from typing import Optional, TYPE_CHECKING
from ....._types import OptStr, OptBool
from ..._object_definition import ObjectDefinition
from .._enums import (
CalendarAdjustment,
CompoundingType,
ExtrapolationMode,
DayCountBasis,
MarketDataAccessDeniedFallback,
SwapPriceSide,
ZcInterpolationMode,
)
from .._models import Step, Turn, ConvexityAdjustment
if TYPE_CHECKING:
from .._zc_curve_types import Steps, Turns
class InterestRateCurveParameters(ObjectDefinition):
"""
Parameters
----------
interest_calculation_method : InterestCalculationMethod, optional
Day count basis of the calculated zero coupon rates
calendar_adjustment : CalendarAdjustment, optional
Cash flow adjustment according to a calendar.
- No: for analytic pricing (i.e. from the bond structure)
- Null: for cash flow pricing using the calendar NULL
- Weekend: for cash flow pricing using the calendar Weekend
- Calendar: for cash flow pricing using the calendar defined
by the parameter calendars.
calendars : string, optional
A list of one or more calendar codes used to define non-working days and to
adjust coupon dates and values.
compounding_type : CompoundingType, optional
Output rates yield type. Values can be:
- Continuous: continuous rate (default value)
- MoneyMarket: money market rate
- Compounded: compounded rate
- Discounted: discounted rate
convexity_adjustment : ConvexityAdjustment, optional
extrapolation_mode : ExtrapolationMode, optional
Extrapolation method for the curve
- None: no extrapolation
- Constant: constant extrapolation
- Linear: linear extrapolation
interpolation_mode : ZcInterpolationMode, optional
Interpolation method for the curve. Available values are:
- CubicDiscount: local cubic interpolation of discount factors
- CubicRate: local cubic interpolation of rates
- CubicSpline: a natural cubic spline
- ForwardMonotoneConvex: forward mMonotone Convexc interpolation
- Linear: linear interpolation
- Log: log-linear interpolation
- Hermite: Hermite (Bessel) interpolation
- AkimaMethod: the Akima method
(a smoother variant of local cubic interpolation)
- FritschButlandMethod: the Fritsch-Butland method (a monotonic cubic variant)
- KrugerMethod: the Kruger method (a monotonic cubic variant)
- MonotonicCubicNaturalSpline: a monotonic natural cubic spline
- MonotonicHermiteCubic: monotonic Hermite (Bessel) cubic interpolation
- TensionSpline: a tension spline
market_data_access_denied_fallback : MarketDataAccessDeniedFallback, optional
- ReturnError: dont price the surface and return an error (Default value)
- IgnoreConstituents: price the surface without the error market data
- UseDelayedData: use delayed Market Data if possible
price_side : SwapPriceSide, optional
Price side of the instrument to be used. Default value is: Mid
steps : Step, optional
turns : Turn, optional
Used to include end period rates/turns when calculating swap rate surfaces
reference_tenor : str, optional
Root tenor(s) for the xIbor dependencies
use_convexity_adjustment : bool, optional
use_multi_dimensional_solver : bool, optional
Specifies the use of the multi-dimensional solver for yield curve bootstrapping.
This solving method is required because the bootstrapping method
sometimes creates a ZC curve which does not accurately reprice the input
instruments used to build it.
The multi-dimensional solver is recommended when cubic interpolation methods
are used in building the curve (in other cases, performance might be inferior
to the regular bootstrapping method). When use for Credit Curve it is only
used when the calibrationModel is set to Bootstrap.
- true: to use multi-dimensional solver for yield curve bootstrapping
- false: not to use multi-dimensional solver for yield curve bootstrapping
use_steps : bool, optional
"""
def __init__(
self,
interest_calculation_method: Optional[DayCountBasis] = None,
calendar_adjustment: Optional[CalendarAdjustment] = None,
calendars: OptStr = None,
compounding_type: Optional[CompoundingType] = None,
convexity_adjustment: Optional[ConvexityAdjustment] = None,
extrapolation_mode: Optional[ExtrapolationMode] = None,
interpolation_mode: Optional[ZcInterpolationMode] = None,
market_data_access_denied_fallback: Optional[MarketDataAccessDeniedFallback] = None,
price_side: Optional[SwapPriceSide] = None,
steps: "Steps" = None,
turns: "Turns" = None,
reference_tenor: OptStr = None,
use_convexity_adjustment: OptBool = None,
use_multi_dimensional_solver: OptBool = None,
use_steps: OptBool = None,
) -> None:
super().__init__()
self.interest_calculation_method = interest_calculation_method
self.calendar_adjustment = calendar_adjustment
self.calendars = calendars
self.compounding_type = compounding_type
self.convexity_adjustment = convexity_adjustment
self.extrapolation_mode = extrapolation_mode
self.interpolation_mode = interpolation_mode
self.market_data_access_denied_fallback = market_data_access_denied_fallback
self.price_side = price_side
self.steps = steps
self.turns = turns
self.reference_tenor = reference_tenor
self.use_convexity_adjustment = use_convexity_adjustment
self.use_multi_dimensional_solver = use_multi_dimensional_solver
self.use_steps = use_steps
@property
def calendar_adjustment(self):
"""
Cash flow adjustment according to a calendar.
- No: for analytic pricing (i.e. from the bond structure)
- Null: for cash flow pricing using the calendar NULL
- Weekend: for cash flow pricing using the calendar Weekend
- Calendar: for cash flow pricing using the calendar defined
by the parameter calendars.
:return: enum CalendarAdjustment
"""
return self._get_enum_parameter(CalendarAdjustment, "calendarAdjustment")
@calendar_adjustment.setter
def calendar_adjustment(self, value):
self._set_enum_parameter(CalendarAdjustment, "calendarAdjustment", value)
@property
def calendars(self):
"""
A list of one or more calendar codes used to define non-working days and to
adjust coupon dates and values.
:return: list string
"""
return self._get_list_parameter(str, "calendars")
@calendars.setter
def calendars(self, value):
self._set_list_parameter(str, "calendars", value)
@property
def compounding_type(self):
"""
Output rates yield type. Values can be:
- Continuous: continuous rate (default value)
- MoneyMarket: money market rate
- Compounded: compounded rate
- Discounted: discounted rate
:return: enum CompoundingType
"""
return self._get_enum_parameter(CompoundingType, "compoundingType")
@compounding_type.setter
def compounding_type(self, value):
self._set_enum_parameter(CompoundingType, "compoundingType", value)
@property
def convexity_adjustment(self):
"""
:return: object ConvexityAdjustment
"""
return self._get_object_parameter(ConvexityAdjustment, "convexityAdjustment")
@convexity_adjustment.setter
def convexity_adjustment(self, value):
self._set_object_parameter(ConvexityAdjustment, "convexityAdjustment", value)
@property
def extrapolation_mode(self):
"""
Extrapolation method for the curve
- None: no extrapolation
- Constant: constant extrapolation
- Linear: linear extrapolation
:return: enum ExtrapolationMode
"""
return self._get_enum_parameter(ExtrapolationMode, "extrapolationMode")
@extrapolation_mode.setter
def extrapolation_mode(self, value):
self._set_enum_parameter(ExtrapolationMode, "extrapolationMode", value)
@property
def interest_calculation_method(self):
"""
Day count basis of the calculated zero coupon rates
:return: enum InterestCalculationMethod
"""
return self._get_enum_parameter(DayCountBasis, "interestCalculationMethod")
@interest_calculation_method.setter
def interest_calculation_method(self, value):
self._set_enum_parameter(DayCountBasis, "interestCalculationMethod", value)
@property
def interpolation_mode(self):
"""
Interpolation method for the curve. Available values are:
- CubicDiscount: local cubic interpolation of discount factors
- CubicRate: local cubic interpolation of rates
- CubicSpline: a natural cubic spline
- ForwardMonotoneConvex: forward mMonotone Convexc interpolation
- Linear: linear interpolation
- Log: log-linear interpolation
- Hermite: Hermite (Bessel) interpolation
- AkimaMethod: the Akima method
(a smoother variant of local cubic interpolation)
- FritschButlandMethod: the Fritsch-Butland method (a monotonic cubic variant)
- KrugerMethod: the Kruger method (a monotonic cubic variant)
- MonotonicCubicNaturalSpline: a monotonic natural cubic spline
- MonotonicHermiteCubic: monotonic Hermite (Bessel) cubic interpolation
- TensionSpline: a tension spline
:return: enum InterpolationMode
"""
return self._get_enum_parameter(ZcInterpolationMode, "interpolationMode")
@interpolation_mode.setter
def interpolation_mode(self, value):
self._set_enum_parameter(ZcInterpolationMode, "interpolationMode", value)
@property
def market_data_access_denied_fallback(self):
"""
- ReturnError: dont price the surface and return an error (Default value)
- IgnoreConstituents: price the surface without the error market data
- UseDelayedData: use delayed Market Data if possible
:return: enum MarketDataAccessDeniedFallback
"""
return self._get_enum_parameter(MarketDataAccessDeniedFallback, "marketDataAccessDeniedFallback")
@market_data_access_denied_fallback.setter
def market_data_access_denied_fallback(self, value):
self._set_enum_parameter(MarketDataAccessDeniedFallback, "marketDataAccessDeniedFallback", value)
@property
def price_side(self):
"""
Price side of the instrument to be used. Default value is: Mid
:return: enum SwapPriceSide
"""
return self._get_enum_parameter(SwapPriceSide, "priceSide")
@price_side.setter
def price_side(self, value):
self._set_enum_parameter(SwapPriceSide, "priceSide", value)
@property
def steps(self):
"""
:return: list Step
"""
return self._get_list_parameter(Step, "steps")
@steps.setter
def steps(self, value):
self._set_list_parameter(Step, "steps", value)
@property
def turns(self):
"""
Used to include end period rates/turns when calculating swap rate surfaces
:return: list Turn
"""
return self._get_list_parameter(Turn, "turns")
@turns.setter
def turns(self, value):
self._set_list_parameter(Turn, "turns", value)
@property
def reference_tenor(self):
"""
Root tenor(s) for the xIbor dependencies
:return: str
"""
return self._get_parameter("referenceTenor")
@reference_tenor.setter
def reference_tenor(self, value):
self._set_parameter("referenceTenor", value)
@property
def use_convexity_adjustment(self):
"""
:return: bool
"""
return self._get_parameter("useConvexityAdjustment")
@use_convexity_adjustment.setter
def use_convexity_adjustment(self, value):
self._set_parameter("useConvexityAdjustment", value)
@property
def use_multi_dimensional_solver(self):
"""
Specifies the use of the multi-dimensional solver for yield curve bootstrapping.
This solving method is required because the bootstrapping method
sometimes creates a ZC curve which does not accurately reprice the input
instruments used to build it.
The multi-dimensional solver is recommended when cubic interpolation methods
are used in building the curve (in other cases, performance might be inferior
to the regular bootstrapping method). When use for Credit Curve it is only
used when the calibrationModel is set to Bootstrap.
- true: to use multi-dimensional solver for yield curve bootstrapping
- false: not to use multi-dimensional solver for yield curve bootstrapping
:return: bool
"""
return self._get_parameter("useMultiDimensionalSolver")
@use_multi_dimensional_solver.setter
def use_multi_dimensional_solver(self, value):
self._set_parameter("useMultiDimensionalSolver", value)
@property
def use_steps(self):
"""
:return: bool
"""
return self._get_parameter("useSteps")
@use_steps.setter
def use_steps(self, value):
self._set_parameter("useSteps", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_models/_interest_rate_curve_parameters.py | 0.959828 | 0.542803 | _interest_rate_curve_parameters.py | pypi |
from typing import TYPE_CHECKING
from ..._object_definition import ObjectDefinition
if TYPE_CHECKING:
from ....._types import OptStr
class ValuationTime(ObjectDefinition):
"""
Parameters
----------
city_name : str, optional
The city name according to market identifier code (mic) (e.g., 'new york') see
iso 10383 for reference.
local_time : str, optional
Local time or other words time in offset timezone. the value is expressed in iso
8601 format: [hh]:[mm]:[ss] (e.g., '14:00:00').
market_identifier_code : str, optional
Market identifier code (mic) is a unique identification code used to identify
securities trading exchanges, regulated and non-regulated trading markets. e.g.
xnas. see iso 10383 for reference.
time_zone_offset : str, optional
Time offsets from utc. the value is expressed in iso 8601 format: [hh]:[mm]
(e.g., '+05:00').
"""
def __init__(
self,
city_name: "OptStr" = None,
local_time: "OptStr" = None,
market_identifier_code: "OptStr" = None,
time_zone_offset: "OptStr" = None,
) -> None:
super().__init__()
self.city_name = city_name
self.local_time = local_time
self.market_identifier_code = market_identifier_code
self.time_zone_offset = time_zone_offset
@property
def city_name(self):
"""
The city name according to market identifier code (mic) (e.g., 'new york') see
iso 10383 for reference.
:return: str
"""
return self._get_parameter("cityName")
@city_name.setter
def city_name(self, value):
self._set_parameter("cityName", value)
@property
def local_time(self):
"""
Local time or other words time in offset timezone. the value is expressed in iso
8601 format: [hh]:[mm]:[ss] (e.g., '14:00:00').
:return: str
"""
return self._get_parameter("localTime")
@local_time.setter
def local_time(self, value):
self._set_parameter("localTime", value)
@property
def market_identifier_code(self):
"""
Market identifier code (mic) is a unique identification code used to identify
securities trading exchanges, regulated and non-regulated trading markets. e.g.
xnas. see iso 10383 for reference.
:return: str
"""
return self._get_parameter("marketIdentifierCode")
@market_identifier_code.setter
def market_identifier_code(self, value):
self._set_parameter("marketIdentifierCode", value)
@property
def time_zone_offset(self):
"""
Time offsets from utc. the value is expressed in iso 8601 format: [hh]:[mm]
(e.g., '+05:00').
:return: str
"""
return self._get_parameter("timeZoneOffset")
@time_zone_offset.setter
def time_zone_offset(self, value):
self._set_parameter("timeZoneOffset", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_curves/_models/_valuation_time.py | 0.926806 | 0.357848 | _valuation_time.py | pypi |
__all__ = ["FxPoint"]
from .._object_definition import ObjectDefinition
from .._enums import Status
class FxPoint(ObjectDefinition):
def __init__(
self,
bid=None,
ask=None,
mid=None,
status=None,
instrument=None,
processing_information=None,
spot_decimals=None,
):
super().__init__()
self.bid = bid
self.ask = ask
self.mid = mid
self.status = status
self.instrument = instrument
self.processing_information = processing_information
self.spot_decimals = spot_decimals
@property
def status(self):
"""
:return: enum Status
"""
return self._get_enum_parameter(Status, "status")
@status.setter
def status(self, value):
self._set_enum_parameter(Status, "status", value)
@property
def ask(self):
"""
:return: float
"""
return self._get_parameter("ask")
@ask.setter
def ask(self, value):
self._set_parameter("ask", value)
@property
def bid(self):
"""
:return: float
"""
return self._get_parameter("bid")
@bid.setter
def bid(self, value):
self._set_parameter("bid", value)
@property
def instrument(self):
"""
:return: str
"""
return self._get_parameter("instrument")
@instrument.setter
def instrument(self, value):
self._set_parameter("instrument", value)
@property
def mid(self):
"""
:return: float
"""
return self._get_parameter("mid")
@mid.setter
def mid(self, value):
self._set_parameter("mid", value)
@property
def processing_information(self):
"""
:return: str
"""
return self._get_parameter("processingInformation")
@processing_information.setter
def processing_information(self, value):
self._set_parameter("processingInformation", value)
@property
def spot_decimals(self):
"""
:return: str
"""
return self._get_parameter("spotDecimals")
@spot_decimals.setter
def spot_decimals(self, value):
self._set_parameter("spotDecimals", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_models/_fx_point.py | 0.854521 | 0.151875 | _fx_point.py | pypi |
__all__ = ["AmortizationItem"]
from typing import Optional, Union
from ...._types import OptDateTime
from .._object_definition import ObjectDefinition
from .._enums import (
AmortizationType,
AmortizationFrequency,
)
class AmortizationItem(ObjectDefinition):
"""
Parameters
----------
start_date : str or date or datetime or timedelta, optional
Start Date of an amortization section/window, or stepped rate
end_date : str or date or datetime or timedelta, optional
End Date of an amortization section/window, or stepped rate
amortization_frequency : AmortizationFrequency, optional
Frequency of the Amortization
amortization_type : AmortizationType or str, optional
Amortization type Annuity, Schedule, Linear, ....
remaining_notional : float, optional
The Remaining Notional Amount after Amortization
amount : float, optional
Amortization Amount at each Amortization Date
Examples
----------
>>> amortization_item = AmortizationItem(
... start_date="2021-02-11",
... end_date="2022-02-11",
... amount=100000,
... amortization_type=AmortizationType.SCHEDULE
... )
>>> amortization_item
"""
def __init__(
self,
start_date: "OptDateTime" = None,
end_date: "OptDateTime" = None,
amortization_frequency: Optional[AmortizationFrequency] = None,
amortization_type: Union[AmortizationType, str] = None,
remaining_notional: Optional[float] = None,
amount: Optional[float] = None,
) -> None:
super().__init__()
self.start_date = start_date
self.end_date = end_date
self.amortization_frequency = amortization_frequency
self.amortization_type = amortization_type
self.remaining_notional = remaining_notional
self.amount = amount
@property
def amortization_frequency(self):
"""
Frequency of the Amortization
:return: enum AmortizationFrequency
"""
return self._get_enum_parameter(AmortizationFrequency, "amortizationFrequency")
@amortization_frequency.setter
def amortization_frequency(self, value):
self._set_enum_parameter(AmortizationFrequency, "amortizationFrequency", value)
@property
def amortization_type(self):
"""
Amortization type Annuity, Schedule, Linear, ....
:return: enum AmortizationType
"""
return self._get_enum_parameter(AmortizationType, "amortizationType")
@amortization_type.setter
def amortization_type(self, value):
self._set_enum_parameter(AmortizationType, "amortizationType", value)
@property
def amount(self):
"""
Amortization Amount at each Amortization Date
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value)
@property
def end_date(self):
"""
End Date of an amortization section/window, or stepped rate
:return: str
"""
return self._get_parameter("endDate")
@end_date.setter
def end_date(self, value):
self._set_datetime_parameter("endDate", value)
@property
def remaining_notional(self):
"""
The Remaining Notional Amount after Amortization
:return: float
"""
return self._get_parameter("remainingNotional")
@remaining_notional.setter
def remaining_notional(self, value):
self._set_parameter("remainingNotional", value)
@property
def start_date(self):
"""
Start Date of an amortization section/window, or stepped rate
:return: str
"""
return self._get_parameter("startDate")
@start_date.setter
def start_date(self, value):
self._set_datetime_parameter("startDate", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_models/_amortization_item.py | 0.95056 | 0.224162 | _amortization_item.py | pypi |
from typing import Optional
from ...._types import OptDateTime
from .._enums import PremiumSettlementType
from .._object_definition import ObjectDefinition
class InputFlow(ObjectDefinition):
"""
API endpoint for Financial Contract analytics,
that returns calculations relevant to each contract type.
Parameters
----------
amount : float, optional
premium_settlement_type : PremiumSettlementType, optional
The cash settlement type of the option premium -spot -forward
currency : str, optional
date : str or date or datetime or timedelta, optional
"""
def __init__(
self,
amount: Optional[float] = None,
premium_settlement_type: Optional[PremiumSettlementType] = None,
currency: Optional[str] = None,
date: "OptDateTime" = None,
) -> None:
super().__init__()
self.amount = amount
self.premium_settlement_type = premium_settlement_type
self.currency = currency
self.date = date
@property
def premium_settlement_type(self):
"""
The cash settlement type of the option premium -spot -forward
:return: enum PremiumSettlementType
"""
return self._get_enum_parameter(PremiumSettlementType, "premiumSettlementType")
@premium_settlement_type.setter
def premium_settlement_type(self, value):
self._set_enum_parameter(PremiumSettlementType, "premiumSettlementType", value)
@property
def amount(self):
"""
:return: float
"""
return self._get_parameter("amount")
@amount.setter
def amount(self, value):
self._set_parameter("amount", value)
@property
def currency(self):
"""
:return: str
"""
return self._get_parameter("currency")
@currency.setter
def currency(self, value):
self._set_parameter("currency", value)
@property
def date(self):
"""
:return: str
"""
return self._get_parameter("date")
@date.setter
def date(self, value):
self._set_date_parameter("date", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_models/_input_flow.py | 0.946535 | 0.30142 | _input_flow.py | pypi |
from typing import Optional
from .._enums import BarrierType
from .._object_definition import ObjectDefinition
class BarrierDefinitionElement(ObjectDefinition):
def __init__(
self,
barrier_type: Optional[BarrierType] = None,
barrier_down_percent: Optional[float] = None,
barrier_up_percent: Optional[float] = None,
rebate_down_percent: Optional[float] = None,
rebate_up_percent: Optional[float] = None,
):
super().__init__()
self.barrier_type = barrier_type
self.barrier_down_percent = barrier_down_percent
self.barrier_up_percent = barrier_up_percent
self.rebate_down_percent = rebate_down_percent
self.rebate_up_percent = rebate_up_percent
@property
def barrier_type(self):
"""
:return: enum BarrierType
"""
return self._get_enum_parameter(BarrierType, "barrierType")
@barrier_type.setter
def barrier_type(self, value):
self._set_enum_parameter(BarrierType, "barrierType", value)
@property
def barrier_down_percent(self):
"""
:return: float
"""
return self._get_parameter("barrierDownPercent")
@barrier_down_percent.setter
def barrier_down_percent(self, value):
self._set_parameter("barrierDownPercent", value)
@property
def barrier_up_percent(self):
"""
:return: float
"""
return self._get_parameter("barrierUpPercent")
@barrier_up_percent.setter
def barrier_up_percent(self, value):
self._set_parameter("barrierUpPercent", value)
@property
def rebate_down_percent(self):
"""
:return: float
"""
return self._get_parameter("rebateDownPercent")
@rebate_down_percent.setter
def rebate_down_percent(self, value):
self._set_parameter("rebateDownPercent", value)
@property
def rebate_up_percent(self):
"""
:return: float
"""
return self._get_parameter("rebateUpPercent")
@rebate_up_percent.setter
def rebate_up_percent(self, value):
self._set_parameter("rebateUpPercent", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_models/_barrier_definition_element.py | 0.930836 | 0.196036 | _barrier_definition_element.py | pypi |
__all__ = ["BondRoundingParameters"]
from .._object_definition import ObjectDefinition
from .._enums import RoundingType, Rounding
class BondRoundingParameters(ObjectDefinition):
def __init__(
self,
accrued_rounding=None,
accrued_rounding_type=None,
price_rounding=None,
price_rounding_type=None,
spread_rounding=None,
spread_rounding_type=None,
yield_rounding=None,
yield_rounding_type=None,
):
super().__init__()
self.accrued_rounding = accrued_rounding
self.accrued_rounding_type = accrued_rounding_type
self.price_rounding = price_rounding
self.price_rounding_type = price_rounding_type
self.spread_rounding = spread_rounding
self.spread_rounding_type = spread_rounding_type
self.yield_rounding = yield_rounding
self.yield_rounding_type = yield_rounding_type
@property
def accrued_rounding(self):
"""
Number of digits to apply for rounding of Accrued field. Available values are Zero, One, Two,..., Eight, Default, Unrounded.
Optional. A default value may be defined in bond reference data, in that case it is used. If it is not the case no rounding
is applied.
:return: enum Rounding
"""
return self._get_enum_parameter(Rounding, "accruedRounding")
@accrued_rounding.setter
def accrued_rounding(self, value):
self._set_enum_parameter(Rounding, "accruedRounding", value)
@property
def accrued_rounding_type(self):
"""
Type of rounding for accrued rounding.
Optional. A default value can be defined in bond reference data. Otherwise, default value is Near.
:return: enum RoundingType
"""
return self._get_enum_parameter(RoundingType, "accruedRoundingType")
@accrued_rounding_type.setter
def accrued_rounding_type(self, value):
self._set_enum_parameter(RoundingType, "accruedRoundingType", value)
@property
def price_rounding(self):
"""
Number of digits to apply for price rounding. Available values are Zero, One, Two,..., Eight, Default, Unrounded.
Optional. A default value may be defined in bond reference data, in that case it is used. If it is not the case no rounding
is applied.
:return: enum Rounding
"""
return self._get_enum_parameter(Rounding, "priceRounding")
@price_rounding.setter
def price_rounding(self, value):
self._set_enum_parameter(Rounding, "priceRounding", value)
@property
def price_rounding_type(self):
"""
Type of rounding for price rounding.
Optional. A default value can be defined in bond reference data. Otherwise, default value is Near.
:return: enum RoundingType
"""
return self._get_enum_parameter(RoundingType, "priceRoundingType")
@price_rounding_type.setter
def price_rounding_type(self, value):
self._set_enum_parameter(RoundingType, "priceRoundingType", value)
@property
def spread_rounding(self):
"""
Number of digits to apply for spread rounding. Available values are Zero, One, Two,..., Eight, Default, Unrounded.
Note that spread rounding is done directly on the base point value.
Optional. By default, data from the bond structure.
:return: enum Rounding
"""
return self._get_enum_parameter(Rounding, "spreadRounding")
@spread_rounding.setter
def spread_rounding(self, value):
self._set_enum_parameter(Rounding, "spreadRounding", value)
@property
def spread_rounding_type(self):
"""
:return: enum RoundingType
"""
return self._get_enum_parameter(RoundingType, "spreadRoundingType")
@spread_rounding_type.setter
def spread_rounding_type(self, value):
self._set_enum_parameter(RoundingType, "spreadRoundingType", value)
@property
def yield_rounding(self):
"""
Number of digits to apply for yield rounding. Available values are Zero, One, Two,..., Eight, Default, Unrounded.
Optional. A default value may be defined in bond reference data, in that case it is used. If it is not the case no rounding
is applied.
:return: enum Rounding
"""
return self._get_enum_parameter(Rounding, "yieldRounding")
@yield_rounding.setter
def yield_rounding(self, value):
self._set_enum_parameter(Rounding, "yieldRounding", value)
@property
def yield_rounding_type(self):
"""
Type of rounding for yield rounding.
Optional. A default value can be defined in bond reference data. Otherwise, default value is Near.
:return: enum RoundingType
"""
return self._get_enum_parameter(RoundingType, "yieldRoundingType")
@yield_rounding_type.setter
def yield_rounding_type(self, value):
self._set_enum_parameter(RoundingType, "yieldRoundingType", value) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/ipa/_models/_bond_rounding_parameters.py | 0.90668 | 0.344499 | _bond_rounding_parameters.py | pypi |
from typing import TYPE_CHECKING, Union
from ._stream import (
Events,
FinalizedOrders,
UniverseTypes,
universe_type_arg_parser,
finalized_orders_arg_parser,
events_arg_parser,
)
from ._stream_facade import Stream
from ..._tools import create_repr, try_copy_to_list
if TYPE_CHECKING:
from ..._types import OptStr, ExtendedParams, OptStrStrs
from ..._core.session import Session
class Definition:
"""
This class describes Analytics Trade Data Service.
Parameters
----------
universe : list, optional
A list of RIC or symbol or user's id for retrieving trading analytics data.
fields : list, optional
A list of enumerate fields.
events : str or Events, optional
Enable/Disable the detail of order event in the streaming.
Default: False
finalized_orders : str or FinalizedOrders, optional
Enable/Disable the cached of finalized order of current day in the streaming.
Default: False
filters : list, optional
Set the condition of subset of trading streaming data.
universe_type : str or UniverseTypes, optional
A type of given universe can be RIC, Symbol or UserID.
Default: UniverseTypes.RIC
api: str, optional
Specifies the data source. It can be updated/added using config file
extended_params : dict, optional
If necessary other parameters
Methods
-------
get_stream(session=session)
Get stream object of this definition
Examples
--------
>>> from refinitiv.data.content import trade_data_service
>>> definition = trade_data_service.Definition()
"""
def __init__(
self,
universe: "OptStrStrs" = None,
universe_type: Union[str, UniverseTypes] = UniverseTypes.UserID,
fields: "OptStrStrs" = None,
events: Union[str, Events] = Events.No,
finalized_orders: Union[str, FinalizedOrders] = FinalizedOrders.No,
filters: "OptStrStrs" = None,
api: "OptStr" = None,
extended_params: "ExtendedParams" = None,
):
self._universe = try_copy_to_list(universe)
self._universe_type = universe_type_arg_parser.get_str(universe_type)
self._fields = try_copy_to_list(fields)
self._events = events_arg_parser.get_str(events)
self._finalized_orders = finalized_orders_arg_parser.get_str(finalized_orders)
self._filters = try_copy_to_list(filters)
self._api = api
self._extended_params = extended_params
def __repr__(self):
return create_repr(
self,
middle_path="content.trade_data_service",
content={"universe": self._universe},
)
def get_stream(self, session: "Session" = None) -> Stream:
"""
Returns a streaming trading analytics subscription.
Parameters
----------
session : Session, optional
The Session used by the TradeDataService to retrieve data from the platform
Returns
-------
TradeDataStream
Examples
--------
>>> from refinitiv.data.content import trade_data_service
>>> definition = trade_data_service.Definition()
>>> stream = definition.get_stream()
>>> stream.open()
"""
stream = Stream(
session=session,
universe=self._universe,
universe_type=self._universe_type,
fields=self._fields,
events=self._events,
finalized_orders=self._finalized_orders,
filters=self._filters,
api=self._api,
extended_params=self._extended_params,
)
return stream | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/trade_data_service/_definition.py | 0.92153 | 0.252848 | _definition.py | pypi |
from typing import TYPE_CHECKING
from .._content_response_factory import ContentResponseFactory
if TYPE_CHECKING:
from ...delivery._data._data_provider import ParsedData
error_message_by_code = {
"default": "{error_message} Requested universes: {universes}. Requested fields: {fields}",
412: "Unable to resolve all requested identifiers in {universes}.",
218: "Unable to resolve all requested fields in {fields}. The formula must "
"contain at least one field or function.",
}
class DataGridResponseFactory(ContentResponseFactory):
def create_fail(self, parsed_data: "ParsedData", universe=None, fields=None, **kwargs):
error_code = parsed_data.first_error_code
if error_code not in error_message_by_code.keys():
parsed_data.error_messages = error_message_by_code["default"].format(
error_message=parsed_data.first_error_message,
fields=fields,
universes=universe,
)
else:
parsed_data.error_messages = error_message_by_code[error_code].format(fields=fields, universes=universe)
return super().create_fail(parsed_data, **kwargs)
class DataGridRDPResponseFactory(DataGridResponseFactory):
def create_success(self, parsed_data: "ParsedData", **kwargs):
inst = super().create_success(parsed_data, **kwargs)
descriptions = self.get_raw(parsed_data).get("messages", {}).get("descriptions", [])
for descr in descriptions:
code = descr.get("code")
if code in {416, 413}:
inst.errors.append((code, descr.get("description")))
return inst
class DataGridUDFResponseFactory(DataGridResponseFactory):
def get_raw(self, parsed_data: "ParsedData"):
return parsed_data.content_data.get("responses", [{}])[0]
def create_success(self, parsed_data: "ParsedData", **kwargs):
inst = super().create_success(parsed_data, **kwargs)
error = self.get_raw(parsed_data).get("error", [])
for err in error:
code = err.get("code")
if code == 416:
inst.errors.append((code, err.get("message")))
return inst | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/fundamental_and_reference/_response_factory.py | 0.710327 | 0.239327 | _response_factory.py | pypi |
from ..._tools import (
ADC_TR_PATTERN,
ADC_FUNC_PATTERN_IN_FIELDS,
ParamItem,
ValueParamItem,
)
from ...delivery._data import RequestMethod
from ...delivery._data._data_provider import RequestFactory, Request
data_grid_rdp_body_params_config = [
ParamItem("universe"),
ParamItem("fields"),
ParamItem("parameters"),
ValueParamItem(
"layout",
"output",
is_true=lambda layout, **kwargs: isinstance(layout, dict) and layout.get("output"),
function=lambda layout, **kwargs: layout["output"],
),
]
data_grid_udf_body_params_config = [
ParamItem("universe", "instruments"),
ValueParamItem(
"fields",
function=lambda fields, **kwargs: [
{"name": i} for i in fields if ADC_TR_PATTERN.match(i) or ADC_FUNC_PATTERN_IN_FIELDS.match(i)
],
),
ParamItem("parameters"),
ValueParamItem(
"layout",
is_true=lambda layout, **kwargs: isinstance(layout, dict) and layout.get("layout"),
function=lambda layout, **kwargs: layout["layout"],
),
]
class DataGridRequestFactory(RequestFactory):
def get_request_method(self, **kwargs) -> RequestMethod:
return RequestMethod.POST
class DataGridRDPRequestFactory(DataGridRequestFactory):
@property
def body_params_config(self):
return data_grid_rdp_body_params_config
class DataGridUDFRequestFactory(DataGridRequestFactory):
def create(self, session, *args, **kwargs):
url_root = session._get_rdp_url_root()
url = url_root.replace("rdp", "udf")
method = self.get_request_method(**kwargs)
header_parameters = kwargs.get("header_parameters") or {}
extended_params = kwargs.get("extended_params") or {}
body_parameters = self.get_body_parameters(*args, **kwargs)
body_parameters = self.extend_body_parameters(body_parameters, extended_params)
headers = {"Content-Type": "application/json"}
headers.update(header_parameters)
request = Request(
url=url,
method=method,
headers=headers,
json={
"Entity": {
"E": "DataGrid_StandardAsync",
"W": {"requests": [body_parameters]},
}
},
)
closure = kwargs.get("closure")
if closure:
request.closure = closure
return request
@property
def body_params_config(self):
return data_grid_udf_body_params_config
def get_body_parameters(self, *args, **kwargs) -> dict:
ticket = kwargs.get("ticket")
if ticket:
return {"ticket": ticket}
return super().get_body_parameters(*args, **kwargs) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/fundamental_and_reference/_request_factory.py | 0.61682 | 0.16175 | _request_factory.py | pypi |
from ..._base_enum import StrEnum
from typing import TYPE_CHECKING, Tuple
from ..._content_type import ContentType
from ..._core.session.tools import is_platform_session
from ..._tools import make_enum_arg_parser, ArgsParser, validate_bool_value
if TYPE_CHECKING:
from ..._core.session import Session
class DataGridType(StrEnum):
UDF = "udf"
RDP = "rdp"
data_grid_types_arg_parser = make_enum_arg_parser(DataGridType)
use_field_names_in_headers_arg_parser = ArgsParser(validate_bool_value)
data_grid_type_value_by_content_type = {
DataGridType.UDF: ContentType.DATA_GRID_UDF,
DataGridType.RDP: ContentType.DATA_GRID_RDP,
}
content_type_by_data_grid_type = {
ContentType.DATA_GRID_UDF: DataGridType.UDF,
ContentType.DATA_GRID_RDP: DataGridType.RDP,
}
def get_data_grid_type(content_type: ContentType) -> DataGridType:
data_grid_type = content_type_by_data_grid_type.get(content_type)
if not data_grid_type:
raise ValueError(f"There is no DataGridType for content_type:{content_type}")
return data_grid_type
def get_content_type(session: "Session") -> ContentType:
from ...delivery._data._data_provider_factory import get_api_config
config = get_api_config(ContentType.DATA_GRID_RDP, session.config)
name_platform = config.setdefault("underlying-platform", DataGridType.RDP)
name_platform = data_grid_types_arg_parser.get_str(name_platform)
content_type = data_grid_type_value_by_content_type.get(name_platform)
return content_type
def determine_content_type_and_flag(session: "Session") -> Tuple["ContentType", bool]:
content_type = get_content_type(session)
changed = False
if is_platform_session(session) and content_type == ContentType.DATA_GRID_UDF:
content_type = ContentType.DATA_GRID_RDP
changed = True
return content_type, changed
def get_data_grid_type_by_session(session: "Session") -> DataGridType:
content_type, _ = determine_content_type_and_flag(session)
return get_data_grid_type(content_type) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/fundamental_and_reference/_data_grid_type.py | 0.562777 | 0.254225 | _data_grid_type.py | pypi |
from typing import TYPE_CHECKING, Iterable, Callable, List
from ..._tools import cached_property
from ...delivery._data._data_provider import ContentValidator
if TYPE_CHECKING:
from ...delivery._data._data_provider import ParsedData
class DataGridContentValidator(ContentValidator):
@classmethod
def status_is_not_error(cls, data: "ParsedData") -> bool:
status_content = data.status.get("content", "")
if status_content.startswith("Failed"):
data.error_codes = -1
data.error_messages = status_content
return False
return True
class DataGridRDPContentValidator(DataGridContentValidator):
@classmethod
def content_data_has_no_error(cls, data: "ParsedData") -> bool:
content_data = data.content_data
error = content_data.get("error")
if error and not content_data.get("data"):
data.error_codes = error.get("code", -1)
data.error_messages = error.get("description")
if not data.error_messages:
error_message = error.get("message")
errors = error.get("errors")
if isinstance(errors, list):
error_message += ":\n"
error_message += "\n".join(map(str, errors))
data.error_messages = error_message
return False
return True
@cached_property
def validators(self) -> List[Callable[["ParsedData"], bool]]:
return [
self.status_is_not_error,
self.content_data_is_not_none,
self.content_data_has_no_error,
]
class DataGridUDFContentValidator(DataGridContentValidator):
@classmethod
def get_raw(cls, parsed_data: "ParsedData"):
return parsed_data.content_data.get("responses", [{}])[0]
@classmethod
def content_data_is_valid_type(cls, data: "ParsedData") -> bool:
content_data = data.content_data
if isinstance(content_data, str):
data.error_codes = -1
data.error_messages = content_data
return False
return True
@classmethod
def content_data_has_valid_response(cls, data: "ParsedData") -> bool:
responses = data.content_data.get("responses", [])
first_response = responses[0] if responses else {}
error = first_response.get("error")
if error and not first_response.get("data"):
if isinstance(error, dict):
data.error_codes = error.get("code", -1)
data.error_messages = error.get("message", error)
else:
data.error_codes = -1
data.error_messages = error
return False
return True
@classmethod
def content_data_response_has_valid_data(cls, data: "ParsedData") -> bool:
response = cls.get_raw(data)
if response.get("ticket"):
return True
row_headers_count = response.get("rowHeadersCount")
if not row_headers_count:
data.error_codes = -1
data.error_messages = "Unable to resolve all request identifiers."
return False
error = response.get("error")
if error and not any(
any(items[row_headers_count:]) if isinstance(items, Iterable) else False for items in response.get("data")
):
first_error = error[0]
data.error_codes = first_error.get("code", -1)
data.error_messages = first_error.get("message", first_error)
return False
return True
@cached_property
def validators(self) -> List[Callable[["ParsedData"], bool]]:
return [
self.status_is_not_error,
self.content_data_is_not_none,
self.content_data_is_valid_type,
self.content_data_has_no_error,
self.content_data_has_valid_response,
self.content_data_response_has_valid_data,
] | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/fundamental_and_reference/_content_validator.py | 0.820901 | 0.284576 | _content_validator.py | pypi |
import asyncio
import time
from enum import unique
from typing import Callable, List, Union, TYPE_CHECKING, Optional, Any
from ._data_grid_type import DataGridType, determine_content_type_and_flag, use_field_names_in_headers_arg_parser
from .._content_data import Data
from .._content_provider_layer import ContentUsageLoggerMixin
from .._df_build_type import DFBuildType
from ..._base_enum import StrEnum
from ..._content_type import ContentType
from ..._core.session import get_valid_session
from ..._tools import (
ArgsParser,
make_convert_to_enum_arg_parser,
try_copy_to_list,
fields_arg_parser,
universe_arg_parser,
)
from ..._tools import create_repr
from ...delivery._data._data_provider import DataProviderLayer, BaseResponse
from ...errors import RDError
if TYPE_CHECKING:
from ..._types import ExtendedParams, OptDict, StrStrings
from ..._core.session import Session
MIN_TICKET_DURATION_MS = 15000
@unique
class RowHeaders(StrEnum):
"""Possible values for row headers."""
DATE = "date"
OptRowHeaders = Optional[Union[str, List[str], RowHeaders, List[RowHeaders]]]
row_headers_enum_arg_parser = make_convert_to_enum_arg_parser(RowHeaders)
def parse_row_headers(value) -> Union[RowHeaders, List[RowHeaders]]:
if value is None:
return []
value = row_headers_enum_arg_parser.parse(value)
return value
row_headers_arg_parser = ArgsParser(parse_row_headers)
def get_layout(row_headers: List[RowHeaders], content_type: ContentType) -> dict:
layout = None
is_rdp = content_type is ContentType.DATA_GRID_RDP
is_udf = content_type is ContentType.DATA_GRID_UDF
if is_udf:
layout = {
"layout": {
"columns": [{"item": "dataitem"}],
"rows": [{"item": "instrument"}],
}
}
elif is_rdp:
layout = {"output": "Col,T|Va,Row,In|"}
if RowHeaders.DATE in row_headers:
if is_udf:
layout["layout"]["rows"].append({"item": "date"})
elif is_rdp:
output = layout["output"]
output = output[:-1] # delete forward slash "|"
output = f"{output},date|"
layout["output"] = output
else:
layout = ""
if layout is None:
raise ValueError(f"Layout is None, row_headers={row_headers}, content_type={content_type}")
return layout
def get_dfbuild_type(row_headers: List[RowHeaders]) -> DFBuildType:
dfbuild_type = DFBuildType.INDEX
if RowHeaders.DATE in row_headers:
dfbuild_type = DFBuildType.DATE_AS_INDEX
return dfbuild_type
class Definition(ContentUsageLoggerMixin[BaseResponse[Data]], DataProviderLayer[BaseResponse[Data]]):
"""
Defines the Fundamental and Reference data to retrieve.
Parameters:
----------
universe : str or list of str
Single instrument or list of instruments.
fields : str or list of str
Single field or list of fields.
parameters : dict, optional
Fields global parameters.
row_headers : str, list of str, list of RowHeaders enum
Output/layout parameters to add to the underlying request. Put headers to rows in the response.
use_field_names_in_headers : bool, optional
Boolean that indicates whether or not to add field names in the headers.
extended_params : dict, optional
Specifies the parameters that will be merged with the request.
Examples
--------
>>> from refinitiv.data.content import fundamental_and_reference
>>> definition = fundamental_and_reference.Definition(["IBM"], ["TR.Volume"])
>>> definition.get_data()
Using get_data_async
>>> import asyncio
>>> task = definition.get_data_async()
>>> response = asyncio.run(task)
"""
_USAGE_CLS_NAME = "FundamentalAndReference.Definition"
def __init__(
self,
universe: "StrStrings",
fields: "StrStrings",
parameters: "OptDict" = None,
row_headers: OptRowHeaders = None,
use_field_names_in_headers: bool = False,
extended_params: "ExtendedParams" = None,
):
extended_params = extended_params or {}
universe = extended_params.get("universe") or try_copy_to_list(universe)
universe = universe_arg_parser.get_list(universe)
universe = [value.upper() if value.islower() else value for value in universe]
self.universe = universe
self.fields = fields_arg_parser.get_list(try_copy_to_list(fields))
if parameters is not None and not isinstance(parameters, dict):
raise ValueError(f"Arg parameters must be a dictionary")
self.parameters = parameters
self.use_field_names_in_headers = use_field_names_in_headers_arg_parser.get_bool(use_field_names_in_headers)
self.extended_params = extended_params
self.row_headers = try_copy_to_list(row_headers)
super().__init__(
data_type=ContentType.DEFAULT,
universe=self.universe,
fields=self.fields,
parameters=self.parameters,
row_headers=self.row_headers,
use_field_names_in_headers=self.use_field_names_in_headers,
extended_params=self.extended_params,
)
def _update_content_type(self, session: "Session"):
content_type, changed = determine_content_type_and_flag(session)
changed and session.debug(
f"UDF DataGrid service cannot be used with platform sessions, RDP DataGrid will be used instead. "
f"The \"/apis/data/datagrid/underlying-platform = '{DataGridType.UDF}'\" "
f"parameter will be discarded, meaning that the regular RDP DataGrid "
f"service will be used for Fundamental and Reference data requests."
)
self._initialize(content_type, **self._kwargs)
row_headers = self._kwargs.get("row_headers")
row_headers = row_headers_arg_parser.get_list(row_headers)
layout = get_layout(row_headers, content_type)
dfbuild_type = get_dfbuild_type(row_headers)
self._kwargs["layout"] = layout
self._kwargs["__dfbuild_type__"] = dfbuild_type
@staticmethod
def make_on_response(callback: Callable) -> Callable:
def on_response(response, data_provider, session):
if response and response.data and response.data.raw.get("ticket"):
return
callback(response, data_provider, session)
return on_response
@staticmethod
def _get_duration(raw: dict) -> int:
"""
Compute the duration to sleep before next retry to request ticket status
Parameters
----------
raw : dict
e.g. {"estimatedDuration": 44000, "ticket": "78BF26B24A9D416E"}
Raises
------
RDError
If raw does not contain "estimatedDuration"
Returns
-------
int
Duration in seconds
"""
estimated_duration_ms = raw.get("estimatedDuration")
if estimated_duration_ms:
duration_sec = min(estimated_duration_ms, MIN_TICKET_DURATION_MS) // 1000
return duration_sec
raise RDError(-1, "Received a ticket response from DataGrid without estimatedDuration")
def get_data(
self,
session: Optional["Session"] = None,
on_response: Optional[Callable] = None,
):
"""
Sends a request to the Refinitiv Data Platform to retrieve the data.
Parameters
----------
session : Session, optional
Session object. If it's not passed the default session will be used.
on_response : Callable, optional
User-defined callback function to process received response.
Returns
-------
Response
Raises
------
AttributeError
If user didn't set default session.
"""
session = get_valid_session(session)
self._update_content_type(session)
if self._content_type == ContentType.DATA_GRID_UDF:
on_response_filter = on_response and self.make_on_response(on_response)
response = super().get_data(session, on_response_filter)
raw = response.data.raw
ticket = raw.get("ticket")
while ticket:
time.sleep(self._get_duration(raw))
self._kwargs["ticket"] = ticket
response = super().get_data(session, on_response_filter)
raw = response.data.raw
ticket = raw.get("ticket")
else:
response = super().get_data(session, on_response)
return response
async def get_data_async(
self,
session: Optional["Session"] = None,
on_response: Optional[Callable] = None,
closure: Optional[Any] = None,
):
"""
Sends an asynchronous request to the Refinitiv Data Platform to retrieve the data.
Parameters
----------
session : Session, optional
Session object. If it's not passed the default session will be used.
on_response : Callable, optional
User-defined callback function to process received response.
closure : any, optional
Optional closure that will be passed to the headers and returned
Returns
-------
Response
Raises
------
AttributeError
If user didn't set default session.
"""
session = get_valid_session(session)
self._update_content_type(session)
if self._content_type == ContentType.DATA_GRID_UDF:
on_response_filter = on_response and self.make_on_response(on_response)
response = await super().get_data_async(session, on_response_filter, closure)
raw = response.data.raw
ticket = raw.get("ticket")
while ticket:
await asyncio.sleep(self._get_duration(raw))
self._kwargs["ticket"] = ticket
response = await super().get_data_async(session, on_response_filter, closure)
raw = response.data.raw
ticket = raw.get("ticket")
else:
response = await super().get_data_async(session, on_response, closure)
return response
def __repr__(self):
return create_repr(
self,
content=f"{{"
f"universe='{self.universe}', "
f"fields='{self.fields}', "
f"parameters='{self.parameters}', "
f"row_headers='{self.row_headers}'"
f"}}",
) | /refinitiv-data-1.3.1.tar.gz/refinitiv-data-1.3.1/refinitiv/data/content/fundamental_and_reference/_definition.py | 0.822973 | 0.243693 | _definition.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.