serenity_types package

serenity_types.account.core

class serenity_types.account.core.Account(*, accountId: UUID, version: int, owner: str, updatedBy: str, updatedAt: datetime, name: str, accountSource: AccountSource, connectorId: UUID | None = None)[source]

Bases: CamelModel

Maintains the overall account information.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_id: UUID

Unique and immutable ID.

account_source: AccountSource

The authoritative source where trading activities, positions and balances can be found.

connector_id: UUID | None

The PositionConnector which created this account. Account created by PositionConnector cannot be manually removed or modified.

name: str

A descriptive name for this account.

owner: str

The primary owner of this account.

updated_at: datetime

Last update timestamp, in UTC.

updated_by: str

Last update user.

version: int

Monotonically increasing version number.

class serenity_types.account.core.AccountBaseRequest(*, name: str, owner: str, updatedBy: str, accountSource: AccountSource)[source]

Bases: CamelModel

The account base request class

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_source: AccountSource
name: str
owner: str
updated_by: str
class serenity_types.account.core.AccountCreationRequest(*, name: str, owner: str, updatedBy: str, accountSource: AccountSource)[source]

Bases: AccountBaseRequest

Input for the create request

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_source: AccountSource
name: str
owner: str
updated_by: str
class serenity_types.account.core.AccountSource(*, sourceIdentifier: str, sourcePlatformId: UUID)[source]

Bases: CamelModel

The authoritative source where trading activities, positions and balances can be found.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

source_identifier: str

The unique identifier that matches to the account name in an exchange or a wallet address if it’s in blockchain.

source_platform_id: UUID

The platform or source where the source_identifier is located. E.g. Binance, Coinbase, Ethereum blockchain.

class serenity_types.account.core.AccountUpdateRequest(*, name: str, owner: str, updatedBy: str, accountSource: AccountSource)[source]

Bases: AccountBaseRequest

Input for the update request

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_source: AccountSource
name: str
owner: str
updated_by: str
class serenity_types.account.core.SourcePlatform(*, platformType: SourcePlatformType, platformId: UUID, displayName: str, xref: str, providerId: UUID, providerName: str, tags: dict | None = None)[source]

Bases: CamelModel

The platform where user’s position can be retrieved, such as a central exchange, wallet in blockchain, custodian, etc.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

display_name: str

Human-friendly name for this platform, e.g. Binance, Coinbase Prime, Ethereum.

platform_id: UUID

Unique ID for this platform.

platform_type: SourcePlatformType

The source platform type, e.g an exchange, wallet in blockchain or other types.

provider_id: UUID

Unique ID for the provider of a platform.

provider_name: str

The literal name of the provider of a platform.

tags: dict | None

Additional custom attributes that provide extra information beyond the default fields.

xref: str

The reference used to determine the internal connectors to use.

class serenity_types.account.core.SourcePlatformType(value)[source]

Bases: Enum

Enum classifying the source platform type, e.g. a central exchange, a digital wallet, etc.

CUSTODIAN = 'CUSTODIAN'

Represents an account in a custodian.

CUSTODY_PROVIDER = 'CUSTODY_PROVIDER'

Represents an account in a custody provider.

EXCHANGE = 'EXCHANGE'

Represents an account in an exchange.

OTHER = 'OTHER'

Other type that is not available in the predefined list.

WALLET = 'WALLET'

Represents a wallet address in an blockchain.

serenity_types.catalog.model

class serenity_types.catalog.model.Model(*, modelId: UUID, modelClassId: UUID, shortName: str, displayName: str, description: str)[source]

Bases: CamelModel

A risk model or other model built into Serenity. In general Models correspond to a single implementation in code, potentially with multiple parameterizations represented by several ModelConfiguration entries.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

description: str

A longer, human-readable description suitable for tooltips and docs.

display_name: str

A human-readable name suitable for labels, like Serenity Factor Risk Model.

model_class_id: UUID

Unique ID for the parent ModelClass.

model_id: UUID

Unique ID for this particular model.

short_name: str

A structured name suitable for lookup keys, like risk.factor.regression.slm.

class serenity_types.catalog.model.ModelClass(*, modelClassId: UUID, shortName: str, displayName: str, description: str)[source]

Bases: CamelModel

A group of related models, like all VaR models.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

description: str

A longer, human-readable description suitable for tooltips and docs.

display_name: str

A human-readable name suitable for labels, like Market Risk.

model_class_id: UUID

Unique ID for this class of models.

short_name: str

A structured name suitable for lookup keys, like risk.market.

class serenity_types.catalog.model.ModelConfiguration(*, modelConfigId: UUID, modelId: UUID, modelStatus: ModelStatus, shortName: str, displayName: str, description: str, version: str, deploymentDate: date, trainingDate: date, codeVersion: str, dataParameters: Dict[str, Json], modelParameters: Dict[str, Json])[source]

Bases: CamelModel

A parameterizxation of a Model, e.g. the short, medium and long time horizon variations of a factor risk model.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

code_version: str

A GitHub commit ID, tag or other means to uniquely identify the code.

data_parameters: Dict[str, Json]

A set of name-value pairs characterizing input data.

deployment_date: date

UTC date when the config was last deployed.

description: str

A longer, human-readable description suitable for tooltips and docs.

display_name: str

A human-readable name suitable for labels, like Parametric VaR Model (Normal).

model_config_id: UUID

Unique ID for this specific model version and parameterization.

model_id: UUID

Unique ID for the parent Model.

model_parameters: Dict[str, Json]

A set of name-value pairs parameterizing the model.

model_status: ModelStatus

Current status of this model, e.g. RECOMMENDED or EXPERIMENTAL.

short_name: str

A structured name suitable for lookup keys, like risk.var.parametric.normal.

training_date: date

UTC date for as-of date of training data used.

version: str

Version number, by convention following SemVer conventions.

class serenity_types.catalog.model.ModelConfigurationSummary(*, modelConfigId: UUID, modelId: UUID, modelStatus: ModelStatus, shortName: str, displayName: str, description: str)[source]

Bases: CamelModel

Summary of a particular available model configuration, suitable for external use.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

description: str

A longer, human-readable description suitable for tooltips and docs.

display_name: str

A human-readable name suitable for labels, like Parametric VaR Model (Normal).

model_config_id: UUID

Unique ID for this specific model version and parameterization.

model_id: UUID

Unique ID for the parent Model.

model_status: ModelStatus

Current status of this model, e.g. RECOMMENDED or EXPERIMENTAL.

short_name: str

A structured name suitable for lookup keys, like risk.var.parametric.normal.

class serenity_types.catalog.model.ModelStatus(value)[source]

Bases: Enum

An enumeration.

DEPRECATED = 'DEPRECATED'

No longer supported model kept in database for historical use only.

EXPERIMENTAL = 'EXPERIMENTAL'

Current experiment which may be promoted in a coming release; for testing only.

RECOMMENDED = 'RECOMMENDED'

Production-grade and recommended for use.

serenity_types.counterparty.custody

class serenity_types.counterparty.custody.CustodyProviderType(value)[source]

Bases: Enum

High-level classification of custody providers. This is the entry point for assessing counterparty risk: within each bucket there can be a finer-grained rating of the risk, so you can have a low- or high-risk exchange or smart contract and also distinguish between the risk of self-custody vs. custody at a qualified custodian at a higher level.

EXCHANGE_WALLET = 'EXCHANGE_WALLET'

An exchange hot wallet.

INSTITUTIONAL_CUSTODIAN = 'INSTITUTIONAL_CUSTODIAN'

An independent, institutional-grade custodian like Copper, but not a QC.

MANAGED_SELF_CUSTODY = 'MANAGED_SELF_CUSTODY'

A policy-managed MPC wallet, e.g. Fireblocks.

MANUAL = 'MANUAL'

Manually created balances / positions.

QUALIFIED_CUSTODIAN = 'QUALIFIED_CUSTODIAN'

A regulated qualified custodian, e.g. Standard Custody or BitGo.

SELF_CUSTODY = 'SELF_CUSTODY'

A simple token balance in a wallet, possibly multi-sign like Gnosis Safe.

SMART_CONTRACT_LOCK = 'SMART_CONTRACT_LOCK'

Balances locked / escrowed in a smart contract

class serenity_types.counterparty.custody.CustodySource(*, custodyType: CustodyProviderType, providerId: UUID | None = None, connectorId: UUID | None = None, accountId: UUID | None = None, providerName: str, accountName: str)[source]

Bases: CamelModel

Represents a custody source for a counterparty.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_id: UUID | None

The ID of the custody account.

account_name: str

The name of the custody account.

connector_id: UUID | None

The ID of the connector.

custody_type: CustodyProviderType

The type of custody provider.

provider_id: UUID | None

The ID of the custody provider.

provider_name: str

The name of the custody provider.

serenity_types.ledger.balance

class serenity_types.ledger.balance.Balance(*, quantity: float, assetId: UUID, accountId: UUID | None = None)[source]

Bases: CamelModel

The asset held in the portfolio at a specific point in time

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_id: UUID | None

Unique identifier of the account for transaction information.

asset_id: UUID

Unique identifier of the asset from Serenity’s asset master database.

quantity: float

The number of tokens, shares, contracts, etc. held in this position. If positive this indicates a long position; if negative, a short one.

serenity_types.portfolio.core

class serenity_types.portfolio.core.AssetPosition(*, assetId: UUID, quantity: float)[source]

Bases: CamelModel

A simple representation of holding a certain amount of a given asset. This is going to be replaced with a much more flexible Portfolio representation in Q1’23.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

Unique identifier of the asset from Serenity’s asset master database.

quantity: float

The number of tokens, shares, contracts, etc. held in this position. If positive this indicates a long position; if negative, a short one.

class serenity_types.portfolio.core.NetDeltaPortfolioPositions(*, originalAssetPositions: List[AssetPosition], netDeltaAssetPositions: List[AssetPosition])[source]

Bases: CamelModel

Representing the ‘before’ and ‘after’ AssetPositions of a net-delta converted portfolio’s positions.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

net_delta_asset_positions: List[AssetPosition]

The result of net-delta conversion AssetPosition.

original_asset_positions: List[AssetPosition]

The original AssetPosition specified by user - before net-delta conversion.

class serenity_types.portfolio.core.PortfolioMetadata(*, metadataId: UUID, name: str, owner: str, version: int, updatedBy: str, updatedAt: datetime, baseCurrencyId: UUID | None = None, strategy: Strategy | None = None, accountIds: List[UUID] | None = None, tags: List[str] | None = None)[source]

Bases: CamelModel

Metadata that are typically part of a portfolio

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_ids: List[UUID] | None

The authoritative sources for transaction information.

base_currency_id: UUID | None

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD. Defaults to USD if it’s not provided.

metadata_id: UUID

Unique and immutable ID.

name: str

A descriptive name for this portfolio.

owner: str

The primary owner of this portfolio.

strategy: Strategy | None

The general approach to investing and managing the portfolio.

tags: List[str] | None

Custom tags for the purpose of searching and filtering.

updated_at: datetime

Last update timestamp, in UTC.

updated_by: str

Last update user.

version: int

Monotonically increasing version number.

class serenity_types.portfolio.core.PortfolioMetadataBaseRequest(*, name: str, owner: str, updatedBy: str, baseCurrencyId: UUID | None = None, strategy: Strategy | None = None, accountIds: List[UUID] | None = None, tags: List[str] | None = None)[source]

Bases: CamelModel

The portfolio metadata base request class

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_ids: List[UUID] | None

The authoritative sources for transaction information.

base_currency_id: UUID | None

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD. Defaults to USD if it’s not provided.

name: str

A descriptive name for this portfolio.

owner: str

The primary owner of this portfolio.

strategy: Strategy | None

The general approach to investing and managing the portfolio.

tags: List[str] | None

Custom tags for the purpose of searching and filtering.

updated_by: str

Last update user.

class serenity_types.portfolio.core.PortfolioMetadataCreateRequest(*, name: str, owner: str, updatedBy: str, baseCurrencyId: UUID | None = None, strategy: Strategy | None = None, accountIds: List[UUID] | None = None, tags: List[str] | None = None)[source]

Bases: PortfolioMetadataBaseRequest

Input for the create request

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_ids: List[UUID] | None

The authoritative sources for transaction information.

base_currency_id: UUID | None

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD. Defaults to USD if it’s not provided.

name: str

A descriptive name for this portfolio.

owner: str

The primary owner of this portfolio.

strategy: Strategy | None

The general approach to investing and managing the portfolio.

tags: List[str] | None

Custom tags for the purpose of searching and filtering.

updated_by: str

Last update user.

class serenity_types.portfolio.core.PortfolioMetadataUpdateRequest(*, name: str, owner: str, updatedBy: str, baseCurrencyId: UUID | None = None, strategy: Strategy | None = None, accountIds: List[UUID] | None = None, tags: List[str] | None = None)[source]

Bases: PortfolioMetadataBaseRequest

Input for the update request

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_ids: List[UUID] | None

The authoritative sources for transaction information.

base_currency_id: UUID | None

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD. Defaults to USD if it’s not provided.

name: str

A descriptive name for this portfolio.

owner: str

The primary owner of this portfolio.

strategy: Strategy | None

The general approach to investing and managing the portfolio.

tags: List[str] | None

Custom tags for the purpose of searching and filtering.

updated_by: str

Last update user.

class serenity_types.portfolio.core.PortfolioSnapshot(*, snapshotId: UUID, version: int, updatedBy: str, updatedAt: datetime, portfolioMetadataId: UUID, asOfTime: datetime, balances: List[Balance], unsupportedAssets: List[UnsupportedAsset] | None = None)[source]

Bases: CamelModel

Snapshot of the positions of a portfolio at a specific point in time.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

The specific point in time for the portfolio snapshot.

balances: List[Balance]

The positions/balances for the portfolio snapshot at a specific point in time.

portfolio_metadata_id: UUID

The metadata that this portfolio snapshot is part of.

snapshot_id: UUID

Unique and immutable ID.

unsupported_assets: List[UnsupportedAsset] | None

The unsupported assets for the portfolio snapshot at a specific point in time.

updated_at: datetime

Last update timestamp, in UTC.

updated_by: str

Last update user.

version: int

Monotonically increasing version number.

class serenity_types.portfolio.core.PortfolioSnapshotBaseRequest(*, portfolioMetadataId: UUID, asOfTime: datetime, balances: List[Balance], unsupportedAssets: List[UnsupportedAsset] | None = None, updatedBy: str)[source]

Bases: CamelModel

The portfolio snapshot base request class

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

The specific point in time for the portfolio snapshot.

balances: List[Balance]

The positions/balances for the portfolio snapshot at a specific point in time.

portfolio_metadata_id: UUID

The metadata that this portfolio snapshot is part of.

unsupported_assets: List[UnsupportedAsset] | None

The unsupported assets for the portfolio snapshot at a specific point in time.

updated_by: str

Last update user.

class serenity_types.portfolio.core.PortfolioSnapshotCreateRequest(*, portfolioMetadataId: UUID, asOfTime: datetime, balances: List[Balance], unsupportedAssets: List[UnsupportedAsset] | None = None, updatedBy: str)[source]

Bases: PortfolioSnapshotBaseRequest

Input for the create request

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

The specific point in time for the portfolio snapshot.

balances: List[Balance]

The positions/balances for the portfolio snapshot at a specific point in time.

portfolio_metadata_id: UUID

The metadata that this portfolio snapshot is part of.

unsupported_assets: List[UnsupportedAsset] | None

The unsupported assets for the portfolio snapshot at a specific point in time.

updated_by: str

Last update user.

class serenity_types.portfolio.core.PortfolioSnapshotUpdateRequest(*, portfolioMetadataId: UUID, asOfTime: datetime, balances: List[Balance], unsupportedAssets: List[UnsupportedAsset] | None = None, updatedBy: str)[source]

Bases: PortfolioSnapshotBaseRequest

Input for the update request

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

The specific point in time for the portfolio snapshot.

balances: List[Balance]

The positions/balances for the portfolio snapshot at a specific point in time.

portfolio_metadata_id: UUID

The metadata that this portfolio snapshot is part of.

unsupported_assets: List[UnsupportedAsset] | None

The unsupported assets for the portfolio snapshot at a specific point in time.

updated_by: str

Last update user.

class serenity_types.portfolio.core.SimplePortfolio(*, portfolioId: UUID, baseCurrencyId: UUID, portfolioName: str, portfolioManager: str, assetPositions: List[AssetPosition])[source]

Bases: CamelModel

A simple portfolio representation that just maps the positions to positive or negative quantities for long and short. There is no history, detail on custody or any other context.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_positions: List[AssetPosition]

List of positions in the portfolio.

base_currency_id: UUID

Asset ID of the base currency for this portfolio.

classmethod merge_duplicated_asset_positions(values)[source]
portfolio_id: UUID

Unique ID; in the initial implementation this is assigned locally in a client installation-hosted database.

portfolio_manager: str

In the initial implementation, a text field for the PM; eventually will link to user ID in the database.

portfolio_name: str

Descriptive name for this portfolio, for display only.

class serenity_types.portfolio.core.Strategy(*, strategyType: StrategyType, description: str | None = None)[source]

Bases: CamelModel

The general approach to investing and managing the portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

description: str | None

The description of the strategy.

strategy_type: StrategyType

The strategy an investor follows when making investment decisions.

class serenity_types.portfolio.core.StrategyType(value)[source]

Bases: Enum

The strategy an investor follows when making investment decisions.

ARBITRAGE = 'ARBITRAGE'

Exploit pricing inefficiencies in the market.

EVENT_DRIVEN = 'EVENT_DRIVEN'

Specific events or catalysts that are expected to have an impact on the price.

INDEX = 'INDEX'

An index strategy is to match the returns of the underlying index.

LONG_ONLY = 'LONG_ONLY'

Long positions only.

LONG_SHORT = 'LONG_SHORT'

Takes both long and short positions in securities simultaneously.

MARKET_NEUTRAL = 'MARKET_NEUTRAL'

Aim to achieve returns that are independent of market movements.

OTHER = 'OTHER'

Other strategy type that is not available in the predefined list.

QUANT_SYSTEMATIC = 'QUANT_SYSTEMATIC'

Using computer-based algorithms and mathematical models to analyze and trade in the market.

SHORT_ONLY = 'SHORT_ONLY'

Shorting positions only.

serenity_types.pricing.derivatives.options.valuation

class serenity_types.pricing.derivatives.options.valuation.AssetValuation(*, valuationId: str | None = None, assetId: UUID | None = None, assetType: AssetType | None = None, qty: float | None = 1.0, ratio: PositiveFloat | None = None)[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID | None

Look up all token or contract economics based on the unique ID of a specific asset.

asset_type: AssetType | None

Type of asset being valued. For option valuation, defaults to LISTED_OPTION if based on asset ID, otherwise defaults to OTC_OPTION.

classmethod check_ratio_vs_qty(ratio, values)[source]
qty: float | None

Number of tokens or contracts. You will get unit notional for listed derivatives if you take the default number of contracts here. Positive values are long; negeative values are short.

ratio: PositiveFloat | None

If pricing based on ratios, set this value to the multiplier to use for this leg.

valuation_id: str | None

Correlation ID to use for this requested valuation. If pricing based on a listed contract or a token asset, by convention the unique ID or symbol of that option should be used.

class serenity_types.pricing.derivatives.options.valuation.FutureLegValuationResult(*, valuationId: str, pv: float, notionalValue: float, spotPrice: float, spotBasis: float)[source]

Bases: LegValuationResult

Valuation result for a future asset leg.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

spot_basis: float

Computed spot basis for this valuation.

spot_price: float

Input spot price for this valuation.

class serenity_types.pricing.derivatives.options.valuation.LegValuationResult(*, valuationId: str, pv: float, notionalValue: float)[source]

Bases: CamelModel

Base class with shared fields for leg-level valuations.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

notional_value: float

The base currency notional of the strategy position. For vanilla derivatives, this is based on the spot notional value: number of contracts (qty) X spot_price X contract_size.

pv: float

Present value (PV) a.k.a. theoretical price or theo. In the case of linear products this is just price.

valuation_id: str

Correlation ID for the original LegValuation. By convention this should be a random UUID but it can also be a meaningful label like “Leg 1” or something similar.

class serenity_types.pricing.derivatives.options.valuation.MarketDataOverride(*, replacement: PositiveFloat | None = None, additiveBump: float | None = None)[source]

Bases: CamelModel

Helper type for representing replacements and bumps for market data inputs in pricing.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

additive_bump: float | None

A value (potentially negative) to add the observed value from stored or live market data.

classmethod check_bump_or_replace_but_not_both(replacement, values)[source]
replacement: PositiveFloat | None

Replacement value for the given market data point.

class serenity_types.pricing.derivatives.options.valuation.OptionValuation(*, valuationId: str | None = None, assetId: UUID | None = None, assetType: AssetType | None = None, qty: float | None = 1.0, ratio: PositiveFloat | None = None, optionValuationId: str | None = None, optionAssetId: UUID | None = None, underlierAssetId: UUID | None = None, strike: PositiveFloat | None = None, expiry: datetime | None = None, optionType: OptionType | None = None, optionStyle: OptionStyle | None = OptionStyle.EUROPEAN, contractSize: PositiveFloat | None = None, impliedVolOverride: MarketDataOverride | None = None, spotPriceOverride: MarketDataOverride | None = None)[source]

Bases: AssetValuation

A collection of option economics and market data overrides used to describe a single option valuation requested from the service. This is intentionally meant to support both listed contract pricing and more general pricing of option economics. For market data, everything is defaulted, but the client can override or bump (shift) any of the inputs to get the exact pricing scenario desired.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_asset_type_vs_asset_id(values)[source]
classmethod check_option_asset_id_vs_asset_id(option_asset_id, values)[source]
classmethod check_option_valuation_id_vs_valuation_id(option_valuation_id, values)[source]
contract_size: PositiveFloat | None

For scaling purposes, the # of underlying per contract. Not required if optionAssetId provided, otherwise it’s loaded from the contract specification in the database.

expiry: datetime | None

Expiration expressed in absolute terms as a date/time. Not required if optionAssetId provided

implied_vol_override: MarketDataOverride | None

Replace or modify the stored volatility surface’s IV for this option.

option_asset_id: UUID | None

Look up all option economics based on the unique ID of a specific listed option contract.

option_style: OptionStyle | None

The variety of option being priced. Not required if optionAssetId provided. Our pricer only supports EUROPEAN at this time, so defaults accordingly.

option_type: OptionType | None

Whether we are pricing a PUT or CALL option. Not required if optionAssetId provided.

option_valuation_id: str | None

Correlation ID to use for this requested option valuation. If pricing based on a listed contract with optionAssetId, by convention the unique ID or symbol of that option should be used.

spot_price_override: MarketDataOverride | None

Replace or modify the stored or observed spot price used when pricing this option.

strike: PositiveFloat | None

Absolute value of the strike. Not required if optionAssetId provided. In future we may wish to support different StrikeType representations here, but some cases (like DELTA) are potentially trickier, so not for initial version.

underlier_asset_id: UUID | None

Serenity asset identifier of the underlier, e.g. BTC (tok.btc.bitcoin). Not required if optionAssetId provided. Note we will be switching to the Exposure UUID instead in a future release (e.g. tok.btc), once the reference data is available.

class serenity_types.pricing.derivatives.options.valuation.OptionValuationRequest(*, asOfTime: datetime | None = None, modelConfigId: UUID | None = None, baseCurrencyId: UUID | None = None, discountingMethod: DiscountingMethod | None = DiscountingMethod.SELF_DISCOUNTING, projectionMethod: ProjectionMethod | None = None, volSurfaceId: UUID | None = None, volSurface: InterpolatedVolatilitySurface | None = None, discountingCurveOverride: YieldCurveOverride | None = None, projectionCurveOverride: YieldCurveOverride | None = None, volModel: VolModel | None = VolModel.SVI, strikeType: StrikeType | None = StrikeType.LOG_MONEYNESS, options: List[OptionValuation])[source]

Bases: ValuationRequest

A batch request to run one or more option valuations using a single model configuration and base set of curves and the vol surface. Reasonable defaults will be provided for any missing inputs, e.g. if you price a set of Deribit BTC options, the latest BTC volatility surface will be used along with the latest discounting curves for BTC and USD. Note that because the request only references a single volatility surface this means all included options must have the same underlier as the one in VolatilitySurfaceVersion.interpolated.definition.underlier_asset_id.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_non_empty_options_list(options, values)[source]
options: List[OptionValuation]

The full set of option valuations to run with the given market data inputs. The client may provide individual overrides or bumps for all inputs as part of each valuation object.

class serenity_types.pricing.derivatives.options.valuation.OptionValuationResult(*, valuationId: str, pv: float, notionalValue: float, optionValuationId: str, volModel: VolModel, iv: float, spotNotional: float, spotPrice: float, forwardPrice: float, projectionRate: float, discountingRate: float, delta: float, deltaQty: float, deltaQtyExposure: float, deltaCcy: float, deltaCcyExposure: float, gamma: float, gammaCcy: float, gammaQty: float, vega: float, vegaCcy: float, vegaQty: float, rho: float, rhoCcy: float, rhoQty: float, theta: float, thetaCcy: float, thetaQty: float)[source]

Bases: LegValuationResult

The result of a series of option valuations based on the parameters in the OptionValuationRequest. Note that the basic calculation is just Black-Scholes, but if you provide additional information regarding the position scaling it will also provide position notional and greek exposures in base currency to allow bucketing of greeks and NAV calculations.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

delta: float

Greek output: delta, the option’s sensitivity to spot changes.

delta_ccy: float

Delta X value, a.k.a. the partial derivative of position value with respect to spot, expressed in base currency

delta_ccy_exposure: float

Delta X value, a.k.a. the partial derivative of position value with respect to spot, expressed in base currency.

delta_qty: float

Delta X qty X contract_size, the delta exposure expressed in qty of underlying.

delta_qty_exposure: float

Delta X value, a.k.a. the partial derivative of position value with respect to spot, expressed in underlying (coin notional).

discounting_rate: float

The discounting rate used when computing the forward; equal to projection_rate with SELF_DISCOUNTING.

forward_price: float

Input forward price for this valuation.

gamma: float

Greek output: gamma, the delta’s sensitivity to spot changes.

gamma_ccy: float

Gamma X value^2, a.k.a. the second derivative of position value with respect to spot, expressed in base currency.

gamma_qty: float

Gamma X value^2, a.k.a. the second derivative of position value with respect to spot, expressed in underlying (coin notional).

iv: float

Implied volatility (IV)

option_valuation_id: str

Correlation ID for the original OptionValuation.

projection_rate: float

The projection rate used when computing the forward.

rho: float

Greek output: rho, the delta’s sensitivity to interest rate changes.

rho_ccy: float

Partial derivative of the spot notional value of the contract with respect to rho X 1bp, expressed in base currency.

rho_qty: float

Partial derivative of the spot notional value of the contract with respect to rho X 1bp, expressed in underlying (coin notional).

spot_notional: float

The base currency notional of the position: number of contracts (qty) X spot_price X contract_size.

spot_price: float

Input spot price for this valuation.

theta: float

Greek output: theta, the delta’s sensitivity to time decay.

theta_ccy: float

Partial derivative of the spot notional value of the contract with respect to theta X 1 day, expressed in base currency.

theta_qty: float

Partial derivative of the spot notional value of the contract with respect to theta X 1 day, expressed in underlying (coin notional).

vega: float

Greek output: vega, the option’s sensitivity to volatility changes.

vega_ccy: float

Partial derivative of the position value of the contract with respect to vega X 1%, expressed in base currency.

vega_qty: float

Partial derivative of the position value of the contract with respect to vega X 1%, expressed in underlying (coin notional).

vol_model: VolModel

The specific volatility model used; as SVI calibrations yield different greeks, this needs to be explicit.

class serenity_types.pricing.derivatives.options.valuation.PerpetualLegValuationResult(*, valuationId: str, pv: float, notionalValue: float, spotPrice: float, spotBasis: float, fundingRate: float)[source]

Bases: FutureLegValuationResult

Valuation result for a perp (swap) asset leg.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

funding_rate: float

Exchange funding rate at the time of valuation.

class serenity_types.pricing.derivatives.options.valuation.StrategyValuationRequest(*, asOfTime: datetime | None = None, modelConfigId: UUID | None = None, baseCurrencyId: UUID | None = None, discountingMethod: DiscountingMethod | None = DiscountingMethod.SELF_DISCOUNTING, projectionMethod: ProjectionMethod | None = None, volSurfaceId: UUID | None = None, volSurface: InterpolatedVolatilitySurface | None = None, discountingCurveOverride: YieldCurveOverride | None = None, projectionCurveOverride: YieldCurveOverride | None = None, volModel: VolModel | None = VolModel.SVI, strikeType: StrikeType | None = StrikeType.LOG_MONEYNESS, qty: int | None = 1, legs: List[OptionValuation])[source]

Bases: ValuationRequest

The full set of leg valuations to run with the given market data inputs.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_non_empty_leg_list(legs, values)[source]
legs: List[OptionValuation]

A list of leg-level asset valuations.

qty: int | None

Number of strategies. If leg ratios are provided, this will be used as a multipler, e.g. if you have a 10:1 combo with 10 tokens and 1 option contract and strategy-level qty is 3, you would value based on 30 tokens and 3 option contracts.

class serenity_types.pricing.derivatives.options.valuation.StrategyValuationRequestBatch(*, batchRequests: List[StrategyValuationRequest])[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

batch_requests: List[StrategyValuationRequest]
class serenity_types.pricing.derivatives.options.valuation.StrategyValuationResult(*, pv: float, deltaQty: float, deltaCcy: float, gammaQty: float, gammaCcy: float, vegaQty: float, vegaCcy: float, rhoQty: float, rhoCcy: float, thetaQty: float, thetaCcy: float, legResults: List[OptionValuationResult])[source]

Bases: CamelModel

Value of a multi-leg strategy: both top-level, and per-leg.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

delta_ccy: float

Sum of leg-level delta_ccy’s

delta_qty: float

Sum of leg-level delta_qty’s

gamma_ccy: float

Sum of leg-level gamma_ccy’s

gamma_qty: float

Sum of leg-level gamma_qty’s

leg_results: List[OptionValuationResult]

Per-leg valuation results, e.g. the individual option values and greeks.

pv: float

The sum of the present values of the strategy legs, i.e. the theoretical strategy value.

rho_ccy: float

Sum of leg-level rho_ccy’s, ignoring leg-level differences in expiries

rho_qty: float

Sum of leg-level rho_qty’s

theta_ccy: float

Sum of leg-level theta_ccy’s

theta_qty: float

Sum of leg-level theta_qty’s

vega_ccy: float

Sum of leg-level vega_ccy’s, ignoring leg-level differences in expiries and strikes

vega_qty: float

Sum of leg-level vega_qty’s

class serenity_types.pricing.derivatives.options.valuation.StrategyValuationResultBatch(*, batchResults: List[StrategyValuationResult])[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

batch_results: List[StrategyValuationResult]
class serenity_types.pricing.derivatives.options.valuation.TokenLegValuationResult(*, valuationId: str, pv: float, notionalValue: float)[source]

Bases: LegValuationResult

Valuation result for a token (spot) asset leg.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

notional_value: float

The base currency notional of the strategy position. For vanilla derivatives, this is based on the spot notional value: number of contracts (qty) X spot_price X contract_size.

pv: float

Present value (PV) a.k.a. theoretical price or theo. In the case of linear products this is just price.

valuation_id: str

Correlation ID for the original LegValuation. By convention this should be a random UUID but it can also be a meaningful label like “Leg 1” or something similar.

class serenity_types.pricing.derivatives.options.valuation.ValuationRequest(*, asOfTime: datetime | None = None, modelConfigId: UUID | None = None, baseCurrencyId: UUID | None = None, discountingMethod: DiscountingMethod | None = DiscountingMethod.SELF_DISCOUNTING, projectionMethod: ProjectionMethod | None = None, volSurfaceId: UUID | None = None, volSurface: InterpolatedVolatilitySurface | None = None, discountingCurveOverride: YieldCurveOverride | None = None, projectionCurveOverride: YieldCurveOverride | None = None, volModel: VolModel | None = VolModel.SVI, strikeType: StrikeType | None = StrikeType.LOG_MONEYNESS)[source]

Bases: CamelModel

Base class for batch requests for valuations of either a portfolio of options or for a multi-leg strategy.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime | None

The as-of time to use for loading all marketdata, surfaces, yield curves and refdata from the database. Defaults to the latest up to this time.

base_currency_id: UUID | None

Base currency to use for expressing all notional values. Defaults to USD.

classmethod check_historical_mode_projection_method(projection_method, values)[source]
classmethod check_vol_surface_id_or_vol_surface(vol_surface, values)[source]
discounting_curve_override: YieldCurveOverride | None

Various forms of modifications to the discounting curve: choosing a variant in the database; passing in a complete curve by value; and/or replacing or shifting the extracted rate.

discounting_method: DiscountingMethod | None

How to derive the discount rate: from the projection rate (self-discounting), or from pre-built discounting curves either provided in API or loaded from the system. Defaults to self-discounting.

model_config_id: UUID | None

The specific derivatives analytics model configuration to load; this is used to drive defaults. Defaults to system’s recommended config.

projection_curve_override: YieldCurveOverride | None

Various forms of modifications to the projection curve: choosing a variant in the database; passing in a complete curve by value; and/or replacing or shifting the extracted rate.

projection_method: ProjectionMethod | None

How to derive the projection rate when in real-time mode: from live futures prices, or from a curve. The default depends on as_of_time. In the case of as_of_time being None the system runs in real-time pricing mode and uses ProjectionMode.FUTURES. When as_of_time is provided the system runs in historical pricing mode and defaults to ProjectionMode.CURVE. Setting both as_of_time and ProjectionMode.FUTURES will yield a validation error from the API.

strike_type: StrikeType | None

The strike representation. Defaults to log-moneyness.

vol_model: VolModel | None

The volatility model used for valuation purposes. Defaults to SVI.

vol_surface: InterpolatedVolatilitySurface | None

The optional client-provided volatility surface to use. If the client provides neither a VS ID nor their own volatility surface, the system will load the default for the underlying as-of the as_of_time.

vol_surface_id: UUID | None

The optional unique ID of the surface to load, latest version as-of the as_of_time.

class serenity_types.pricing.derivatives.options.valuation.YieldCurveOverride(*, yieldCurveId: UUID | None = None, yieldCurve: InterpolatedYieldCurve | None = None, rateOverride: MarketDataOverride | None = None)[source]

Bases: CamelModel

Helper for representing explicitly either override by UUID (load that YieldCurveDefinition from the database for the appropriate as_of_time) or by value. The client can also specify mutations to make to this input market data. In the case where you want to replace the rate entirely do not specify either yield_curve_id or yield_curve; in the case where you want to do a shift of the yield curve, specify either ID or curve and then an additive_bump. Everything null or both yield_curve_id and yield_curve specified yields validation errors.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_yield_curve_ids_or_yield_curve(yield_curve, values)[source]
rate_override: MarketDataOverride | None

Optionally modifies the input data. Note properly you should not need to both provide a yield_curve and modify it, but in case clients want to play back our stored yield_curve via API without having to mutate the curve themselves, it could make sense.

yield_curve: InterpolatedYieldCurve | None

Optionally specifies a supported yield curve bootstrapped by the client or loaded separately. Not every definition is accepted, e.g. you cannot pass in a CurveUsage.PROJECTION curve for discounting.

yield_curve_id: UUID | None

Optionally specifies a supported YieldCurveDefinition UUID from the database. Not every definition is accepted, e.g. you cannot pass in a CurveUsage.PROJECTION curve for discounting.

serenity_types.pricing.derivatives.options.volsurface

class serenity_types.pricing.derivatives.options.volsurface.Axis(value)[source]

Bases: Enum

Enumeration of the X, Y axes for the surface.

STRIKE = 'STRIKE'

Slice range denotes start and end strikes according to the surface type, e.g. log moneyness or absolute strike.

TIME_TO_EXPIRY = 'TIME_TO_EXPIRY'

Slice range denotes start and end time to expiry as a year fraction.

class serenity_types.pricing.derivatives.options.volsurface.DiscountingMethod(value)[source]

Bases: Enum

The strategy to use for deriving the discount rate, i.e. the assumed interest rate to use when discounting prices to present.

CURVE = 'CURVE'

Extract a discount factor from discount curves, either provided via API or loaded from database.

SELF_DISCOUNTING = 'SELF_DISCOUNTING'

Use the base asset’s projection rate as the discount rate instead of a discount curve. This is the default, and the option you should choose if you want to reproduce the Deribit forward pricing model.

class serenity_types.pricing.derivatives.options.volsurface.InterpolatedVolatilitySurface(*, definition: VolatilitySurfaceDefinition, strikes: List[float], timeToExpiries: List[float], vols: List[float], inputParams: Dict[str, object], calibrationParams: Dict[float, Dict[str, float]])[source]

Bases: CamelModel

A calibrated volatility surface with a dense grid of fitted vols. Each array is of equal length and corresponds to (x, y, z) for the mesh.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

calibration_params: Dict[float, Dict[str, float]]

Informational set of calibration parameters, e.g. the SVI parameters. Keying is time_to_expiry expressed in year fractions to parameter set, where the parameter keys are VolModel-specific.

definition: VolatilitySurfaceDefinition

The unique set of parameters used to calibrate / fit this surface.

input_params: Dict[str, object]

Informational set of input parameters, e.g. yield curves used for the forward. May be empty and keys will depend on the configuration, e.g. DiscountingType.

strikes: List[float]

All strikes expressed as log-money values, the x-axis in the mesh.

time_to_expiries: List[float]

All times to expiry expressed as year fractions, the y-axis in the mesh.

vols: List[float]

All fitted vols, the z-axis in the mesh.

class serenity_types.pricing.derivatives.options.volsurface.PillarDate(value)[source]

Bases: Enum

A standard time-to-expiry. Use for drop-downs to select slices for Axis.TIME_TO_EXPIRY.

label: str

Display label to use: 1D, 1W, 1M, 3M, 6M, 1Y.

time_to_expiry: float

Relative date expressed as a year fraction.

class serenity_types.pricing.derivatives.options.volsurface.ProjectionMethod(value)[source]

Bases: Enum

The strategy to use for deriving the projection rates, i.e. the forward interest rates.

CURVE = 'CURVE'

Projection rate is extracted from a projection curve, either provided via API or loaded from database. This option is respected in both real-time pricing and historical pricing modes, though in real-time the curve version loaded is always the very latest. Select CURVE if you want a more stable forward.

FUTURES = 'FUTURES'

Projection rate is snapped from the corresponding Deribit futures prices; this option is only supported in real-time pricing mode. Select FUTURES if in real-time you want to reproduce Deribit forward pricing model and incorporate up-to-the-moment market view on the forward.

class serenity_types.pricing.derivatives.options.volsurface.RawVolatilitySurface(*, strikeType: StrikeType, spotPrice: float, volPoints: List[VolPoint])[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

spot_price: float

The observed spot price that went into the IV calculations.

strike_type: StrikeType

Strike representation used for this surface, e.g. ABSOLUTE or LOG_MONEYNESS.

vol_points: List[VolPoint]

The discrete IV points available for fitting as a volatility surface.

class serenity_types.pricing.derivatives.options.volsurface.Slice(*, volSurfaceId: UUID, asOfTime: datetime, specification: SliceSpecification, values: List[float], vols: List[float])[source]

Bases: CamelModel

A slice from a 3D volatility surface to show the volatility smile at a particular time-to-expiry or strike.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

As-of time for the particular volatility surface version that was sliced.

specification: SliceSpecification

Associated specification for this slice: where the slice was made.

values: List[float]

List of times to expiry or strikes, depending on SliceSpecification.

vol_surface_id: UUID

The specific combination of parameters (VolModel, etc.) retrieved from the database.

vols: List[float]

List of corresponding IV values for the given times or strikes.

class serenity_types.pricing.derivatives.options.volsurface.SliceRequest(*, surfaces: VolatilitySurfaceVersionRequest, slices: List[SliceSpecification])[source]

Bases: CamelModel

A request to load one or more volatility surfaces and take one or more “cuts” of the surface. This lets the front-end efficiently batch requests to get all data required for a multi-time plot of how the volatility smile evolves through time.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

slices: List[SliceSpecification]

Specification of where to slice the volatility surface version(s)., e.g. show the volatility smile at the time_to_expiry values corresponding to 1M, 3M and 6M pillar dates.

surfaces: VolatilitySurfaceVersionRequest

A specification of which volatility surfaces to load and slice.

class serenity_types.pricing.derivatives.options.volsurface.SliceSpecification(*, axis: Axis, value: float)[source]

Bases: CamelModel

Specification of a volatility surface “slice” – to extract the volatility smile along either the expiry axis or strike axis.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

axis: Axis

Axis to slice at: time-to-expiry or strike. With Axis.TIME_TO_EXPIRY, then for every strike on the surface you’ll get a 2D array of strike, IV. With Axis.STRIKE, then for every time to expiry on the surface you’ll get a 2D array of time_to_expiry, IV.

value: float

The X or Y value to position the slice on the surface.

class serenity_types.pricing.derivatives.options.volsurface.StrikeType(value)[source]

Bases: Enum

Currently supported strike representations.

ABSOLUTE = 'ABSOLUTE'

Absolute value of strike, e.g. the 20000 option.

LOG_MONEYNESS = 'LOG_MONEYNESS'

Relative value of strike vs. current spot with log transformation: log(strike / spot).

class serenity_types.pricing.derivatives.options.volsurface.VolModel(value)[source]

Bases: Enum

Currently supported volatility models.

BLACK_SCHOLES = 'BLACK_SCHOLES'

Classic Black-Scholes volatility model.

SVI = 'SVI'

Stochastic volatility (SVI) calibrated volatility model.

class serenity_types.pricing.derivatives.options.volsurface.VolPoint(*, optionAssetId: UUID, timeToExpiry: float, strikeValue: float, markPrice: float, projectionRate: float, discountingRate: float, forwardPrice: float, iv: float)[source]

Bases: CamelModel

An individual IV input point.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

discounting_rate: float

The discounting rate used when computing the forward; equal to projection_rate with SELF_DISCOUNTING, which is currently the default for our IV calculations.

forward_price: float

The computed forward price that went into the IV calculation.

iv: float

The computed implied volatility (IV) that corresponds to the given mark_price and other inputs.

mark_price: float

The observed option premium used as input to the IV calculation.

option_asset_id: UUID

The specific option that was used for vol fitting purposes.

projection_rate: float

The projection rate used when computing the forward.

strike_value: float

Value of strike for this point, unit defined by StrikeType.

time_to_expiry: float

The time to expiry for this point, expressed as a year fraction.

class serenity_types.pricing.derivatives.options.volsurface.VolatilitySurfaceAvailability(*, definition: VolatilitySurfaceDefinition, asOfTimes: List[datetime], effectiveTimes: List[EffectiveDateTime])[source]

Bases: CamelModel

Information about version availability for a given volsurface definition.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: List[datetime]

The list of all available as_of_times in the requested window.

definition: VolatilitySurfaceDefinition

Description of the particular volsurface parameters that are available to load.

effective_times: List[EffectiveDateTime]

The list of all available EffectiveDateTime in the requested window.

class serenity_types.pricing.derivatives.options.volsurface.VolatilitySurfaceDefinition(*, volSurfaceId: UUID, volModel: VolModel, strikeType: StrikeType, underlierAssetId: UUID, displayName: str)[source]

Bases: CamelModel

A uniquely-identified set of VS parameters for fitting a VolatilitySurface.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

display_name: str

Human-readable description of this curve, e.g. Deribit BTC (SVI, ABSOLUTE)

strike_type: StrikeType

Strike representation used for this surface, e.g. ABSOLUTE or LOG_MONEYNESS.

underlier_asset_id: UUID

The linked asset for this surface, e.g. for a Bitcoin volatility surface, this is BTC (tok.btc.bitcoin). Note we will be switching to the Exposure UUID instead in a future release (e.g. tok.btc), once the reference data is available.

vol_model: VolModel

Volatility model used for this surface.

vol_surface_id: UUID

Unique ID for this volatility surface’s collection of attributes; note that surfaces are re-fitted hourly, and so there are going to be many versions over time.

class serenity_types.pricing.derivatives.options.volsurface.VolatilitySurfaceVersion(*, raw: RawVolatilitySurface, interpolated: InterpolatedVolatilitySurface, asOfTime: datetime, effectiveTime: EffectiveDateTime, buildTime: datetime)[source]

Bases: CamelModel

A single version of a fitted volatility surface, with both the raw and interpolated content.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

The time window, generally top of the hour, for which we have fitted the volatility surface; latest prices as of this time are used as input to the surface calibration.

build_time: datetime

The actual time of the build; due to DQ or system issues this might be different from as_of_time.

effective_time: EffectiveDateTime

The effective time range, for which we have fitted the volatility surface; latest prices as of this time are used as input to the surface calibration.

interpolated: InterpolatedVolatilitySurface

The interpolated volatility surface.

raw: RawVolatilitySurface

The raw volatility surface inputs.

class serenity_types.pricing.derivatives.options.volsurface.VolatilitySurfaceVersionRequest(*, volSurfaceId: UUID, asOfTimes: AsOfTimeRange | List[datetime])[source]

Bases: CamelModel

A request for one or more versions of a specific volatility surface. Used for plotting on the front-end to show how the surface evolves over a narrow time window.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: AsOfTimeRange | List[datetime]

Either a start/end range of as-of times for VolatilitySurfaceVersions to retrieve, or an explicit list of as-of times to load. The combination of UUID + as-of times gives you a list of VolatilitySurfaceVersions to retrieve.

vol_surface_id: UUID

The specific combination of parameters (VolModel, etc.) that you want to retrieve from the database.

serenity_types.pricing.derivatives.rates.yield_curve

class serenity_types.pricing.derivatives.rates.yield_curve.CurvePoint(*, tenor: str | None = None, pillarDate: date | None = None, duration: float | None = None, rateSourceType: RateSourceType, rateSources: List[str] | None = None, referenceAssets: List[UUID] | None = None, markPrices: List[float] | None = None, rate: float, discountFactor: float)[source]

Bases: CamelModel

A discrete input point on the curve, with all the metadata describing what is being provided and its source to help reproduce the results.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

discount_factor: float

The input DF value, if rate not provided.

duration: float | None

The duration for this point, expressed as a year fraction.

mark_prices: List[float] | None

In the case where a DF is backed out from the implied forward of a reference asset or basket thereof, the observed prices that should go into the bootstrapping method.

pillar_date: date | None

The specific forward date for the given rate and DF, e.g. the 1W point for today would be the next business day a week ahead.

rate: float

The input rate value, if DF not provided.

rate_source_type: RateSourceType

The type of input being provided for this CurvePoint, e.g. if it’s from a 3M future, this would be FUTURE_PX, while if it’s from traditional rates fixings, it would be FIXINGS.

rate_sources: List[str] | None

The specific rate sources used, e.g. OIS, SOFR or LIBOR; for LENDING_RATE, DeFi or other sources used, e.g. CHAINLINK, IPOR or AAVE. For FUNDING_RATE this holds the UUID for the exchange Organization ID.

reference_assets: List[UUID] | None

In the case where an implied forward is backed out from market observables, the assets observed.

tenor: str | None

A relative date code, e.g. 1Y or 3M.

class serenity_types.pricing.derivatives.rates.yield_curve.CurveUsage(value)[source]

Bases: Enum

Intended usage of this curve, e.g. for discounting or for projection purposes.

DISCOUNTING = 'DISCOUNTING'

Curve points for discounting future cashflows.

PROJECTION = 'PROJECTION'

Curve points indicating the market forward view.

class serenity_types.pricing.derivatives.rates.yield_curve.InterpolatedYieldCurve(*, definition: YieldCurveDefinition, durations: List[float], rates: List[float], discountFactors: List[float])[source]

Bases: CamelModel

A term structure of rates and discount factors built from a RAW representation. This is the version that you should pass in for option valuation purposes, and is suitable for extracting rates and discount factors as well as plotting purposes.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

definition: YieldCurveDefinition

The unique set of parameters used to bootstrap this yield curve.

discount_factors: List[float]

Array of all discount factors (DF’s) along the curve.

durations: List[float]

Array of all durations along the curve, as year fractions.

rates: List[float]

Array of all interpolated rates along the curve.

class serenity_types.pricing.derivatives.rates.yield_curve.InterpolationMethod(value)[source]

Bases: Enum

Specific interpolation method used. Currently only supports flat-forward.

FLAT_FWD = 'FLAT_FWD'
class serenity_types.pricing.derivatives.rates.yield_curve.RateSourceType(value)[source]

Bases: Enum

Sources of rates & discount factors. In the most general case the yield curve can be built from multiple imports, so we tag each CurvePoint that is the input to the interpolated YC with the particular source, e.g. we might have an 8H rate at the short end from perpetual future funding rates and implied forwards backed out from calendar spreads.

FIXING = 'FIXING'

Observed traditional rate fixings.

FUNDING_RATE = 'FUNDING_RATE'

Observed exchange perpetual future funding rate.

FUTURE_PX = 'FUTURE_PX'

Implied forward backed out from observed future prices.

LENDING_RATE = 'LENDING_RATE'

Observed CeFi / OTC or DeFi lending rate.

OPTION_PX = 'OPTION_PX'

Implied forward backed out from observed option prices & spreads.

STAKING_RATE = 'STAKING_RATE'

Observed proof-of-stake protocol staking rate.

class serenity_types.pricing.derivatives.rates.yield_curve.RawYieldCurve(*, points: List[CurvePoint])[source]

Bases: CamelModel

A term structure of yield curve inputs. The RAW representation is offered to clients so they can either do their own interpolation or for diagnostics.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

points: List[CurvePoint]

The list of market data observations that went into this raw yield curve, e.g. rates, discount factors and futures prices corresponding to various tenors.

class serenity_types.pricing.derivatives.rates.yield_curve.YieldCurveAvailability(*, definition: YieldCurveDefinition, asOfTimes: List[datetime], effectiveTimes: List[EffectiveDateTime])[source]

Bases: CamelModel

Information about version availability for a given YC definition.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: List[datetime]

The list of all available as_of_times in the requested window.

definition: YieldCurveDefinition

Description of the particular yield curve parameters that are available to load.

effective_times: List[EffectiveDateTime]

The list of all available EffectiveDateTime in the requested window.

class serenity_types.pricing.derivatives.rates.yield_curve.YieldCurveDefinition(*, yieldCurveId: UUID, curveUsage: CurveUsage, interpolationMethod: InterpolationMethod, rateSourceType: RateSourceType, underlierAssetId: UUID, displayName: str)[source]

Bases: CamelModel

A uniquely-identified set of YC parameters for bootstrapping a YieldCurve.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

curve_usage: CurveUsage

The curve’s intended purpose, e.g. for discounting or representing market view on forward rates.

display_name: str

Human-readable description of this curve, e.g. OIS (FLAT_FWD)

interpolation_method: InterpolationMethod

The specific interpolator type used to bootstrap this curve.

rate_source_type: RateSourceType

The type of input being provided for this CurvePoint, e.g. if it’s from a 3M future, this would be FUTURE_PX, while if it’s from traditional rates fixings, it would be FIXINGS.

underlier_asset_id: UUID

The linked asset for this curve, e.g. for an Ethereum staking curve, this would be ETH (tok.eth.ethereum). Note we will be switching to the Exposure UUID instead in a future release (e.g. tok.eth), once the reference data is available.

yield_curve_id: UUID

Unique ID for this particular combination of yield curve attributes; note yield curves are bootstrapped daily, and so there are going to be many versions over time.

class serenity_types.pricing.derivatives.rates.yield_curve.YieldCurveVersion(*, raw: RawYieldCurve, interpolated: InterpolatedYieldCurve, asOfTime: datetime, effectiveTime: EffectiveDateTime, buildTime: datetime)[source]

Bases: CamelModel

A single version of a YieldCurveDefinition, inclusive of its raw and interpolated YC content.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

The time window, generally top of the hour, for which we have fitted the volatility surface; latest prices as of this time are used as input to the surface calibration.

build_time: datetime

The actual time of the build; due to DQ or system issues this might be different from as_of_time.

effective_time: EffectiveDateTime

The effective time range for which we have bootstrapped this yield curve; latest rates / input prices as of this time are used.

interpolated: InterpolatedYieldCurve

The bootstrapped yield curve.

raw: RawYieldCurve

The raw yield curve input.

class serenity_types.pricing.derivatives.rates.yield_curve.YieldCurveVersionRequest(*, yieldCurveId: UUID, asOfTimes: AsOfTimeRange | List[datetime])[source]

Bases: CamelModel

A request for one or more versions of a specific volatility surface. Used for plotting on the front-end to show how the surface evolves over a narrow time window.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: AsOfTimeRange | List[datetime]

Either a start/end range of as-of times for YieldCurveVersions to retrieve, or an explicit list of as-of times to load. The combination of UUID + as-of times gives you a list of YieldCurveVersions to retrieve.

yield_curve_id: UUID

Unique ID for this particular combination of yield curve attributes; note yield curves are bootstrapped daily, and so there are going to be many versions over time.

serenity_types.pricing.derivatives.rates.yield_surface

class serenity_types.pricing.derivatives.rates.yield_surface.YieldSurfaces(*, yieldSurfaceId: UUID, underlierAssetId: UUID, asOfTimes: List[datetime], projectionRates: Dict[str, List[float | None]])[source]

Bases: CamelModel

Model representing yield surfaces.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: List[datetime]

Series of timestamps corresponding to the start of each yield surfaces.

projection_rates: Dict[str, List[float | None]]

The projection rates keyed by CTM projection rates (1D, 1W, 2W, 1M, 3M, 6M, 9M, 1Y).

underlier_asset_id: UUID

The underlier asset_id for this yield surface.

yield_surface_id: UUID

Unique identifier for this yield surface.

class serenity_types.pricing.derivatives.rates.yield_surface.YieldSurfacesConfigs(*, supportedUnderlierIds: List[UUID], maxAllowedSnapshots: Dict[str, int])[source]

Bases: CamelModel

Serenity’s configurations for yield surfaces.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

max_allowed_snapshots: Dict[str, int]

The maximum allowed number of snapshots to be returned in one call.

supported_underlier_ids: List[UUID]

A list of supported underlier_asset_id.

class serenity_types.pricing.derivatives.rates.yield_surface.YieldSurfacesDatetimeRange(*, underlierAssetId: UUID, minSnapshotDatetime: datetime, maxSnapshotDatetime: datetime)[source]

Bases: CamelModel

Yield surface snapshots datetime range

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

max_snapshot_datetime: datetime

The maximum/latest snapshot datetime for this yield surface.

min_snapshot_datetime: datetime

The minimum/earliest snapshot datetime for this yield surface.

underlier_asset_id: UUID

The underlier asset_id for this yield surface, e.g. BTC (78e2e8e2-419d-4515-9b6a-3d5ff1448e89).

serenity_types.pricing.core

class serenity_types.pricing.core.AsOfTimeRange(*, startTime: datetime, endTime: datetime)[source]

Bases: CamelModel

Simple helper object that specifies a datetime range as a single object.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

end_time: datetime

End of the range, inclusive.

start_time: datetime

Start of the range, inclusive.

class serenity_types.pricing.core.CashTreatment(value)[source]

Bases: Enum

For purposes of cash positions, what counts as cash?

FIAT_ONLY = 'FIAT_ONLY'

Include only traditional currencies, e.g. USD or EUR.

FIAT_PEGGED_STABLECOINS = 'FIAT_PEGGED_STABLECOINS'

Include both fiat and fiat pegs, e.g. USD and USDT.

class serenity_types.pricing.core.EffectiveDateTime(*, asOfFromTs: datetime, asOfToTs: datetime)[source]

Bases: CamelModel

The effective datetime range of the returned batch data. None denotes realtime data.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_from_ts: datetime

Start of the bitemporal as-of time: when this data is effective from.

as_of_to_ts: datetime

End of the bitemporal as-of time: when this data is effective to.

class serenity_types.pricing.core.Interval(value)[source]

Bases: Enum

Enum for data interval.

DAILY = 'DAILY'
HOURLY = 'HOURLY'
class serenity_types.pricing.core.MarkTime(value)[source]

Bases: Enum

For purposes of closing prices in a 24x7 market, which regional market closing should be used?

HK_EOD = 'HK_EOD'

Mark prices at 4:00PM Asia/Hong_Kong.

LN_EOD = 'LN_EOD'

Mark prices at 4:30PM Europe/London.

NY_EOD = 'NY_EOD'

Mark prices at 4:30PM America/New_York.

UTC = 'UTC'

Mark prices at UTC midnight.

class serenity_types.pricing.core.PricingContext(*, asOfDate: date | None = None, asOfTime: datetime | None = None, markTime: MarkTime | None = MarkTime.UTC, baseCurrencyId: UUID | None = None, cashTreatment: CashTreatment | None = CashTreatment.FIAT_ONLY)[source]

Bases: CamelModel

Standard settings to use when doing pricing for risk calculation purposes, portfolio valuation, etc.. Generally controls which prices to select and how to convert those prices into the organization’s base currency.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_date: date | None

The date on which the portfolio was valued; default to latest date.

as_of_time: datetime | None

The datetime on which the portfolio was valued; default to latest datetime.

base_currency_id: UUID | None

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD.

cash_treatment: CashTreatment | None

What to consider to be a cash position, e.g. for NAV calcs.

mark_time: MarkTime | None

The close time convention to use for close-on-close prices in the 24x7 market.

classmethod set_as_of_time_from_as_of_date(as_of_time, values)[source]

serenity_types.refdata.asset

class serenity_types.refdata.asset.Asset(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str)[source]

Bases: CamelModel

Base class for all financial assets tracked in Serenity.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

Unique, immutable ID for this asset. Symbols can change over time, but asset ID’s are stable.

asset_status: AssetStatus

Asset status.

asset_type: AssetType

Basic classification of this asset. Based on the type, sub-classes of the Asset may carry additional details.

display_name: str

Human-readable name for this asset.

is_supported: bool

Flag to indicate if this asset is supported by Serenity.

native_symbol: str | None

Whatever is the issuer’s symbol for this asset. For tokens this is typically the token smart contract symbol or native blockchain token symbol, e.g. ETH or DAI.

symbol: str

Serenity’s unique symbol for this asset, e.g. tok.usdc.ethereum.

class serenity_types.refdata.asset.AssetSearchRequest(*, assetTypes: List[AssetType] | None = None, exchangeIds: List[UUID] | None = None, underlierAssets: List[UUID] | None = None, expiries: List[date] | None = None, strikes: List[float] | None = None, includeExpired: bool = False, offset: int | None = None, limit: ConstrainedIntValue | None = 1000)[source]

Bases: CamelModel

Request for performing a structured query of the asset database. The system may apply limits on the size of the response if the scope of the query is too large. Note at this time this query is always applied against the latest version of the asset master.

Wildcards here should be interpreted to maximize matches rather than being treated as exclusive AND conditions, i.e. if the user requests TOKEN and OPTION assets and specifies an expiry date as well, this should be used to limit the OPTION but still return any matching TOKEN assets.

At this time you cannot filter to PUT or CALL options only or limit by option style, e.g. EUROPEAN, or contract size; the full option chain will be returned, with any expiry and strike filters applied.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_types: List[AssetType] | None

Asset types to query, or all if not specified or empty.

classmethod check_include_expired_vs_expiries(include_expired, values)[source]
exchange_ids: List[UUID] | None

For listed derivatives, the exchanges to include.

expiries: List[date] | None

For futures and options, the expiries to include.

include_expired: bool

Whether to include expired contracts. In the first release this will ALWAYS be False to limit search space, and the backend will reject; parameter included for documentation purposes only at this time.

limit: int | None

The maximum number of items that should be returned. Cannot exceed more than 1000 records.

offset: int | None

The number of records to skip in the page.

strikes: List[float] | None

For options only, the strike prices to include.

underlier_assets: List[UUID] | None

For derivatives, the underliers. For spot, the token asset or, for wrapped assets or stableassets, the underlying asset.

class serenity_types.refdata.asset.AssetStatus(value)[source]

Bases: Enum

Asset status classification.

ACTIVE = 'ACTIVE'
DELISTED = 'DELISTED'
EXPIRED = 'EXPIRED'
UNLISTED = 'UNLISTED'
class serenity_types.refdata.asset.AssetSummary(*, assetId: UUID, assetType: AssetType, assetSymbol: str, nativeSymbol: str, displayName: str, xrefSymbols: List[XRefSymbol])[source]

Bases: CamelModel

Flattened, lowest common denominator representation of assets. This is to support the legacy Refdata API, which only handled TOKEN and CURRENCY. We will be replacing this with a richer mechanism going forward.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

Serenity’s unique internal identifier for this asset. This never changes.

asset_symbol: str

Serenity’s human-readable symbol for this asset. This identifier may change.

asset_type: AssetType

Serenity’s classification for this asset, e.g. TOKEN or CURRENCY.

display_name: str

Serenity’s human-readable display name for this asset, e.g. Bitcoin.

native_symbol: str

The blockchain, listing exchange or other primary authority’s symbol, e.g. BTC.

xref_symbols: List[XRefSymbol]

All associated cross-reference symbols for this asset.

class serenity_types.refdata.asset.AssetType(value)[source]

Bases: Enum

Simple classification of assets.

CURRENCY = 'CURRENCY'

Fiat currency, e.g. EUR.

FUTURE = 'FUTURE'

An exchange-listed futures contract.

INDEX = 'INDEX'

A basket of other assets.

LISTED_OPTION = 'LISTED_OPTION'

An exchange-listed option.

OTC_OPTION = 'OTC_OPTION'

An OTC option contract.

PEGGED_TOKEN = 'PEGGED_TOKEN'

A tokenized asset whose price is linked to an exposure.

PERPETUAL = 'PERPETUAL'

An exchange-listed perpetual future, a.k.a. swap.

STRATEGY = 'STRATEGY'

A multi-leg asset composed of positions in other assets.

TOKEN = 'TOKEN'

Generic tokenized assets.

WRAPPED_TOKEN = 'WRAPPED_TOKEN'

A tokenized asset which represents a claim on a token, typically on another Network.

class serenity_types.refdata.asset.UnsupportedAsset(*, contractAddress: str | None = None, symbol: str | None = None, quantity: float, accountId: UUID | None = None)[source]

Bases: CamelModel

The asset held in the portfolio but not currently supported.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_id: UUID | None

Unique identifier of the account for transaction information.

contract_address: str | None

The address of a contract held in this position.

quantity: float

The number of contracts held in this position.

symbol: str | None

The symbol of a contract held in this position.

class serenity_types.refdata.asset.XRefSymbol(*, authority: SymbolAuthority, symbol: str)[source]

Bases: CamelModel

Legacy representation of a cross-reference symbol for an AssetSummary.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

authority: SymbolAuthority

Symbology for which this symbol is authoritative, e.g. COINGECKO or SEDOL.

symbol: str

String symbol in the given symbology as of the effective date loaded. Note the vendor symbols can and do change over time, so this should be mapped to a Serenity asset ID using inputs from the same day.

serenity_types.refdata.currency

class serenity_types.refdata.currency.Currency(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, isoCurrencyCode: str)[source]

Bases: Asset

An asset representing a fiat currency like the dollar, euro or yen. Note this will need to be extended to link to a fiat_issuance_id for the Exposure UUID once we have distinct fiat exposure reference data.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

iso_currency_code: str

The ISO currency code, e.g. USD or EUR.

serenity_types.refdata.derivatives

class serenity_types.refdata.derivatives.DerivativeAsset(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, underlierAssetId: UUID, quoteAssetId: UUID, referenceIndexId: UUID | None = None, contractSize: float, settlementAssetId: UUID, settlementType: SettlementType, tradeEndTs: datetime | None = None, listingTs: datetime | None = None)[source]

Bases: Asset

A listed or OTC derivative contract.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

contract_size: float

Size of the contract in qty of underlying.

listing_ts: datetime | None

The datetime of this asset being listed.

quote_asset_id: UUID

The quote asset_id for this derivative contract, e.g. USD (a9bc74b3-c761-4446-b4f2-725ae1dcf4fc).

reference_index_id: UUID | None

The specific index, e.g. Deribit BTC Index, used to get a fair price for the underlying at settlement time.

settlement_asset_id: UUID

The asset that this derivatives settles in, e.g. on Deribit, CASH settled, it might be USD. Note we will be switching to the Exposure UUID instead in a future release.

settlement_type: SettlementType

Whether this contract settles in cash or in the underlying itself.

trade_end_ts: datetime | None

The last trade datetime for this asset.

underlier_asset_id: UUID

The underlier asset_id for this derivative contract, e.g. BTC (78e2e8e2-419d-4515-9b6a-3d5ff1448e89).

class serenity_types.refdata.derivatives.Expiry(*, expirationDate: date, expirationTime: time)[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

expiration_date: date

The local expiration date in the contract specification; exact datetime requires a timezone.

expiration_time: time

The local expiration time in the contract specification; exact datetime requires a timezone.

class serenity_types.refdata.derivatives.ListedDerivative(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, underlierAssetId: UUID, quoteAssetId: UUID, referenceIndexId: UUID | None = None, contractSize: float, settlementAssetId: UUID, settlementType: SettlementType, tradeEndTs: datetime | None = None, listingTs: datetime | None = None, exchangeId: UUID)[source]

Bases: DerivativeAsset

An exchange-listed derivative contract.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

exchange_id: UUID

The exchange on which this contract is listed.

class serenity_types.refdata.derivatives.PayoffType(value)[source]

Bases: Enum

An enumeration.

INVERSE = 'INVERSE'

Non-linear payoff that moves opposite the underlying price movements.

LINEAR = 'LINEAR'

Linear payoff that follows the price movement of the underlier.

QUANTO = 'QUANTO'

A quantity-adjusting payoff in which the underlying asset is denominated in one currency but settlement is made in another currency at a predetermined exchange rate.

class serenity_types.refdata.derivatives.SettlementType(value)[source]

Bases: Enum

An enumeration.

CASH = 'CASH'

Derivative contract settled in fiat or stablecoins.

PHYSICAL = 'PHYSICAL'

Derivative contract settled in an asset other than fiat or stablecoins.

serenity_types.refdata.futures

class serenity_types.refdata.futures.Future(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, underlierAssetId: UUID, quoteAssetId: UUID, referenceIndexId: UUID | None = None, contractSize: float, settlementAssetId: UUID, settlementType: SettlementType, tradeEndTs: datetime | None = None, listingTs: datetime | None = None, exchangeId: UUID, expiry: Expiry, expiryDatetime: datetime, payoffType: PayoffType)[source]

Bases: ListedDerivative

An exchange-listed futures contract.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

expiry: Expiry
expiry_datetime: datetime

Expiration datetime for this particular term futures contract.

payoff_type: PayoffType

Whether the contract tracks the price movement (LINEAR) or its mirror image (INVERSE).

class serenity_types.refdata.futures.Perpetual(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, underlierAssetId: UUID, quoteAssetId: UUID, referenceIndexId: UUID | None = None, contractSize: float, settlementAssetId: UUID, settlementType: SettlementType, tradeEndTs: datetime | None = None, listingTs: datetime | None = None, exchangeId: UUID, payoffType: PayoffType)[source]

Bases: ListedDerivative

An exchange-listed perpetual future, sometimes referred to as a swap.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

payoff_type: PayoffType

Whether the contract tracks the price movement (LINEAR) or its mirror image (INVERSE).

serenity_types.refdata.legacy

class serenity_types.refdata.legacy.Currency(*, assetId: UUID, isoCurrencyCode: str, displayName: str)[source]

Bases: CamelModel

Legacy fiat currency reference data; use serenity_types.refdata.currency.Currency instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID
display_name: str
iso_currency_code: str
class serenity_types.refdata.legacy.Future(*, assetId: UUID, listedOn: UUID, underlierAssetId: UUID, expiryDatetime: datetime, settlementAssetId: UUID, settlementType: SettlementType)[source]

Bases: CamelModel

Legacy futures reference data; use serenity_types.refdata.futures.Future instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID
expiry_datetime: datetime
listed_on: UUID
settlement_asset_id: UUID
settlement_type: SettlementType
underlier_asset_id: UUID
class serenity_types.refdata.legacy.Index(*, assetId: UUID, providerId: UUID, symbol: str, family: str, displayName: str)[source]

Bases: CamelModel

Legacy index reference data; use serenity_types.refdata.index.Index instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID
display_name: str
family: str
provider_id: UUID
symbol: str
class serenity_types.refdata.legacy.ListedOption(*, assetId: UUID, listedOn: UUID, underlierAssetId: UUID, optionType: OptionType, optionStyle: OptionStyle, strikePrice: float, expiryDatetime: datetime, settlementAssetId: UUID, settlementType: SettlementType)[source]

Bases: CamelModel

Legacy options reference data; use serenity_types.refdata.options.Option instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID
expiry_datetime: datetime
listed_on: UUID
option_style: OptionStyle
option_type: OptionType
settlement_asset_id: UUID
settlement_type: SettlementType
strike_price: float
underlier_asset_id: UUID
class serenity_types.refdata.legacy.Perpetual(*, assetId: UUID, listedOn: UUID, underlierAssetId: UUID, settlementAssetId: UUID, settlementType: SettlementType)[source]

Bases: CamelModel

Legacy perpetuals reference data; use serenity_types.refdata.futures.Perpetual instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID
listed_on: UUID
settlement_asset_id: UUID
settlement_type: SettlementType
underlier_asset_id: UUID
class serenity_types.refdata.legacy.ReferenceRate(*, assetId: UUID, providerId: UUID, linkedAssetId: UUID, indexAssetId: UUID, displayName: str)[source]

Bases: CamelModel

Legacy reference index reference data; use serenity_types.refdata.index.ReferenceIndex instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID
display_name: str
index_asset_id: UUID
linked_asset_id: UUID
provider_id: UUID
class serenity_types.refdata.legacy.Token(*, tokenId: UUID, blockchainNetworkId: UUID, symbol: str, nativeSymbol: str, displayName: str, logo: str)[source]

Bases: CamelModel

Legacy token reference data; use serenity_types.refdata.exposure.Exposure instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

blockchain_network_id: UUID
display_name: str
native_symbol: str
symbol: str
token_id: UUID
class serenity_types.refdata.legacy.TokenAsset(*, assetId: UUID, token: Token)[source]

Bases: CamelModel

Legacy token asset reference data; use serenity_types.refdata.token.TokenAsset instead.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID
token: Token

serenity_types.refdata.options

class serenity_types.refdata.options.ListedOption(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, underlierAssetId: UUID, quoteAssetId: UUID, referenceIndexId: UUID | None = None, contractSize: float, settlementAssetId: UUID, settlementType: SettlementType, tradeEndTs: datetime | None = None, listingTs: datetime | None = None, exchangeId: UUID, optionType: OptionType, optionStyle: OptionStyle, strikePrice: float, expiry: Expiry, expiryDatetime: datetime)[source]

Bases: ListedDerivative

An exchange-listed vanilla option.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

expiry: Expiry
expiry_datetime: datetime

Expiration datetime for this option.

option_style: OptionStyle

Exercise type for this option, e.g. European exercise.

option_type: OptionType

Whether this is a put or call contract.

strike_price: float

Strike price for the option contract, e.g. 20000.

class serenity_types.refdata.options.OTCOption(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType = AssetType.OTC_OPTION, symbol: str, nativeSymbol: str | None = None, displayName: str, underlierAssetId: UUID, quoteAssetId: UUID, referenceIndexId: UUID | None = None, contractSize: float, settlementAssetId: UUID, settlementType: SettlementType, tradeEndTs: datetime | None = None, listingTs: datetime | None = None, optionType: OptionType, optionStyle: OptionStyle, strikePrice: float, expiryDatetime: datetime)[source]

Bases: DerivativeAsset

An OTC option.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_type: AssetType

Set asset_type as OTCOption.

expiry_datetime: datetime

Expiration datetime for this option.

option_style: OptionStyle

Exercise type for this option, e.g. European exercise.

option_type: OptionType

Whether this is a put or call contract.

strike_price: float

Strike price for the option contract, e.g. 20000.

class serenity_types.refdata.options.OptionStyle(value)[source]

Bases: Enum

Variety of option supported. Right now we only support vanilla European options.

AMERICAN = 'AMERICAN'

An option that can be exercised at any time up to the expiry date.

EUROPEAN = 'EUROPEAN'

An option that can only be exercised on the expiry date.

class serenity_types.refdata.options.OptionType(value)[source]

Bases: Enum

Put/call flag for options.

CALL = 'CALL'

The right but not the obligation to buy the underlier at the strike price on exercise.

PUT = 'PUT'

The right but not the obligation to sell the underlier at the strike price on exercise.

serenity_types.refdata.organization

class serenity_types.refdata.organization.Organization(*, organizationId: UUID, organizationType: OrganizationType, shortName: str, displayName: str)[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

display_name: str

Human-friend name for this organization, e.g. S&P Dow Jones Indices.

organization_id: UUID

Unique ID for this organization.

organization_type: OrganizationType

Catagory of organization, e.g. an exchange.

short_name: str

One-word, lowercase code for this organization, e.g. spdix.

class serenity_types.refdata.organization.OrganizationType(value)[source]

Bases: Enum

Category of legal entity; generally used when referring to who provides information, prices, positions, etc..

DAO = 'DAO'

A Decentralized Autonomous Organization (DAO); generally associated with DeFi and other protocols as the owner, e.g. MakerDAO.

DATA_PROVIDER = 'DATA_PROVIDER'

A data vendor like Kaiko or Amberdata. This is to allow for the possibility that data might come either directly from an exchange or indirectly via a data aggregator of some kind.

DEALER = 'DEALER'

A broker/dealer, prime broker, OTC desk associated with a prop trading firm or market maker, or any other entity that does OTC deals and otherwise could be a counterparty.

EXCHANGE = 'EXCHANGE'

A centralized exchange, e.g. Binance or Deribit.

INDEX_PROVIDER = 'INDEX_PROVIDER'

A benchmark or other index provider like S&P.

ORACLE = 'ORACLE'

A price oracle like ChainLink or Pyth.

OTHER = 'OTHER'

Any other kind of organization we wish to track.

serenity_types.refdata.symbology

class serenity_types.refdata.symbology.SymbolAuthority(*, name: str, description: str)[source]

Bases: CamelModel

An authoritative source for asset symbols.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

description: str

Human-readable description of this authority or symbology.

name: str

Name for the authority or symbology; used in enums.

class serenity_types.refdata.symbology.XRefSymbol(*, authority: str, symbol: str)[source]

Bases: CamelModel

A simple that can be used for cross-referencing a Serenity asset ID to another, external source’s symbols.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

authority: str

The short name for the owning authority.

symbol: str

The corresponding symbol.

serenity_types.refdata.token

class serenity_types.refdata.token.PegMechanism(value)[source]

Bases: Enum

The mechanism used to establish and maintain the peg of one asset’s price ot another.

ALGOSTABLE = 'ALGOSTABLE'

Pegging via an algorithmic stabilization mechanism, e.g. FRAX.

COLLATERIZED_DEBT_POSITION = 'COLLATERIZED_DEBT_POSITION'

A tokenized CDP (Collateralized Debt Position), generally over-collateralized with cryptoassets, e.g. DAI.

TOKENIZED_ASSET = 'TOKENIZED_ASSET'

Pegging to an asset reserve-backed holding, e.g. PAXG.

TOKENIZED_CASH = 'TOKENIZED_CASH'

Pegging to a currency reserve-backed holding, e.g. USDC and BUSD.

class serenity_types.refdata.token.PeggedTokenAsset(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, tokenIssuanceId: UUID, networkId: UUID, referencedExposureId: UUID, pegMechanism: PegMechanism)[source]

Bases: TokenAsset

A token whose price aims to track the price of an Exposure.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

peg_mechanism: PegMechanism

How the peg is established and maintained, e.g. backed 100% by reserves of assets with an identical exposure as referenced_exposure_id, or algorithmically stabilized via an arbitrage mechanism, etc..

referenced_exposure_id: UUID

The exposure that is being pegged to, e.g. USD (for USDC) XAU (for PAXG).

class serenity_types.refdata.token.TokenAsset(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, tokenIssuanceId: UUID, networkId: UUID)[source]

Bases: Asset

A tokenized asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

network_id: UUID

The blockchain on which this particular asset has been tokenized.

token_issuance_id: UUID

A reference to the Exposure UUID for the underlying token issuance. This is to allow for the fact that a number of tokens have been issued on more than one blockchain, e.g. DAI on Ethereum and Solana in our model would be two different assets, tok.dai.ethereum and tok.dai.solana, both pointing to a single DAI exposure linked to MakerDAO.

class serenity_types.refdata.token.WrappedTokenAsset(*, assetId: UUID, isSupported: bool, assetStatus: AssetStatus, assetType: AssetType, symbol: str, nativeSymbol: str | None = None, displayName: str, tokenIssuanceId: UUID, networkId: UUID, wrappedTokenIssuanceId: UUID, originNetworkId: UUID)[source]

Bases: TokenAsset

A token that allows another token Exposure to be represented on a non-native network. Typically this is done by locking the asset in a smart contract or by a custodian holding the asset in reserve and then issuing a token. At any time the holder has a right to redeem the wrapped asset for the underlying asset one for one, though there is implicit smart contract / counterparty risk involved as this is not guaranteed.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

origin_network_id: UUID

The original network that the wrapped asset sits on, e.g. bitcoin for WBTC, or ethereum or WETH. Note in the case of WETH on Ethereum as an asset, the origin_network_id and network_id are the same, because it’s just an ERC20 encapsulation of the native ETH token.

wrapped_token_issuance_id: UUID

The token issuance that this asset is wrapping, e.g. BTC for WBTC.

serenity_types.risk.simulators.driver_keys

This module contains the types, enumerations and classes that represent the driver keys.

We use the generic term driver, instead of the more popular term risk driver, because the drivers described here are not necessarily related to risk, as the could also be used for stress testing or sensitivity analysis.

class serenity_types.risk.simulators.driver_keys.DriverKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType)[source]

Bases: CamelModel

The common attributes to all driver keys.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

class Config[source]

Bases: object

Pydantic configuration class: we vaildate the assignments so that the fields cannot be changed after creation.

validate_assignment = True
description: str

A summary of all the driver fields that can also be used as long unique identifier for the driver key itself.

driver_key_type: DriverKeyType

The driver-key type, one of the values of the DriverKeyType enumeration.

key_id: DriverKeyId

A unique identifier for the risk driver key. This field should be a readable deterministic unique identifier, computed from the other fields.

class serenity_types.risk.simulators.driver_keys.DriverKeyId[source]

Bases: EntityId

A unique identifier for all driver keys, currently an entity id.

class serenity_types.risk.simulators.driver_keys.DriverKeyType(value)[source]

Bases: Enum

The enumeration of all possible driver-key types.

Note that the representation string matches the corresponding model name (see below).

EXCHANGE_RATE = 'ExchangeRateKey'

The exchange-rate driver keys

FUTURES_BASIS = 'FuturesBasisKey'

The futures-basis driver keys

INTEREST_RATE = 'InterestRateKey'

The interest-rate driver keys

PERPETUAL_BASIS = 'PerpetualBasisKey'

The perpetual-basis driver keys

PROJECTION_CURVE = 'ProjectionCurveKey'

The projection-curve driver keys

PROJECTION_RATE = 'ProjectionRateKey'

The projection-rate driver keys

SPOT_PRICE = 'SpotPriceKey'

The spot-price driver keys

VOLATILITY_POINT = 'VolatilityPointKey'

The volatility-point driver keys

VOLATILITY_SLICE = 'VolatilitySliceKey'

The volatility-slice driver keys

VOLATILITY_SURFACE = 'VolatilitySurfaceKey'

The volatility-surface driver keys

class serenity_types.risk.simulators.driver_keys.DriverMoneyness[source]

Bases: str

The moneyness of a driver, typically an implied volatility.

Currently it is just a string, however we might add some verification logic in the future.

class serenity_types.risk.simulators.driver_keys.DriverTenor[source]

Bases: str

The tenor of a driver such as a projection rate or a volatility point.

Currently it is just a string, however we might add some verification logic in the future.

class serenity_types.risk.simulators.driver_keys.ExchangeRateKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID)[source]

Bases: DriverKey

The exchange rate between a base exposure and a quote exposure. This is the exchange rate is the base class for all keys that represent exchange rates. (This includes spot prices, which are exchange rates between an asset and a currency.)

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_exposure_id: UUID

The base exposure of the exchange rate. E.g., the UUID of BTC in a BTC/USD exchange rate

quote_exposure_id: UUID

The quote exposure of the exchange rate. E.g., the UUID of USD in a BTC/USD exchange rate

class serenity_types.risk.simulators.driver_keys.FuturesBasisKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID)[source]

Bases: ExchangeRateKey

The basis of futures contracts.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_exposure_id: UUID

The base exposure of the exchange rate. E.g., the UUID of BTC in a BTC/USD exchange rate

description: str

A summary of all the driver fields that can also be used as long unique identifier for the driver key itself.

driver_key_type: DriverKeyType

The driver-key type, one of the values of the DriverKeyType enumeration.

key_id: DriverKeyId

A unique identifier for the risk driver key. This field should be a readable deterministic unique identifier, computed from the other fields.

quote_exposure_id: UUID

The quote exposure of the exchange rate. E.g., the UUID of USD in a BTC/USD exchange rate

class serenity_types.risk.simulators.driver_keys.InterestRateKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, tenor: DriverTenor)[source]

Bases: DriverKey

The interest rate of a currency at a given tenor

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_exposure_id: UUID

The base exposure of the interest rate

tenor: DriverTenor

The tenor of the interest rate

class serenity_types.risk.simulators.driver_keys.PerpetualBasisKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID)[source]

Bases: ExchangeRateKey

The basis of perpetual contracts.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_exposure_id: UUID

The base exposure of the exchange rate. E.g., the UUID of BTC in a BTC/USD exchange rate

description: str

A summary of all the driver fields that can also be used as long unique identifier for the driver key itself.

driver_key_type: DriverKeyType

The driver-key type, one of the values of the DriverKeyType enumeration.

key_id: DriverKeyId

A unique identifier for the risk driver key. This field should be a readable deterministic unique identifier, computed from the other fields.

quote_exposure_id: UUID

The quote exposure of the exchange rate. E.g., the UUID of USD in a BTC/USD exchange rate

class serenity_types.risk.simulators.driver_keys.ProjectionCurveKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID, rates: Tuple[DriverKeyId, ...])[source]

Bases: ExchangeRateKey

The entire projection curve composed of many projection rates.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

rates: Tuple[DriverKeyId, ...]

The list of ids of the projection rates that compose the projection curve

class serenity_types.risk.simulators.driver_keys.ProjectionRateKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID, tenor: DriverTenor)[source]

Bases: ExchangeRateKey

The projection rate of an asset with respect to a currency

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

tenor: DriverTenor

The tenor of the projection rate

class serenity_types.risk.simulators.driver_keys.SpotPriceKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID)[source]

Bases: ExchangeRateKey

The spot price of an asset in the quoted exposure. In a BTC/USD spot price, the base exposure is BTC and the quote exposure is USD.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_exposure_id: UUID

The base exposure of the exchange rate. E.g., the UUID of BTC in a BTC/USD exchange rate

description: str

A summary of all the driver fields that can also be used as long unique identifier for the driver key itself.

driver_key_type: DriverKeyType

The driver-key type, one of the values of the DriverKeyType enumeration.

key_id: DriverKeyId

A unique identifier for the risk driver key. This field should be a readable deterministic unique identifier, computed from the other fields.

quote_exposure_id: UUID

The quote exposure of the exchange rate. E.g., the UUID of USD in a BTC/USD exchange rate

class serenity_types.risk.simulators.driver_keys.VolatilityPointKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID, tenor: str, moneynesses: DriverMoneyness)[source]

Bases: ExchangeRateKey

A single volatility point. The implied volatility of an asset with respect to a currency at a given tenor and moneyness.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

moneynesses: DriverMoneyness

The volatility moneyness.

tenor: str

The volatility tenor.

class serenity_types.risk.simulators.driver_keys.VolatilitySliceKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID, tenor: DriverTenor, points: Tuple[DriverKeyId, ...])[source]

Bases: ExchangeRateKey

A slice of the volatility surface, i.e. a reference to all volatility points with the same tenor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

points: Tuple[DriverKeyId, ...]

The list of ids of the volatility points that compose the volatility slice.

tenor: DriverTenor

The volatility tenor.

class serenity_types.risk.simulators.driver_keys.VolatilitySurfaceKey(*, keyId: DriverKeyId, description: str, driverKeyType: DriverKeyType, baseExposureId: UUID, quoteExposureId: UUID, slices: Tuple[DriverKeyId, ...])[source]

Bases: ExchangeRateKey

The entire volatility surface composed of many volatility slices.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

slices: Tuple[DriverKeyId, ...]

The list of ids of the volatility slices that compose the volatility surface.

serenity_types.risk.simulators.entities

Entity is a generic name for simulator contributors, driver keys, trees, …

class serenity_types.risk.simulators.entities.EntityId[source]

Bases: str

A unique identifier for entities.

It should be a readable deterministic unique identifier.

serenity_types.risk.simulators.entity_holders

Entity holders are used to store the simulator entities in flat dictionaries.

class serenity_types.risk.simulators.entity_holders.EntityHolder(*, contributors: Dict[ContributorId, CustodyProviderContributor | CustodyTypeContributor | DriverKeyContributor | MoneynessContributor | ModelFactorContributor | QuotedAssetContributor | SimulatorRootContributor | SourcedPositionContributor | TenorContributor | UnderlierContributor | ResidualContributor] = None, contributorTrees: Dict[str, EntityTreeNode] = None, driverKeys: Dict[DriverKeyId, DriverKey] = None)[source]

Bases: CamelModel

Holding all relevant simulation entities in a single place.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

contributor_trees: Dict[str, EntityTreeNode]

The dictionary of all contributor trees. Note that the root node is enough to specify the whole tree.

contributors: Dict[ContributorId, CustodyProviderContributor | CustodyTypeContributor | DriverKeyContributor | MoneynessContributor | ModelFactorContributor | QuotedAssetContributor | SimulatorRootContributor | SourcedPositionContributor | TenorContributor | UnderlierContributor | ResidualContributor]

The flat dictionary of all contributors.

driver_keys: Dict[DriverKeyId, DriverKey]

The dictionary of all driver keys. This field is empty if the simulation does not expose any driver entities.

serenity_types.risk.simulators.greek_measures

This module defines the types used by the simulator for Greek measures in financial computations.

class serenity_types.risk.simulators.greek_measures.GreekMeasureAggregationType(value)[source]

Bases: Enum

Specifies how Greek measures are aggregated, such as net, gross, or none.

GROSS = 'Gross'

The absolute value of the Greek measure is aggregated, so that we always get a positive number.

NET = 'Net'

The Greek measure is aggregated as is, i.e. keeping its sign.

NONE = 'None'

No aggregation is performed on the Greek measure.

class serenity_types.risk.simulators.greek_measures.GreekMeasureParameters(*, tag: str, measureType: GreekMeasureType, reference: GreekMeasureReference, aggregationType: GreekMeasureAggregationType, unit: GreekMeasureUnit)[source]

Bases: CamelModel

Represents the parameters associated with a specific Greek measure.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

class Config[source]

Bases: object

Pydantic configuration class: we vaildate the assignments so that the fields cannot be changed after creation.

validate_assignment = True
aggregation_type: GreekMeasureAggregationType

The aggregation type for the Greek measure.

measure_type: GreekMeasureType

The risk-measure type chosen from the list of risk measure types.

reference: GreekMeasureReference

The reference for the Greek measure.

tag: str

The Greek measure unique identifier, unique within the list of Greek measures. This field is usially deterministically generated from the other fields.

unit: GreekMeasureUnit

The Greek measure unit.

class serenity_types.risk.simulators.greek_measures.GreekMeasureReference(value)[source]

Bases: Enum

Defines the reference context for Greek measures, like native, quantity, or currency.

CURRENCY = 'Currency'

The Greek measure is related to the currency of the instrument.

NATIVE = 'Native'

The Greek measure is related to the native pricing variable. This is the pure unalterated mathematical derivative value.

QUANTITY = 'Quantity'

The Greek measure is related to the quantity of the instrument.

class serenity_types.risk.simulators.greek_measures.GreekMeasureRequest(*, asOfTime: datetime | None = None, portfolioAsOfTime: datetime | None = None, portfolioMetadataId: UUID | None = None, portfolioBalances: List[Balance] | None = None, simulationId: UUID | None = None)[source]

Bases: CamelModel

Represents the request for Greek-measure computation. Specify either portfolio_metadata_id or the full portfolio_balances by values.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime | None

The as-of time to be used when askingb the data source for market data. If this is not specified, the latest market data will be used.

classmethod check_portfolio_snapshot_id_and_portfolio_balances(values)[source]
portfolio_as_of_time: datetime | None

The as-of time used to determine which portfolio snapshot is to be used. Defaults to the value of the as_of_time parameter.

portfolio_balances: List[Balance] | None

The balances by values, i.e. the list of positions to be used in the computation. If this is not specified, the balances will be retrieved from the database using the portfolio_metadata_id.

portfolio_metadata_id: UUID | None

Portfolio metadata ID used to retrieve the balances if parameter portfolio_balances is not specified.

simulation_id: UUID | None

Used to create a seed for the deterministic creation of the contributors ids. It can be used in future requests to obtain the same contributors ids, if the tree structure is the same. If this is not specified, a new simulation id will be created.

class serenity_types.risk.simulators.greek_measures.GreekMeasureResponse(*, asOfTime: datetime, simulationId: UUID, balances: List[Balance], custodySources: List[CustodySource], greekMeasureParameters: Dict[str, GreekMeasureParameters], entityHolder: EntityHolder, greekMeasures: Dict[ContributorId, Dict[str, float]], intermediateValues: Dict[ContributorId, Dict[str, float]])[source]

Bases: CamelModel

Results for the Greek measures.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime

The actual as_of_time used for the computation.

balances: List[Balance]

The actual portfolio balances used for the computation. They might be different from the requested balances if there were duplications or null balances.

custody_sources: List[CustodySource]

The list of custody sources used in the computation.

entity_holder: EntityHolder

Encapsulates the information about the entities (such as financial instruments or portfolios) involved in the computation of Greek measures.

greek_measure_parameters: Dict[str, GreekMeasureParameters]

A dictionary mapping Greek-measure tags to their corresponding parameters. Each tag represents a specific Greek measure (e.g., delta, gamma) with the associated calculation parameters.

greek_measures: Dict[ContributorId, Dict[str, float]]

A nested dictionary where each key is a Contributor ID and its value is another dictionary mapping Greek-measure tags to their calculated values. This structure provides the computed Greek measures for each contributing entity.

intermediate_values: Dict[ContributorId, Dict[str, float]]

Contains intermediate computational variables, organized by Contributor ID. Each entry is a dictionary mapping variable tags to their respective values, providing insights into the calculations performed for each contributor. Not all contributors may have corresponding entries in this dictionary.

simulation_id: UUID

This actual simulation_id used to create the contributors ids.

class serenity_types.risk.simulators.greek_measures.GreekMeasureType(value)[source]

Bases: Enum

Enumeration for different types of Greek measures.

DELTA = 'Delta'

The delta’s sensitivity to spot changes.

GAMMA = 'Gamma'

The gamma’s sensitivity to spot changes.

RHO = 'Rho'

The rho’s sensitivity to interest-rate changes.

THETA = 'Theta'

The theta’s sensitivity to time changes.

VALUE = 'Value'

The value zero-order mathematical derivative, i.e. the derivative-asset value itself.

VEGA = 'Vega'

The vega’s sensitivity to volatility changes.

class serenity_types.risk.simulators.greek_measures.GreekMeasureUnit(value)[source]

Bases: Enum

Units for representing Greek measures, like unity, percent, basis point, or day.

BASIS_POINT = 'BasisPoint'

The basis point is Decimal(“0.0001”).

DAY = 'Day'

The day as a fraction of a year: Decimal(“1”)/Decimal(“365”).

PERCENT = 'Percent'

The percentage is Decimal(“0.01”).

UNITY = 'Unity'

The pure derivative value.

class serenity_types.risk.simulators.greek_measures.InternalGreekMeasureRequest(*, asOfTime: datetime | None = None, portfolioBalances: List[Balance], custodySources: List[CustodySource], simulationId: UUID | None = None)[source]

Bases: CamelModel

INTERNAL USE ONLY: for clients’ risk services to call core risk services.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime | None

The as-of time to use for loading all marketdata, surfaces, yield curves and refdata from the database. Defaults to the latest up to this time.

custody_sources: List[CustodySource]

List of custody sources for the specified balances’ accounts.

portfolio_balances: List[Balance]

The full portfolio balances by values.

simulation_id: UUID | None

Note that the simulation_id is optional. If it is not provided, a new one will be created. The simulation_id is used to create a seed for the deterministic creation contributors id’s. It can be used in future requests to obtain the same contributors ids, if the tree structure is the same.

serenity_types.risk.simulators.simulator_contributors

Simulator contributors specify elements to which we can associate a measure contribution.

class serenity_types.risk.simulators.simulator_contributors.ChildContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId)[source]

Bases: SimulatorContributor

A child contributor always has a parent contributor as a reference. This is a base class and should not be instantiated directly, however this is not enforced in the code.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

parent_id: ContributorId

The contributor id to which this child contribution referes to.

class serenity_types.risk.simulators.simulator_contributors.ContributorId[source]

Bases: EntityId

A unique identifier for the simulator contributors. It is currently just an entity id.

class serenity_types.risk.simulators.simulator_contributors.ContributorType(value)[source]

Bases: Enum

The enumeration of all simulator contributor types. Note that the representation string matches the corresponding model name (see below).

CUSTODY_PROVIDER = 'CustodyProviderContributor'

The custodian contributor holds contributor values for the same custodian.

CUSTODY_TYPE = 'CustodyTypeContributor'

The custody-type contributor holds contributor values for the same custody type.

DRIVER_KEY = 'DriverKeyContributor'

The simulator contributor is a driver key.

MODEL_FACTOR = 'ModelFactorContributor'

The simulator contributor is a model factor.

MONEYNESS = 'MoneynessContributor'

The simulator contributor holds contributor values with the same moneyness.

OTC_ASSET = 'OtcAssetContributor'

The simulator contributor is an OTC asset.

PORTFOLIO_SNAPSHOT = 'PortfolioSnapshotContributor'

The simulator contributor is a portfolio snapshot.

QUOTED_ASSET = 'QuotedAssetContributor'

The simulator contributor is a quoted asset.

RESIDUAL = 'ResidualContributor'

The simulator contributor is a residual value.

SIMULATOR_ROOT = 'SimulatorRootContributor'

The simulator contributor is a root node.

SOURCED_POSITION = 'SourcedPositionContributor'

The balance contributor of an asset in an account.

TENOR = 'TenorContributor'

The simulator contributor holds contributor values with the same tenor.

UNDERLIER = 'UnderlierContributor'

The underlier contributor holds contributor values for the same underlier.

UNSOURCED_POSITION = 'UnsourcedPositionContributor'

The balance contributor of an asset that is not in an account.

class serenity_types.risk.simulators.simulator_contributors.CustodyProviderContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, providerId: UUID | None)[source]

Bases: ChildContributor

The simulator contributor for a custody provider. For example the ID of a certified custodian.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

provider_id: UUID | None

The ID of the custody provider.

class serenity_types.risk.simulators.simulator_contributors.CustodyTypeContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, custodyProviderType: CustodyProviderType)[source]

Bases: ChildContributor

The simulator contributor for a custody type. For example, a cold wallet, a centralized exchange, a certified custodian, and so on.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

custody_provider_type: CustodyProviderType

The unique identifier of the custody type

class serenity_types.risk.simulators.simulator_contributors.DriverKeyContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, driverKey: DriverKey)[source]

Bases: ChildContributor

The simulator contributor for a driver key.

For example, contributor by the volatility related to the portfolio-snapshot.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

driver_key: DriverKey

A copy of the driver key associated with this contributor.

class serenity_types.risk.simulators.simulator_contributors.ModelFactorContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, modelConfigId: UUID, factorName: str)[source]

Bases: ChildContributor

The simulator contributor for model factors. The model-factor contributor usually referes to a portfolio snapshot, a quoted asset or an OTC asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

factor_name: str

The name of the factor in the factor model specified by the model_config_id. E.g. ‘momentum’ or ‘size’”

model_config_id: UUID

The unique identifier of the factor model

class serenity_types.risk.simulators.simulator_contributors.MoneynessContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, moneyness: DriverMoneyness)[source]

Bases: ChildContributor

The simulator contributor for the moneyness.

For example, the contributor of the 50-sigma volatility related for a portfolio-snapshot contributor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

moneyness: DriverMoneyness

The moneyness of this contributor

class serenity_types.risk.simulators.simulator_contributors.OtcAssetContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, otcAssetId: str, otcAssetType: OTCAssetTypes)[source]

Bases: ChildContributor

The simulator contributor for OTC assets

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

otc_asset_id: str

User specified unique identifier of the OTC asset.

otc_asset_type: OTCAssetTypes

Serenity classification of OTC assets

class serenity_types.risk.simulators.simulator_contributors.PortfolioSnapshotContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, snapshotId: UUID)[source]

Bases: SimulatorContributor

The simulator contributor for portfolio snapshots. Usually, there is only one portfolio snapshot per simulation. Note that this contributor cannot be a child of any other contributor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

description: str

A unique description of the portfolio-snapshot contributor. It can be used to create different tree roots for the same portfolio snapshot.

snapshot_id: UUID

The unique identifier of the portfolio snapshot

class serenity_types.risk.simulators.simulator_contributors.QuotedAssetContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, assetId: UUID)[source]

Bases: ChildContributor

The simulator contributor for quoted assets. There should be one, and only one, quoted asset contributor for each quoted asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

The unique identifier of the quoted asset

class serenity_types.risk.simulators.simulator_contributors.ResidualContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId)[source]

Bases: ChildContributor

The residual contributor for another contributor. As sometimes the sum of the standard contributors is not equal to the total, we need for add a residual contributor. The reference contributor is usually a portfolio snapshot, a quoted asset or an OTC asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

contributor_id: ContributorId

A readable deterministic unique identifier for the simulator contributor. This field should be computed by a factory from the other fields after the object creation.

contributor_type: ContributorType

The type of the simulator contributor.

description: str

A summary of all the contributor fields that can also be used as long unique identifier this contributor. This should be computed by a factory deterministically from the other fields.

parent_id: ContributorId

The contributor id to which this child contribution referes to.

class serenity_types.risk.simulators.simulator_contributors.SimulatorContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType)[source]

Bases: CamelModel

The base model for all simulator contributors.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

class Config[source]

Bases: object

Pydantic configuration: we vaildate the assignments so that the fields cannot be changed after creation.

validate_assignment = True
contributor_id: ContributorId

A readable deterministic unique identifier for the simulator contributor. This field should be computed by a factory from the other fields after the object creation.

contributor_type: ContributorType

The type of the simulator contributor.

description: str

A summary of all the contributor fields that can also be used as long unique identifier this contributor. This should be computed by a factory deterministically from the other fields.

class serenity_types.risk.simulators.simulator_contributors.SimulatorRootContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, simulationId: UUID)[source]

Bases: SimulatorContributor

The simulator contributor for root nodes. There might be multiple root nodes per simulation, these are distinguished by the description field. Note that this contributor cannot be a child of any other contributor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

description: str

A unique description of the root node contributor. It can be used to create different tree roots for the same simulation id.

simulation_id: UUID

Used to create a seed for the deterministic creation of the contributors ids. It can be used in future requests to obtain the same contributors ids, if the tree structure is the same.

class serenity_types.risk.simulators.simulator_contributors.SourcedPositionContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, assetId: UUID, accountId: UUID)[source]

Bases: ChildContributor

The simulator contributor for a balance that has an account id. Since these contributors are uniquely identified by the asset_id and the account_id, balances with the same asset_id and account_id are grouped together.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

account_id: UUID

Unique identifier of the account for transaction information.

asset_id: UUID

The unique asset identifier.

class serenity_types.risk.simulators.simulator_contributors.TenorContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, tenor: DriverTenor)[source]

Bases: ChildContributor

The simulator contributor for a tenor related for another contributor.

For example, the contributor of the 3-month projection rate related for a portfolio-snapshot contributor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

tenor: DriverTenor

The tenor of this contributor.

class serenity_types.risk.simulators.simulator_contributors.UnderlierContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, assetId: UUID)[source]

Bases: ChildContributor

The simulator contributor for an underlier. For example, the contributor that gathers together all derivative with a specific underlying asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

The unique identifier of the underlier. Note that in the future we might also allow a tuple of UUID, to represent no underlier or a multiplicity of them.

class serenity_types.risk.simulators.simulator_contributors.UnsourcedPositionContributor(*, contributorId: ContributorId, description: str, contributorType: ContributorType, parentId: ContributorId, assetId: UUID)[source]

Bases: ChildContributor

The simulator contributor for a balance that has the asset id only. Since these contributors are uniquely identified by the asset_id, balances with the same asset_id are grouped together.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

The unique asset identifier.

serenity_types.risk.simulators.simulator_trees

Entity tree nodes specify nodes for entity trees.

class serenity_types.risk.simulators.simulator_trees.EntityTreeNode(*, entityId: EntityId, children: List[EntityTreeNode] = None, label: str | None = None)[source]

Bases: CamelModel

Trees are composed of nodes that are either leaves or have children. Each node has a mandatory entity_id field that reference an existing entity object. The entity_id should be unique within a tree, however, it could belong to multiple trees. Most commonly used with simulator contributors.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

class Config[source]

Bases: object

Pydantic configuration: we vaildate the assignments so that the fields cannot be changed after creation.

validate_assignment = True
children: List[EntityTreeNode]

The list of node children. If there is at least one child, then the node is either a branch or the root node. If this list is empty, then the node is a leaf.

entity_id: EntityId

The id of the entity that is related to this node. This is usually a the id of a simulator contributor.

label: str | None

An optional user-readble label that can help the user to identify the node. In the case of simulator contributors, this is usually the string associated with the contributor type.

serenity_types.risk.factor

class serenity_types.risk.factor.AssetFactorExposureMatrixElement(*, assetId: UUID, factor: str, value: float)[source]

Bases: CamelModel

A single element from the matrix of asset factor exposures, for one day.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

The unique ID of the asset from the portfolio.

factor: str

The name of the factor from the risk model, e.g. Momentum.

value: float

Factor loading for the given factor-asset pair (betas from the regression).

class serenity_types.risk.factor.AssetFactorIndexWeight(*, assetId: UUID, weight: float)[source]

Bases: CamelModel

A single entry in a factor portfolio index, with the asset’s weight in the portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

The unique ID of the asset from the portfolio.

weight: float

signed weight (long or short) of this asset in the factor index; this is a fraction, e.g. 0.25 for 25%. For long-only they sum to 1.0 and for long-short they sum to 0.0 in the current methodology.

class serenity_types.risk.factor.AssetMatrixElement(*, assetId1: UUID, assetId2: UUID, value: float)[source]

Bases: CamelModel

A single cell in an asset-asset matrix, e.g. a covariance matrix.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id1: UUID

First unique asset ID in the pair.

asset_id2: UUID

Second unique asset ID in the pair.

value: float

Matrix cell value, e.g. correlation.

class serenity_types.risk.factor.AssetResidualValue(*, assetId: UUID, value: float)[source]

Bases: CamelModel

A single entry in a list of asset residuals from the covariance matrix.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

Unique asset ID being referenced.

value: float

Asset residual covariance value.

class serenity_types.risk.factor.AssetRisk(*, factorRisk: float, specificRisk: float, totalRisk: float, assetId: UUID, sectorLevels: List[str])[source]

Bases: Risk

This object supports the “Breakdown” view By Asset as well as the sector breakdowns.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

The unique asset ID for the asset break-down of risk.

sector_levels: List[str]

A list of sector level names that identifies a “path” to a particular level in the sector taxonomy, as defined above; however, in this instance, this is the fully-qualified path to this particular asset, i.e. the leaf level.

class serenity_types.risk.factor.FactorExposureValue(*, factorExposure: float, factorExposureBaseCcy: float)[source]

Bases: CamelModel

A decimal or base currency exposure to a risk factor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

factor_exposure: float

Asset-level factor loading.

factor_exposure_base_ccy: float

The factor exposure expressed in base currency terms.

class serenity_types.risk.factor.FactorMatrixElement(*, factor1: str, factor2: str, value: float)[source]

Bases: CamelModel

A single cell in a factor-factor matrix, e.g. factor covariance.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

factor1: str

Name of the first factor from the risk model, e.g. Momentum

factor2: str

Name of the second factor from the risk model, e.g. Size.

value: float

Matrix cell value, e.g. a covariance or a correlation.

class serenity_types.risk.factor.FactorReturn(*, factor: str, closeDate: date, value: float)[source]

Bases: CamelModel

A single daily return for a factor portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

close_date: date
factor: str

Name of the factor from the risk model, e.g. Momentum.

value: float

Daily return for this particular factor on the given close date.

class serenity_types.risk.factor.FactorsReturnsHourly(*, asOfTimes: List[datetime], factors: List[str], values: List[List[float]])[source]

Bases: CamelModel

Time series of hourly factor returns.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: List[datetime]

The list of all available as_of_times in the requested window.

factors: List[str]

Names of the factors according to the chosen model, e.g. Momentum.

values: List[List[float]]

Matrix of hourly returns for each as_of_time, factor pair.

class serenity_types.risk.factor.Risk(*, factorRisk: float, specificRisk: float, totalRisk: float)[source]

Bases: CamelModel

Common triplet for risk measures used across the API.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

factor_risk: float

The volatility or variance explained by the factor risk model.

specific_risk: float

The volatility or variance not explained by the model.

total_risk: float

The total volatility or variance along the measured dimension.

class serenity_types.risk.factor.RiskAttributionRequest(*, asOfDate: date | None = None, portfolio: List[AssetPosition], modelConfigId: UUID | None = None, sectorTaxonomyId: UUID | None = None, markTime: MarkTime | None = None, baseCurrencyId: UUID | None = None, strict: bool | None = False)[source]

Bases: CamelModel

Request to run a risk attribution on the given portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_date: date | None

UTC date midnight; default to latest, as yyyy-mm-dd.

base_currency_id: UUID | None

Base currency for value reporting, defaults to USD.

mark_time: MarkTime | None

Time to use for close, defaults to MarkTime.NY_EOD.

classmethod merge_duplicated_asset_positions(values)[source]
model_config_id: UUID | None

A reference to a factor risk model configuration from [ModelOps API, e.g. a specific parameterization of SFRMv1; if not specified then the system will select the most appropriate model.

portfolio: List[AssetPosition]

Portfolio constituents to analyze.

sector_taxonomy_id: UUID | None

References a taxonomy UUID from the Refdata API, specifically the getSectorTaxonomies call; defaults to DACS.

strict: bool | None

Should the request fail if there are any warnings?

class serenity_types.risk.factor.RiskAttributionResponse(*, totalRisk: TotalRisk, absoluteContributionRisk: RiskBreakdown, relativeContributionRisk: RiskBreakdown, assetMarginalRisk: List[AssetRisk], factorrisk: List[TotalFactorRisk], sectorfactorexposures: List[SectorFactorExposure])[source]

Bases: CamelModel

Consolidated response for a single risk attribution run using a factor risk model.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

absolute_contribution_risk: RiskBreakdown

Sector and asset absolute contribution to the volatility of the portfolio; cross-check sums by asset to equal total factor, specific and total volatility for all assets.

asset_marginal_risk: List[AssetRisk]

By-asset marginal weighted contribution of volatility to the portfolio.

factorRisk: List[TotalFactorRisk]

By-factor absolute, relative and marginal contribution to risk, as well as the portfolio’s exposure to each factor.

relative_contribution_risk: RiskBreakdown

Sector and asset relative contribution to the variance of the portfolio; cross-check sums by asset to equal total factor and specific variance divided by total variance.

sectorFactorExposures: List[SectorFactorExposure]

Aggregations of factor exposure by factor and sector.

total_risk: TotalRisk

Portfolio risk in volatility and variance terms; volatility is non-additive, so factor and specific volatility do not sum to total volatility, but variance does.

class serenity_types.risk.factor.RiskBreakdown(*, bySector: List[SectorLevelRisk], byAsset: List[AssetRisk])[source]

Bases: CamelModel

Collection of dimensions along which risk can be broken down.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

by_asset: List[AssetRisk]

The risk values for all of the assets in the portfolio for the given risk measure, e.g. absolute vs. relative risk.

by_sector: List[SectorLevelRisk]

The risk values at each level in the sector hierarchy for all of the sectors represented in the portfolio for the given risk measure, e.g. absolute vs. relative risk.

class serenity_types.risk.factor.SectorFactorExposure(*, factor: str, sectorLevels: List[str], absoluteRisk: float, relativeRisk: float, marginalRisk: float, factorExposure: FactorExposureValue)[source]

Bases: CamelModel

This object supports breaking down risk by sector and factor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

absolute_risk: float

Absolute contribution of this factor to the portfolio’s overall volatility, i.e. the total amount of volatility attributable to this factor.

factor: str

Name of the factor from the risk model, e.g. Momentum.

factor_exposure: FactorExposureValue

The exposure at this hierarchy level to this factor.

marginal_risk: float

Marginal contribution of this factor to the portfolio’s overall volatility, i.e. how much additional exposure to this factor would increase the volatility

relative_risk: float

Relative contribution of this factor to the portfolio’s overall volatility, i.e. the fraction of the volatility attributable to this factor.

sector_levels: List[str]

A list of sector level names that identifies a “path” to a particular level in the sector taxonomy, as defined above.

class serenity_types.risk.factor.SectorLevelRisk(*, factorRisk: float, specificRisk: float, totalRisk: float, sectorLevels: List[str])[source]

Bases: Risk

This object supports the “Breakdown” views By Sector & Asset and By Sector & Factor. The way to think about this one is the factor, specific & total risk for each supported risk contribution type, absolute and marginal at each level in the sector hierarchy gets one of these objects.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

sector_levels: List[str]

A list of sector level names that identifies a “path” to a particular level in the sector taxonomy; as many of the risk values are non-additive, the output must provide every level explicitly, e.g. [‘Sector A’], [‘Sector A’, ‘Sub-sector A’] and [‘Sector A’, ‘Sub-sector A’, ‘Industry A’] would all be in the by_sector array.

class serenity_types.risk.factor.TotalFactorRisk(*, factor: str, absoluteContribution: float, relativeContribution: float, marginalContribution: float, factorExposure: FactorExposureValue)[source]

Bases: CamelModel

This object supports the Breakdown view By Factor, which shows the portfolio-level factor risk contributions and exposures.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

absolute_contribution: float

Absolute contribution of this factor to the portfolio’s overall volatility, i.e. the total amount of volatility attributable to this factor

factor: str

Name of the factor from the risk model, e.g. Momentum.

factor_exposure: FactorExposureValue

The exposure of the whole portfolio to this factor.

marginal_contribution: float

Marginal contribution of this factor to the portfolio’s overall volatility, i.e. how much would additional exposure to this factor increase the volatility

relative_contribution: float

Relative contribution of this factor to the portfolio’s overall volatility, i.e. the fraction of the volatility attributable to this factor

class serenity_types.risk.factor.TotalRisk(*, volatility: Risk, variance: Risk)[source]

Bases: CamelModel

This object, returned at the top level, gives you a summary of the factor, specific and total risk expressed in both volatility and variance for the whole portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

variance: Risk

Factor, specific and total variance of the portfolio.

volatility: Risk

Factor, specific and total volatility of the portfolio.

serenity_types.risk.measures

Serializables needed for the computation of the distribution measures.

class serenity_types.risk.measures.AssetContribution(*, assetId: UUID, values: Dict[str, float | None])[source]

Bases: CamelModel

The risk measure values for an asset

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

The asset_id

values: Dict[str, float | None]

The risk measure values, or contribution values, for each risk-measure tag Null values are not included in the response.

class serenity_types.risk.measures.MeasureParameters(*, measureType: MeasureType, tag: str = '', confidenceLevel: ConstrainedDecimalValue | None = None)[source]

Bases: CamelModel

Parameters for a single risk measure.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

confidence_level: Decimal | None

The confidence level value. Needed for distortion measures such as VaR and CVaR. Not needed for volatility.

Note: using “confidence_level” as the parameter name makes it clear that you are looking for the value below which a certain percentage of the distribution lies, rather than simply a specific percentile or quantile.

measure_type: MeasureType

The risk measure type chosen from the list of risk measure types.

tag: str

The tag of the risk measure, unique within the list of risk measures.

class serenity_types.risk.measures.MeasureType(value)[source]

Bases: Enum

Enum for the distribution measure types.

CGAR = 'CGaR'

The Conditional Gain at Risk, i.e. the expected gain given that the gain is greater than the GaR.

CVAR = 'CVaR'

The Conditional Value at Risk, i.e. the expected loss given that the loss is greater than the VaR.

DOWNDEV = 'DownsideDev'

The losses standard deviation.

GAR = 'GaR'

The Gain at Risk, i.e. the expected gain at the given confidence level.

KGAR = 'KGaR'

The (biased) Kernel Gain at Risk, i.e. the expected gain around the given confidence level.

KVAR = 'KVaR'

The (biased) Kernel Value at Risk, i.e. the expected loss around the given confidence level.

STDEV = 'StDev'

The standard deviation of the distribution.

UPDEV = 'UpsideDev'

The gains standard deviation.

VAR = 'VaR'

The standard Value at Risk, i.e. the expected loss at the given confidence level.

class serenity_types.risk.measures.OTCAssetContribution(*, otcAssetId: str, otcAssetType: OTCAssetTypes, values: Dict[str, float | None])[source]

Bases: CamelModel

The risk measure values for an OTC asset

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

otc_asset_id: str

User specified unique identifier of the OTC asset.

otc_asset_type: OTCAssetTypes

Serenity classification of assets

values: Dict[str, float | None]

The risk measure values, or contribution values, for each risk-measure tag Null values are not included in the response.

class serenity_types.risk.measures.OTCAssetPosition(*, otcAssetId: str, quantity: float, otcAssetType: OTCAssetTypes | None = OTCAssetTypes.OPTION_VANILLA, bookingDetails: OTCOptionVanillaBookingDetails)[source]

Bases: CamelModel

A simple representation of holding a certain amount of a given OTC asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

booking_details: OTCOptionVanillaBookingDetails

Specify the OTC asset booking details.

otc_asset_id: str

User specified unique identifier of the OTC asset.

otc_asset_type: OTCAssetTypes | None

The OTC asset type. Currently only support OTC option vanilla.

quantity: float

The number of OTC asset held in this position. If positive this indicates a long position; if negative, a short one.

class serenity_types.risk.measures.OTCAssetTypes(value)[source]

Bases: Enum

Enum for the OTC asset types.

OPTION_VANILLA = 'OPTION_VANILLA'

OTC Option vanilla asset type.

class serenity_types.risk.measures.OTCOptionVanillaBookingDetails(*, optionType: OptionType, optionStyle: OptionStyle = OptionStyle.EUROPEAN, strikePrice: float, expiryDatetime: datetime, underlierAssetId: UUID, quoteAssetId: UUID, contractSize: float, settlementAssetId: UUID, settlementType: SettlementType)[source]

Bases: CamelModel

OTC option vanilla booking details.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

contract_size: float

Size of the contract in qty of underlying.

expiry_datetime: datetime

Expiration datetime for this option.

option_style: OptionStyle

Exercise type for this option, e.g. European exercise.

option_type: OptionType

Whether this is a put or call contract.

quote_asset_id: UUID

The quote asset_id for this derivative contract, e.g. USD (a9bc74b3-c761-4446-b4f2-725ae1dcf4fc).

settlement_asset_id: UUID

The asset that this derivatives settles in, e.g. on Deribit, CASH settled, it might be USD. Note we will be switching to the Exposure UUID instead in a future release.

settlement_type: SettlementType

Whether this contract settles in cash or in the underlying itself.

strike_price: float

Strike price for the option contract, e.g. 20000.

underlier_asset_id: UUID

The underlier asset_id for this derivative contract, e.g. BTC (78e2e8e2-419d-4515-9b6a-3d5ff1448e89).

class serenity_types.risk.measures.PortfolioRiskMeasuresValue(*, values: Dict[str, float | None], pv: float | None | None = None, riskRatio: Dict[str, float | None] | None = None)[source]

Bases: CamelModel

The portfolio values, pv, and risk ratio

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

pv: float | None

The portfolio present value. Set to None for null responses.

risk_ratio: Dict[str, float | None] | None

The ratio between the portfolio risk measures and the portfolio present value

values: Dict[str, float | None]

The portfolio risk measure values, or contribution values. Null values are not included in the response.

class serenity_types.risk.measures.PortfolioRiskResponse(*, asOfDatetime: str | None = None, request: RiskComputationRequest, portfolio: PortfolioRiskMeasuresValue, contributions: List[AssetContribution | OTCAssetContribution], pnlRiskScenarios: List[float | None])[source]

Bases: CamelModel

Results for the risk measures.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_datetime: str | None

The latest date time of the reference data used to compute the risk scenarios

contributions: List[AssetContribution | OTCAssetContribution]

The contributions to the portfolio risk measures by each component asset

pnl_risk_scenarios: List[float | None]

The list of portfolio P&L risk scenarios

portfolio: PortfolioRiskMeasuresValue

The portfolio pv, values, and risk ratio.

request: RiskComputationRequest

The request that generated the response

class serenity_types.risk.measures.RichRiskMeasuresRequest(*, portfolio: List[AssetPosition | OTCAssetPosition], riskComputationRequest: RiskComputationRequest, asOfTime: datetime | None = None)[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_time: datetime | None
portfolio: List[AssetPosition | OTCAssetPosition]
risk_computation_request: RiskComputationRequest
classmethod validate_portfolio(values)[source]
class serenity_types.risk.measures.RiskComputationRequest(*, lookbackDays: ConstrainedIntValue = 365, samplingHours: ConstrainedIntValue = 1, horizonScale: ConstrainedDecimalValue = Decimal('1'), measures: List[MeasureParameters] | None = None)[source]

Bases: CamelModel

Configuration for the risk measures.

Parameters:

lookback_days – The lookback period expressed in days.

## Notes on the parameters

### The lookback days parameter

The term “lookback_days” refers to the time period over which historical data is considered when computing risk. It represents the number of days in the past that are taken into account for analyzing and calculating risk. In risk analysis, historical data is often used to assess the probability and potential impact of future events or outcomes. By examining past data, patterns, and trends, you can gain insights into the potential risks associated with a particular system, investment, or activity. The “lookback_days” parameter allows you to specify how far back in time you want to analyze historical data when calculating risk. For example, if you set “lookback_days” to 360, it means you are considering the data from the past year for risk assessment. The appropriate value for “lookback_days” depends on the specific context and requirements of your risk calculation, however setting the “lookback_days” parameter to 360 is a good starting point for in most cases.

### The sampling hours parameter

The term “sampling_hours” typically refers to the time interval between each sample when computing risk. It represents the duration for which data is collected or observed to analyze and calculate risk. For example, in the context of your hourly samples, the “sampling_hours” would be 1 hour since you are collecting data on an hourly basis. Each sample represents a data point collected at a specific hour, and the “sampling_hours” indicates the time span between consecutive samples. If daily samples are collected, then the “sampling_hours” would be 24 hours. Each sample represents a data point collected. In order to increase the accuracy of your distribution, the advice is to keep the “sampling_hours” as low as possible. The “sampling_hours” value of 1 hour is a good starting point for most cases. In case that daily scenarios are needed, the advice is to still keep the “sampling_hours” as 1 and to set the “horizon_scale” to 24.

### The horizon scale parameter

The term “horizon_scale” refers to the time period or duration over which the risk is projected. It represents the length of time, in “sampling_hours”, for which the risk assessment is made. The “horizon_scale” parameter allows you to specify the desired time horizon for risk analysis. It determines the timeframe within which the risks and their associated probabilities and impacts are evaluated. The choice of “horizon_scale” depends on the specific requirements and objectives of the risk assessment. When the “sampling_hours” is set to 1, the “horizon_scale” is expressed in hours. For example, if you set “horizon_scale” to 24 hours, it means that the risk analysis will project or estimate the potential risks and their magnitudes over a 24-hour timeframe, i.e. of one day. While, in theory, the “horizon_scale” can be set to any value, it is recommended to keep it as low as possible and not to exceed the 48 hours. The reason for this is that the accuracy of the risk assessment decreases as the “horizon_scale” increases. This is because the risk assessment is based on historical data, and the further back in time you go, the less relevant the data becomes.

### The measures parameter

The term “measures” refers to the list of risk measures parameters. It represents the list of distribution measures that are computed for the given portfolio. The list of possible distribution measures is specified in the “MeasureType” enumeration. Note that the concentracion measures require the “confidence_level” parameter, while the dispersion measures do not. When the measure parameter is empty in the request, a list of reasonable default measures is used. The default measures are: StDev, VaR, CVaR, GaR, and CGar with a confidence level of 99%. Also note that when the “measures” list contains duplicate tags, only the first occurrence of the tag is used.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

horizon_scale: Decimal

The length of time in sampling hours for which the risk assessment is made.

lookback_days: int

The lookback period expressed in days.

measures: List[MeasureParameters] | None

The list of risk measures parameters

sampling_hours: int

The number of hours between samples.

serenity_types.risk.scenarios

class serenity_types.risk.scenarios.AssetPnL(*, assetId: UUID, sectorLevels: List[str], assetPnl: PnL)[source]

Bases: CamelModel

A single entry representing an asset-level impact of this scenario’s shocks. It supports both by-asset and by-sector views in Serenity UX.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

Unique asset identifier from the Asset Master.

asset_pnl: PnL

P&L impact in total and by shock for this asset.

sector_levels: List[str]

A list of sector level names that identifies a “path” to a particular level in the sector taxonomy, as defined above; note we only have the leaf level here; we don’t need to show PnL at each level in the sector hierarchy above the assets, UX can do the aggregation since $ values are additive here.

class serenity_types.risk.scenarios.CustomScenarioGeneratorRequest(*, name: str, startDate: date, endDate: date, modelConfigId: UUID)[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

end_date: date

End of the shock period.

model_config_id: UUID

The model config to use with the Scenario

name: str

A descriptive name for this scenario.

start_date: date

Start of the shock period.

class serenity_types.risk.scenarios.FactorPnL(*, factor: str, factorExposureBaseCcy: float, factorPnl: PnL)[source]

Bases: CamelModel

A single entry representing a factor-level impact of this scenario’s shocks.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

factor: str

Factor name, e.g. MOMENTUM.

factor_exposure_base_ccy: float

Total factor exposure in the portfolio, in base currency.

factor_pnl: PnL

P&L impact in total and by shock for this factor.

class serenity_types.risk.scenarios.PnL(*, basePnl: float, totalShockPnl: float, pnlByShock: List[ShockPnL])[source]

Bases: CamelModel

Value object with information about a particular dimension’s P&L impact from all shocks.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_pnl: float

The PnL, in base currency, over the period (default 1 day) absent all the shocks, e.g. portfolio lost $12K in the last 24 hours.

pnl_by_shock: List[ShockPnL]

The PnL, in base currency, from applying each shock individually, e.g. the portfolio would have lost $4K from shocking ETH down 10% and $35K from shocking BTC down 10%.

total_shock_pnl: float

The PnL, in base currency, from all shocks combined, e.g. the portfolio would have lost an additional $50K if all shocks had been applied.

class serenity_types.risk.scenarios.RunStatus(value)[source]

Bases: Enum

Results of the scenario run at a high level.

COMPLETED = 'COMPLETED'

Job completed with no errors.

FAILED = 'FAILED'

Job failed with an error.

RUNNING = 'RUNNING'

Job sent to the scenario engine and running, may be async / long-running.

class serenity_types.risk.scenarios.ScenarioCloneRequest(*, scenarioId: UUID, scenarioName: str)[source]

Bases: CamelModel

A request to clone an existing scenario; typically used to allow the client to customize a canned scenario.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

scenario_id: UUID

Unique ID of the custom or predefined scenario to clone.

scenario_name: str

Name to use post-cloning to avoid ambiguity.

class serenity_types.risk.scenarios.ScenarioDefinition(*, scenarioId: UUID | None = None, scenarioVersion: int | None = None, source: ScenarioSource, name: str, shocks: List[Shock], deleted: bool | None = False, lastUpdated: datetime | None = None, lastUpdatedBy: str, owner: str | None = None, modelConfigId: UUID | None = None, startDateDisplay: date | None = None, endDateDisplay: date | None = None, description: str | None = None)[source]

Bases: CamelModel

A complete definition of a stress test to perform for scenario analysis.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

deleted: bool | None

If set, this definition was logically deleted in the database and is not current.

description: str | None

Description for the Scenario

end_date_display: date | None

The end date of the Scenario

last_updated: datetime | None

Last update timestamp, in UTC.

last_updated_by: str

Last update user.

model_config_id: UUID | None

The model config to use with the Scenario

name: str

A descriptive name for this scenario.

owner: str | None

Owner of the Scenario.

scenario_id: UUID | None

Unique ID for this scenario, optional when creating or if we are dealing with a transient scenario to run.

scenario_version: int | None

Monotonically increasing version number, optional when creating or if we are dealing with a transient scenario to run.

shocks: List[Shock]

The discrete shocks to apply as part of this scenario.

source: ScenarioSource

Whether this shock is user- or system-defined.

start_date_display: date | None

The start date of the Scenario

class serenity_types.risk.scenarios.ScenarioRequest(*, scenarioId: UUID | None = None, scenario: ScenarioDefinition | None = None, portfolio: SimplePortfolio, pricingContext: PricingContext | None = None, sectorTaxonomyId: UUID | None = None, modelConfigId: UUID, startDate: date | None = None, endDate: date | None = None, schemaVersion: int | None = None)[source]

Bases: CamelModel

A request to run a scenario against a portfolio. This scenario may be stored or transient.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

end_date: date | None

End of the shock period; in the instantaneous case, same as start_date.

model_config_id: UUID

Factor model configuration ID to use for risk purposes.

portfolio: SimplePortfolio

Portfolio to run the scenario on.

pricing_context: PricingContext | None

Common model inputs, e.g. mark time.

scenario: ScenarioDefinition | None

Transient scenario to run; if not provided, user must provide a scenario ID instead.

scenario_id: UUID | None

Unique ID of the scenario to run; if not provided, user must provide a transient scenario instead.

schema_version: int | None

Version number for the scenario schema.

sector_taxonomy_id: UUID | None

References a taxonomy UUID from the Refdata API, specifically the getSectorTaxonomies call.

start_date: date | None

Start of the shock period; in the instantaneous case, same as end_date.

class serenity_types.risk.scenarios.ScenarioResult(*, portfolioPnl: PnL, assetPnl: List[AssetPnL], factorPnl: List[FactorPnL] | None = None, startDate: date, endDate: date, scenarioRunId: UUID, warnings: List[str] | None = None, schemaVersion: int | None = None)[source]

Bases: CamelModel

ScenarioResult provides the portfolio base & shock P&L and the breakdowns by asset, sector and by factor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_pnl: List[AssetPnL]

Report on P&L impact by asset & sector.

end_date: date

End of the shock period; in the instantaneous case, same as start_date.

factor_pnl: List[FactorPnL] | None

Report on P&L impact by risk factor in the provided factor risk model.

portfolio_pnl: PnL

The impact to the portfolio broken out by shocks.

scenario_run_id: UUID

The run that this result is associated with.

schema_version: int | None

Version number for the scenario schema.

start_date: date

Start of the shock period; in the instantaneous case, same as end_date.

warnings: List[str] | None

Any warnings generated at the time of the run.

class serenity_types.risk.scenarios.ScenarioRun(*, runId: UUID, scenarioRequest: ScenarioRequest, status: RunStatus, basePnl: float | None = None, totalShockPnl: float | None = None, startDatetime: datetime, endDatetime: datetime | None = None)[source]

Bases: CamelModel

A summary of the run. Note that to get the detail you need to call getScenarioRun with the runId; this just gives you the status, the base PnL absent all the shocks and the total shock PnL.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_pnl: float | None

The PnL, in base currency, over the period (default 1 day) absent all the shocks, e.g. portfolio lost $12K in the last 24 hours.

end_datetime: datetime | None

UTC datetime of the run completion, if COMPLETED.

run_id: UUID

Unique ID of this run.

scenario_request: ScenarioRequest

The request that was run previously.

start_datetime: datetime

UTC datetime of the run start.

status: RunStatus

Current state of the run.

total_shock_pnl: float | None

the PnL, in base currency, from all shocks combined, e.g. the portfolio would have lost an additional $50K if all shocks had been applied.

class serenity_types.risk.scenarios.ScenarioSource(value)[source]

Bases: Enum

Enum classifying scenarios by whether they are user- or system-defined.

CUSTOM = 'CUSTOM'

A user-defined scenario.

CUSTOM_GENERATED = 'CUSTOM_GENERATED'

Custom date range-based scenario using Serenity’s model for shock generation.

PREDEFINED = 'PREDEFINED'

A canned scenario provided by the platform; typically these represent fitted historical events like the 2020 COVID Crash.

class serenity_types.risk.scenarios.Shock(*, shockId: UUID | None = None, targetType: ShockTo, shockTarget: UUID | str, magnitude: float)[source]

Bases: CamelModel

A discrete market shock that is being simulated in a scenario.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

magnitude: float

Magnitude of the shock, + / - for up or down shock actions; note this is expressed as a fraction, not a percentage.

shock_id: UUID | None

Unique ID for the shock; this can be generated and stored with the ShockDefinition (and thus unchanging) or if the scenario is run on-the-fly, the UUID should be generate at request time so there is a clear linkage between Shock and ShockPnL.

shock_target: UUID | str

UUID for asset ID, or name of the factor to shock.

target_type: ShockTo

What to shock: asset returns or factor returns?

class serenity_types.risk.scenarios.ShockPnL(*, shockId: UUID, shockPnl: float)[source]

Bases: CamelModel

Value object with information about a particular dimension’s P&L impact from a single shock.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

shock_id: UUID

Unique ID for the shock from the original ShockDefinition.

shock_pnl: float

The PnL, in base currency, from the shock, e.g. the portfolio would have lost an additional $2K if this shock had been applied.

class serenity_types.risk.scenarios.ShockTo(value)[source]

Bases: Enum

Enum classifying what is being shocked, e.g. asset returns or factor returns.

ASSET = 'ASSET'

Shock applied additively to the asset’s returns at the close, per MarkTime.

FACTOR = 'FACTOR'

Shock applied additively to the factor’s returns at the close, per MarkTime.

serenity_types.storage.core

show-inheritance:

class serenity_types.storage.core.DatasetContent(value)[source]

Bases: Enum

Enum for the available dataset contents.

CTM_BASIS = 'CTM_BASIS'
CTM_PROJ_RATE = 'CTM_PROJ_RATE'
class serenity_types.storage.core.DatasetContentInfo(*, datasetContent: DatasetContent, datasetContentTimeRange: Dict[UUID, Dict[UUID, DatasetContentTimeRange]])[source]

Bases: CamelModel

Model to represents dataset content information.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

dataset_content: DatasetContent

The dataset content.

dataset_content_time_range: Dict[UUID, Dict[UUID, DatasetContentTimeRange]]

The dataset content availability datetime range. By underlier asset UUID and exchange UUID.

class serenity_types.storage.core.DatasetContentTimeRange(*, minDatetime: datetime, maxDatetime: datetime)[source]

Bases: CamelModel

The dataset content availability datetime range.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

max_datetime: datetime

The maximum / latest dataset content datetime.

min_datetime: datetime

The minimum / earliest dataset content datetime.

classmethod min_max_datetime(values)[source]
class serenity_types.storage.core.DatasetContentUrlAndToken(*, datasetContentInfo: DatasetContentInfo, rootUrl: str, prefix: str, sasToken: str, fullListFilesUrl: str)[source]

Bases: CamelModel

Returns generated URL and SAS token to access dataset content.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

dataset_content_info: DatasetContentInfo

Dataset content information.

full_list_files_url: str

The full URL to list dataset content files. i.e. {root_url}/{prefix}/{sas_token}.

prefix: str

Prefix for the dataset content location.

root_url: str

Root URL to access Serenity.

sas_token: str

Temporary SAS token to access Serenity.

serenity_types.valuation.benchmark

show-inheritance:

class serenity_types.valuation.benchmark.BenchmarkMetadata(*, metadataId: UUID, benchmarkType: BenchmarkType, effectiveDatetime: datetime, updatedAt: datetime, updatedBy: str, owner: str | None = None, baseCurrencyId: UUID, symbol: str | None = None, displayName: str | None = None, description: str | None = None, providerId: UUID | None = None, indexFamily: str | None = None, licenseRequired: bool = False, licenseContact: str | None = None, autoRebalancing: bool = False, autoRebalancingDefinition: CustomBenchmarkAutoRebalancingDefinition | None = None)[source]

Bases: CamelModel

Metadata describing a particular benchmark offering.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

auto_rebalancing: bool

Flag to indicate if Serenity should do auto rebalancing for the specified CUSTOM benchmark.

If set to True, Serenity will automatically generated the benchmark snapshots based on auto_rebalancing_definition and users are not allowed to manually create/update snapshots for this benchmark metadata.

auto_rebalancing_definition: CustomBenchmarkAutoRebalancingDefinition | None

Custom benchmark auto rebalancing definition. Optional unless CUSTOM and auto_rebalancing is set to True.

base_currency_id: UUID

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD.

benchmark_type: BenchmarkType

Classification for this benchmark.

description: str | None

Longer human-readable description of this index and its essential methodology. Required for CUSTOM, PRELOADED, PREDEFINED.

display_name: str | None

Short human-readable name for this index, e.g. MarketVector Digital Assets 100. Required for CUSTOM, PRELOADED, PREDEFINED.

effective_datetime: datetime

The effective datetime for this benchmark metadata.

index_family: str | None

Grouping that this benchmark index belongs to; typically used for PRELOADED, for vendors.

license_contact: str | None

If client not licensed, who should they be prompted to contact? Only applies to PRELOADED.

license_required: bool

Does the client require a license for the index in order to use it? Only applies to PRELOADED.

metadata_id: UUID

Serenity’s unique ID for this benchmark metadata.

owner: str | None

The primary owner of this benchmark.

provider_id: UUID | None

Organization ID from Serenity’s database. Optional unless PRELOADED.

symbol: str | None

Conventional symbol used for this index, e.g. MVDA.

updated_at: datetime

Last update timestamp, in UTC.

updated_by: str

Last update user.

class serenity_types.valuation.benchmark.BenchmarkMetadataAndSnapshotInfo(*, benchmarkMetadata: BenchmarkMetadata, benchmarkLatestSnapshot: BenchmarkSnapshotInfo | None = None)[source]

Bases: CamelModel

” Output response containing benchmark metadata and its latest snapshot info.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

benchmark_latest_snapshot: BenchmarkSnapshotInfo | None

The corresponding latest benchmark latest snapshot info.

benchmark_metadata: BenchmarkMetadata

The benchmark metadata.

class serenity_types.valuation.benchmark.BenchmarkSnapshot(*, snapshotId: UUID, metadataId: UUID, effectiveDatetime: datetime, updatedAt: datetime, updatedBy: str, compositionHistory: PortfolioComposition | CustomizedPortfolioComposition)[source]

Bases: BenchmarkSnapshotInfo

Snapshot of the positions of a benchmark at a specific point in time.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

composition_history: PortfolioComposition | CustomizedPortfolioComposition

The benchmark snapshot composition history.

class serenity_types.valuation.benchmark.BenchmarkSnapshotInfo(*, snapshotId: UUID, metadataId: UUID, effectiveDatetime: datetime, updatedAt: datetime, updatedBy: str)[source]

Bases: CamelModel

Benchmak snapshot info.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

effective_datetime: datetime

The effective datetime for this benchmark snapshot.

metadata_id: UUID

The benchmark metadata ID that this benchmark snapshot is part of.

snapshot_id: UUID

Serenity’s unique ID for this benchmark snapshot.

updated_at: datetime

Last update timestamp, in UTC.

updated_by: str

Last update user.

class serenity_types.valuation.benchmark.BenchmarkType(value)[source]

Bases: Enum

Simple classification of the type of benchmark, reflective of its origin and who maintains it.

CUSTOM = 'CUSTOM'

A benchmark created by the client themselves and stored on the server.

PREDEFINED = 'PREDEFINED'

A benchmark offered as part of Serenity, owned and maintained by the Cloudwall Research team.

PRELOADED = 'PRELOADED'

A benchmark offered by a third party vendor like MSCI or S&P.

TRANSIENT = 'TRANSIENT'

A benchmark provided as input ot analytics with zero information about where it came from, methodology, etc.. In V1 this is the only type of benchmark we need to support, with minimal metadata.

class serenity_types.valuation.benchmark.CreateCustomBenchmarkSnapshotRequest(*, effectiveDatetime: datetime | None = None, compositionHistory: PortfolioComposition | CustomizedPortfolioComposition, metadataId: UUID)[source]

Bases: CustomBenchmarkSnapshotRequest

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

metadata_id: UUID

Serenity’s unique ID for the benchmark metadata.

class serenity_types.valuation.benchmark.CustomBenchmarkAutoRebalancingDefinition(*, initialWeights: List[AssetWeight], initialCashQuantity: float, startDatetime: datetime, endDatetime: datetime | None = None, closeFrequency: PortfolioTimeseriesFrequency | None = PortfolioTimeseriesFrequency.DAILY, markTime: MarkTime | None = MarkTime.UTC, rebalancingFrequency: RebalancingFrequency | None = RebalancingFrequency.DAILY)[source]

Bases: CamelModel

Custom benchmark with auto rebalancing feature definition. From an initial cash positions and a set of weights and a rebalancing rule, the server then generates a series of positions at a given frequency, e.g. daily, rebalancing periodically to bring the positions in line with the desired weights.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_initial_weights_sum(values)[source]
close_frequency: PortfolioTimeseriesFrequency | None

When generating the position time series, the frequency of balance snapshots. Where DAILY, the selected mark_time is used as daily close times.

end_datetime: datetime | None

The timestamp of which the generated benchmark snapshot should end. Defaults to None which denotes generated benchmark snapshot to always have latest date position.

initial_cash_quantity: float

Amount of cash in the portfolio at inception. In current implementation defaults to USD.

initial_weights: List[AssetWeight]

The model portfolio allocation in terms of weights. At start_datetime the system will buy the assets using the initial_cash_quantity and then periodically accordingly to rebalance_frequency will generate buys and sells to bring the allocation back in line with the initial weights.

mark_time: MarkTime | None

The close time convention to use for close-on-close prices in the 24x7 market. Defaults to UTC midnight.

rebalancing_frequency: RebalancingFrequency | None

Frequency at which the system revaluates positions and weights to bring the allocation back in line with the initial_weights.

start_datetime: datetime

The timestamp of which the generated benchmark snapshot should start from.

class serenity_types.valuation.benchmark.CustomBenchmarkMetadataRequest(*, displayName: str, description: str | None = None, effectiveDatetime: datetime | None = None, owner: str | None = None, symbol: str | None = None, baseCurrencyId: UUID | None = None, autoRebalancing: bool = False, autoRebalancingDefinition: CustomBenchmarkAutoRebalancingDefinition | None = None)[source]

Bases: CamelModel

Input for creating/updating custom benchmark metadata.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

auto_rebalancing: bool

Flag to indicate if Serenity should do auto rebalancing for the specified CUSTOM benchmark.

auto_rebalancing_definition: CustomBenchmarkAutoRebalancingDefinition | None

Custom benchmark auto rebalancing definition. Optional unless auto_rebalancing is set to True.

base_currency_id: UUID | None

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD. Defaults to USD if it’s not provided.

description: str | None

Longer human-readable description of this index and its essential methodology.

display_name: str

Short human-readable name for this index, e.g. MarketVector Digital Assets 100.

effective_datetime: datetime | None

The effective datetime for this benchmark metadata. If not specified, defaults to current datetime.

owner: str | None

The primary owner of this benchmark.

symbol: str | None

Conventional symbol used for this index, e.g. MVDA.

class serenity_types.valuation.benchmark.CustomBenchmarkSnapshotRequest(*, effectiveDatetime: datetime | None = None, compositionHistory: PortfolioComposition | CustomizedPortfolioComposition)[source]

Bases: CamelModel

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

composition_history: PortfolioComposition | CustomizedPortfolioComposition

The history of index holdings.

effective_datetime: datetime | None

The effective datetime for this benchmark metadata. If not specified, defaults to current datetime.

class serenity_types.valuation.benchmark.UpdateCustomBenchmarkSnapshotRequest(*, effectiveDatetime: datetime | None = None, compositionHistory: PortfolioComposition | CustomizedPortfolioComposition)[source]

Bases: CustomBenchmarkSnapshotRequest

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

composition_history: PortfolioComposition | CustomizedPortfolioComposition

The history of index holdings.

effective_datetime: datetime | None

The effective datetime for this benchmark metadata. If not specified, defaults to current datetime.

serenity_types.valuation.core

show-inheritance:

class serenity_types.valuation.core.AssetWeight(*, assetId: UUID, weight: float)[source]

Bases: CamelModel

Tuple representing a single position represented as an asset and a percentage weight: an allocation.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

Unique ID for the asset from the Serenity asset master.

weight: float

Allocated weight for this asset, expressed as a fraction.

class serenity_types.valuation.core.BasePortfolioComposition(*, asOfTimes: List[datetime], weights: List[List[float]] | None = None, quantities: List[List[float]] | None = None)[source]

Bases: CamelModel

Base portfolio/benchmark composition. Different portfolios/benchmarks rebalance at different times, and according to their own rules, and this cannot be captured in simple metadata. We just capture the output, provided by the vendor.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: List[datetime]

Series of timestamps of the compositions. Generally it’s a date midnight, but for full generality expressed as a datetime.

classmethod check_as_of_times_include_tz(as_of_times)[source]
quantities: List[List[float]] | None

Composition by specifying quantity for each as_of_time, asset_id pair Should not be used together with ‘weight’.

classmethod validate_all_fields(values)[source]
weights: List[List[float]] | None

Composition by specifying percentage weights, expressed as fractions for each as_of_time, asset_id pair Should not be used together with ‘quantity’.

class serenity_types.valuation.core.CompoundingFrequency(value)[source]

Bases: Enum

Compounding frequency inputs for returns data

DAILY = 365
HOURLY = 8760
MONTHLY = 12
WEEKLY = 52
YEARLY = 1
class serenity_types.valuation.core.CompoundingFrequencyInput(value)[source]

Bases: Enum

Compounding frequency inputs for returns data

DAILY = 'DAILY'
HOURLY = 'HOURLY'
MONTHLY = 'MONTHLY'
WEEKLY = 'WEEKLY'
YEARLY = 'YEARLY'
class serenity_types.valuation.core.CorePortfolioCompositionAndTrades(*, trades: Trades | None = None, transfers: Transfers | None = None, positions: PortfolioComposition | CustomizedPortfolioComposition)[source]

Bases: PortfolioTradesAndTransfers

Specify portfolio compositions by values, trades, and transfers.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

positions: PortfolioComposition | CustomizedPortfolioComposition

Series of portfolio weights or quantities of Serenity supported assets or custom assets.

class serenity_types.valuation.core.CustomizedPortfolioComposition(*, asOfTimes: List[datetime], weights: List[List[float]] | None = None, quantities: List[List[float]] | None = None, transientAssetIds: List[str], prices: List[List[float]])[source]

Bases: BasePortfolioComposition

Series of portfolio/benchmark weights or positions for all custom assets.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_duplicated_transient_asset_ids(transient_asset_ids)[source]
prices: List[List[float]]

Series of user specified mark prices, presumed in V1 to be USD only, which were used to calculate NAV. Mandatory field for CustomizedPortfolioComposition.

transient_asset_ids: List[str]

Series of unique custom asset identifiers. This can be anything as long as each transient_asset_ids is unique.

class serenity_types.valuation.core.NetDeltaConversionRequest(*, portfolio: List[AssetPosition], pricingContext: PricingContext | None = None)[source]

Bases: CamelModel

Request to do net delta equivalent conversion for a given portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod merge_duplicated_asset_positions(values)[source]
portfolio: List[AssetPosition]

Basic, moment-in time image of the portfolio to be valued.

pricing_context: PricingContext | None

Common settings related to how to value the portfolio, e.g. which prices to load.

class serenity_types.valuation.core.PortfolioByMetadataIdOrCompositionValue(*, metadataId: UUID | None = None, portfolioEndDatetime: datetime | None = None, portfolioStartDatetime: datetime | None = None, positions: PortfolioComposition | CustomizedPortfolioComposition | None = None)[source]

Bases: CamelModel

Specify portfolio and/or benchmark positions composition by metadata id or by value.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_metadata_id_or_positions(values)[source]
metadata_id: UUID | None

Portfolio / Benchmark metadata ID used to retrieve the balances if parameter positions is not specified.

portfolio_end_datetime: datetime | None

The end datetime used to determine which portfolio / benchmark snapshot to be used. Defaults to the current datetime.

portfolio_start_datetime: datetime | None

The start datetime used to determine which portfolio / benchmark snapshot to be used. Defaults to the portfolio_end_datetime - 30 days.

positions: PortfolioComposition | CustomizedPortfolioComposition | None

Series of portfolio / benchmark weights or quantities of Serenity supported assets or custom assets.

class serenity_types.valuation.core.PortfolioComposition(*, asOfTimes: List[datetime], weights: List[List[float]] | None = None, quantities: List[List[float]] | None = None, assetIds: List[UUID], prices: List[List[float]] | None = None)[source]

Bases: BasePortfolioComposition

Series of portfolio/benchmark weights or positions for all Serenity supported assets.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_ids: List[UUID]

Series of unique asset identifiers from Serenity asset master.

classmethod check_duplicated_asset_ids(asset_ids)[source]
prices: List[List[float]] | None

Series of user specified mark prices, presumed in V1 to be USD only, which were used to calculate NAV. Optional field for PortfolioComposition. If not specified, use Serenity’s sourced prices.

class serenity_types.valuation.core.PortfolioCompositionAndTrades(*, trades: Trades | None = None, transfers: Transfers | None = None, portfolioComposition: PortfolioByMetadataIdOrCompositionValue)[source]

Bases: PortfolioTradesAndTransfers

Specify portfolio compositions by metadata id or values, trades, and transfers.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

portfolio_composition: PortfolioByMetadataIdOrCompositionValue

Series of portfolio weights or quantities of Serenity supported assets or custom assets.

class serenity_types.valuation.core.PortfolioTimeseriesAndTrades(*, positions: PositionTimeseries, trades: Trades | None = None, transfers: Transfers | None = None)[source]

Bases: CamelModel

Portfolio quantity timeseries, trades, and transfers.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

positions: PositionTimeseries

Series of portfolio quantities of Serenity supported assets.

trades: Trades | None

Trades associated with this portfolio.

transfers: Transfers | None

Transfers associated with this portfolio.

class serenity_types.valuation.core.PortfolioTimeseriesFrequency(value)[source]

Bases: Enum

When creating a portfolio from weights or trades and transfers, how frequently to generate snapshots with position balances.

DAILY = 'DAILY'

Compute position balances at the end of each day at a daily close based on MarkTime.

HOURLY = 'HOURLY'

Compute position balances at the end of each hourly period.

MONTHLY = 'MONTHLY'

Compute position balances at the end of each month at a daily close based on MarkTime.

class serenity_types.valuation.core.PortfolioTradesAndTransfers(*, trades: Trades | None = None, transfers: Transfers | None = None)[source]

Bases: CamelModel

Specify portfolio’s trades and transfers.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

trades: Trades | None

Trades associated with this portfolio.

transfers: Transfers | None

Transfers associated with this portfolio.

class serenity_types.valuation.core.PortfolioValuationRequest(*, portfolio: List[AssetPosition], pricingContext: PricingContext)[source]

Bases: CamelModel

Request to do a NAV calculation for a portfolio. This is simple right now, but once we support non-linear assets we will need to extend it.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod merge_duplicated_asset_positions(values)[source]
portfolio: List[AssetPosition]

Basic, moment-in time image of the portfolio to be valued.

pricing_context: PricingContext

Common settings related to how to value the portfolio, e.g. which prices to load.

class serenity_types.valuation.core.PortfolioValuationResponse(*, pricingContext: PricingContext, close: PortfolioValue, previous: PortfolioValue, current: PortfolioValue | None = None, positions: Dict[str, PositionValuation])[source]

Bases: CamelModel

Response with the value of the portfolio at top level plus all position values.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

close: PortfolioValue

The value of the whole portfolio as of the most recent close date.

current: PortfolioValue | None

The value of the whole portfolio as of real-time price.

positions: Dict[str, PositionValuation]

The values of each of the individual positions in the portfolio keyed by asset UUID.

previous: PortfolioValue

The value of the whole portfolio as of the previous close date.

pricing_context: PricingContext

The context that was used to value this portfolio. DEPRECATED, not needed.

class serenity_types.valuation.core.PortfolioValue(*, netHoldingsValue: float, grossHoldingsValue: float, cashPositionValue: float, netAssetValue: float)[source]

Bases: CamelModel

Total value of the portfolio as of a certain time.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

cash_position_value: float

The fiat position or stablecoin equivalent based on settings determining whether stablecoins count as cash.

classmethod convert_nan_to_zero_portfolio_value(values)[source]
gross_holdings_value: float

The sum of the absolute values of all non-cash positions.

net_asset_value: float

NAV, i.e. net_position_value + cash_position_value.

net_holdings_value: float

The sum of the values of all non-cash positions.

class serenity_types.valuation.core.PositionTimeseries(*, asOfTimes: List[datetime], assetIds: List[UUID], quantities: List[List[float]])[source]

Bases: CamelModel

Historical time series of position balances, expressed as quantities.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: List[datetime]

Series of timestamps for the positions.

asset_ids: List[UUID]

Series of unique asset identifiers from the Serenity asset master.

classmethod check_as_of_times_include_tz(as_of_times)[source]
quantities: List[List[float]]

Matrix of quantities for each as_of_time, asset_id pair.

class serenity_types.valuation.core.PositionValuation(*, close: PositionValue, previous: PositionValue, current: PositionValue | None = None)[source]

Bases: CamelModel

Close, previous and current values of a single position in the portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

close: PositionValue

The value of the asset at the MarkTime, as of the most recent close.

current: PositionValue | None

The value of the position as of the current moment. Requires real-time data that will be connected in Q1’23.

previous: PositionValue

The value of the asset at the MarkTime, as of the previous close.

class serenity_types.valuation.core.PositionValue(*, value: float, price: float, qty: float, weight: float)[source]

Bases: CamelModel

Value of a single position in the portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod convert_nan_to_zero_position_value(values)[source]
price: float

The price for this position according to the chosen mark time.

qty: float

The quantity of assets, e.g. 0.7 BTC.

value: float

The value of this position in base currency, e.g. qty * price for simple asset types.

weight: float

The weight of this position in the overall portfolio, as a fraction, e.g. 0.12. This is just the position’s value divided by the portfolio value.

class serenity_types.valuation.core.RebalancingFrequency(value)[source]

Bases: Enum

How often the porfolio rebalances to given weight.

DAILY = 'DAILY'

Perform a daily rebalance at the closing time based on MarkTime.

class serenity_types.valuation.core.ReturnsType(value)[source]

Bases: Enum

Calculation treatment for portfolio returns

LOG = 'LOG'

Use logarithmic returns

SIMPLE = 'SIMPLE'

Use simple percentage returns.

class serenity_types.valuation.core.TradeCommission(*, assetId: UUID, quantity: float)[source]

Bases: CamelModel

A trade commission expressed as an asset rather than USD.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: UUID

Unique ID for the asset from the Serenity asset master.

quantity: float

Quantity of the asset paid as commission.

class serenity_types.valuation.core.Trades(*, tradeDatetime: List[datetime], baseAssetId: List[UUID], quoteAssetId: List[UUID], quantity: List[float], fillPrice: List[float], commissionInUsd: List[float])[source]

Bases: CamelModel

A set of trades applied to a portfolio. All lists are understood in parallel, so index 0 is the first fill in the series, with timestamps, asset ID’s, etc. as separate series.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_asset_id: List[UUID]

Series of unique asset ID’s of the traded instruments, e.g. in BTC-USD, BTC.

classmethod check_all_fields_equal_len(values)[source]
classmethod check_trade_datetime_include_tz(trade_datetime)[source]
commission_in_usd: List[float]

Series of commissions paid for the trades, expressed in USD for convenience. In a future release this will be generalized to use TradeCommission, allowing expression of fees in any asset.

fill_price: List[float]

Series of fill prices for the trades, expressed in quote asset.

quantity: List[float]

Series of fill quantities for the trades.

quote_asset_id: List[UUID]

Series of unique asset ID’s of the quote instruments used to fund the trades, e.g. in BTC-USD, USD.

trade_datetime: List[datetime]

Series of exact timestamps of the trade / fill.

class serenity_types.valuation.core.Transfers(*, transferDatetime: List[datetime], assetId: List[UUID], quantity: List[float])[source]

Bases: CamelModel

A set of transaction moving assets from one account – typically external – in or out of an exchange account.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_id: List[UUID]

Series of unique asset ID’s transferred in or out of the account.

classmethod check_all_fields_equal_len(values)[source]
classmethod check_transfer_datetime_include_tz(transfer_datetime)[source]
quantity: List[float]

Series of transfer amounts.

transfer_datetime: List[datetime]

Series of exact timestamps of the transfers executed.

serenity_types.valuation.portfolio_analytic

show-inheritance:

class serenity_types.valuation.portfolio_analytic.BasePortfolioAnalyticRequest(*, simulatedTrades: Trades | None = None, compoundingFrequency: CompoundingFrequencyInput | None = CompoundingFrequencyInput.DAILY, markTime: MarkTime | None = MarkTime.UTC, returnsType: ReturnsType | None = ReturnsType.SIMPLE, baseCurrencyId: UUID | None = None)[source]

Bases: CamelModel

Base Portfolio Analytic request.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_currency_id: UUID | None

The accounting currency to use for valuation, reporting, etc., e.g. fund reports in USD. Defaults to USD asset id if it’s not provided.

compounding_frequency: CompoundingFrequencyInput | None

Where using logarithmic returns, how frequently are the returns compounded? Where DAILY, the selected mark_time is used as daily close times.

mark_time: MarkTime | None

The close time convention to use for close-on-close prices in the 24x7 market. Defaults to UTC midnight.

returns_type: ReturnsType | None

Calculation treatment for portfolio returns.

simulated_trades: Trades | None

Optional set of trades to overlay on the base portfolio in order to simulate the performance impact of a rebalance or other portfolio composition change.

class serenity_types.valuation.portfolio_analytic.BrinsonAttribution(*, exposures: BrinsonAttributionExposure, asOfTimes: List[datetime], allocation: List[float | None], selection: List[float | None], interaction: List[float | None], activeReturn: List[float | None])[source]

Bases: CamelModel

Brinson attribution results.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

active_return: List[float | None]

Calculated portfolio’s active return. Active return is a directly calculable effect resulting from the sum of all, allocation, selection and interaction effects. It is also a direct measure of portfolio performance, relative to a benchmark.

allocation: List[float | None]

Calculatd portfolio’s allocation return. Allocation refers to the value the portfolio manager adds by having different sector weights in the portfolio than the sector weights in the benchmark.

as_of_times: List[datetime]

Series of timestamps corresponding to the start of each reporting period.

exposures: BrinsonAttributionExposure

Calculated portfolio and benchmarks exposure (compounded over time), by sector.

interaction: List[float | None]

Calculates portfolio’s interaction return. Interaction is a directly calculable effect resulting from the combination of (or interaction between) allocation and selection effects.

selection: List[float | None]

Calculated portfolio’s selection return. Selection refers to the value the portfolio manager adds by holding individual securities or instruments within the sector in different-than-benchmark weights.

class serenity_types.valuation.portfolio_analytic.BrinsonAttributionExposure(*, sectors: List[str], portfolio: List[float | None], benchmark: List[float | None], difference: List[float | None])[source]

Bases: CamelModel

Portfolio and benchmarks exposure (compounded over time), by sector.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

benchmark: List[float | None]

Benchmark’s exposure (compounded over time), by sector.

difference: List[float | None]

Difference between portfolio and benchmark exposure.

portfolio: List[float | None]

Portfolio’s exposure (compounded over time), by sector.

sectors: List[str]

List of sectors.

class serenity_types.valuation.portfolio_analytic.BrinsonAttributionOutput(*, baseResults: BrinsonAttributionResult, simulatedResults: BrinsonAttributionResult | None = None)[source]

Bases: CamelModel

Value object carrying a combination of the base results and the results from running the brinson attribution with the portfolio plus the simulated_trades.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_results: BrinsonAttributionResult

Results without the simulated trades.

simulated_results: BrinsonAttributionResult | None

Results with the simulated trades, if provided.

class serenity_types.valuation.portfolio_analytic.BrinsonAttributionRequest(*, simulatedTrades: Trades | None = None, compoundingFrequency: CompoundingFrequencyInput | None = CompoundingFrequencyInput.DAILY, markTime: MarkTime | None = MarkTime.UTC, returnsType: ReturnsType | None = ReturnsType.SIMPLE, baseCurrencyId: UUID | None = None, portfolio: PortfolioCompositionAndTrades, benchmarks: Dict[str, PortfolioByMetadataIdOrCompositionValue] | None = None, sectorTaxonomyId: UUID | None = None, customAssetsGroups: CustomAssetsGroups | None = None)[source]

Bases: PortfolioAnalyticRequest

Public API request to compute brinson attribution of a given portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

custom_assets_groups: CustomAssetsGroups | None

Specify user’s own custom assets grouping / taxonomy.

sector_taxonomy_id: UUID | None

Specify which sector taxonomy provider’s UUID to be used. Defaults to DACS’s UUID.

classmethod validate_taxonomy_source(values)[source]
class serenity_types.valuation.portfolio_analytic.BrinsonAttributionResult(*, byBenchmark: Dict[str, BrinsonAttribution])[source]

Bases: CamelModel

Value object carrying the result of brinson attribution against each benchmarks.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

by_benchmark: Dict[str, BrinsonAttribution]
class serenity_types.valuation.portfolio_analytic.CoreBrinsonAttributionRequest(*, simulatedTrades: Trades | None = None, compoundingFrequency: CompoundingFrequencyInput | None = CompoundingFrequencyInput.DAILY, markTime: MarkTime | None = MarkTime.UTC, returnsType: ReturnsType | None = ReturnsType.SIMPLE, baseCurrencyId: UUID | None = None, portfolio: CorePortfolioCompositionAndTrades, benchmarks: Dict[str, PortfolioComposition | CustomizedPortfolioComposition] | None = None, sectorTaxonomyId: UUID | None = None, customAssetsGroups: CustomAssetsGroups | None = None)[source]

Bases: CorePortfolioAnalyticRequest

Core API request to compute brinson attribution of a given portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

custom_assets_groups: CustomAssetsGroups | None

Specify user’s own custom assets grouping / taxonomy.

sector_taxonomy_id: UUID | None

Specify which sector taxonomy provider’s UUID to be used. Defaults to DACS’s UUID.

classmethod validate_taxonomy_source(values)[source]
class serenity_types.valuation.portfolio_analytic.CorePortfolioAnalyticRequest(*, simulatedTrades: Trades | None = None, compoundingFrequency: CompoundingFrequencyInput | None = CompoundingFrequencyInput.DAILY, markTime: MarkTime | None = MarkTime.UTC, returnsType: ReturnsType | None = ReturnsType.SIMPLE, baseCurrencyId: UUID | None = None, portfolio: CorePortfolioCompositionAndTrades, benchmarks: Dict[str, PortfolioComposition | CustomizedPortfolioComposition] | None = None)[source]

Bases: BasePortfolioAnalyticRequest

Core API request to compute a set of performance statistics for a given portfolio. If simulated_trades are provided, the system will compute twice: once with the base portfolio, and again with the base portfolio + simulated_trades applied.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

benchmarks: Dict[str, PortfolioComposition | CustomizedPortfolioComposition] | None

For benchmark-relative measures, which benchmark indices, baskets or assets should be used for purposes of comparison?

portfolio: CorePortfolioCompositionAndTrades

The base set of positions and trades to use for computing performance statistics.

class serenity_types.valuation.portfolio_analytic.CustomAssetsGroups(*, assetIds: List[UUID], sectorLevel1: List[str], sectorLevel2: List[str | None], sectorLevel3: List[str | None])[source]

Bases: CamelModel

Model to represents custom assets grouping / taxonomy.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

asset_ids: List[UUID]

Series of unique asset identifiers from Serenity asset master.

sector_level_1: List[str]

The level 1 asset’s sector classification. All assets should have at least the first level defined.

sector_level_2: List[str | None]

The level 2 asset’s sector classification.

sector_level_3: List[str | None]

The level 3 asset’s sector classification.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticAbsolutePerformance(*, sharpeRatio: float | None = None, sortinoRatio: float | None = None, calmarRatio: float | None = None, maxDrawdown: float | None = None)[source]

Bases: CamelModel

Value object carrying various measures of absolute portfolio performance, independent of the chosen benchmark(s).

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

calmar_ratio: float | None

A ratio used to gauge the risk-adjusted performance of an investment by comparing the average annual return to the maximum drawdown experienced over a specific time frame, indicating the ability to generate returns relative to the depth of losses.

max_drawdown: float | None

The largest peak-to-trough decline in the value of an investment or portfolio during a specific period, revealing the extent of loss from the highest point to the lowest point reached.

sharpe_ratio: float | None

A measure that evaluates the risk-adjusted return of an investment by considering the excess return earned per unit of volatility, helping to assess the efficiency of returns relative to the level of risk taken.

sortino_ratio: float | None

A risk-adjusted performance metric that focuses on downside volatility by measuring the excess return per unit of downside risk, providing insight into an investment’s ability to generate positive returns while minimizing downside fluctuations.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticLogReturn(*, cumulativeReturn: float | None = None, annualisedReturn: float | None = None, returnsByPeriod: Dict[datetime, float | None])[source]

Bases: CamelModel

Value object carrying portfolio return measures based on continuously compounded or logarithmic returns.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

annualised_return: float | None

The average rate of growth or change in value of an investment per year, calculated by compounding the logarithmic returns over the entire holding period and then converting the result into an annualized percentage. This method accounts for the compounding effect of returns over time and provides a standardized measure of performance, suitable for comparing investments with varying holding periods.

cumulative_return: float | None

The total growth or change in value of an investment over a specific period, calculated by summing the logarithmic returns for each subperiod within that timeframe. This approach accurately reflects the compounding effect of returns over time and provides a more precise representation of overall investment performance, especially for extended periods.

returns_by_period: Dict[datetime, float | None]

Breakdown of logarithmic returns by reporting period.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticOutput(*, baseResults: PortfolioAnalyticResult, simulatedResults: PortfolioAnalyticResult | None = None)[source]

Bases: CamelModel

Value object carrying a combination of the base results and the results from running the analytics with the portfolio plus the simulated_trades.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

base_results: PortfolioAnalyticResult

Results without the simulated trades.

simulated_results: PortfolioAnalyticResult | None

Results with the simulated trades, if provided.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticPearsonCorrelationGroup(*, byPortfolios: Dict[str, Dict[str, float | None]] | None = None, byAssets: Dict[UUID | str, Dict[UUID | str, float | None]])[source]

Bases: CamelModel

Value object that groups correlation results by portfolio and constituent asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

by_assets: Dict[UUID | str, Dict[UUID | str, float | None]]

Grouping of pairwise asset correlations by asset ID.

by_portfolios: Dict[str, Dict[str, float | None]] | None

Grouping of pairwise portfolio correlations by portfolio ID.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticRelativePerformance(*, annualisedActivePremium: float | None = None, trackingError: float | None = None, informationRatio: float | None = None, relativeBeta: float | None = None, upsideCaptureRatio: float | None = None, downsideCaptureRatio: float | None = None, excessMaxDrawdown: float | None = None)[source]

Bases: CamelModel

Benchmark-relative measures of portfolio performance.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

annualised_active_premium: float | None

The yearly average difference in returns between a portfolio and its benchmark index, reflecting the active management’s impact on performance after accountingfor market movements.

downside_capture_ratio: float | None

The ratio of a portfolio’s negative returns compared to its benchmark’s negative returns, demonstrating the portfolio’s susceptibility to losses during unfavorable market conditions.

excess_max_drawdown: float | None

The difference between a portfolio’s maximum drawdown (peak-to-trough decline) and the corresponding drawdown of its benchmark index, highlighting how much worse the portfolio’s losses were compared to the benchmark during its worst period.

information_ratio: float | None

A ratio that assesses an investment manager’s ability to generate excess returns relative to the level of risk taken, by comparing the portfolio’s active return with its tracking error.

relative_beta: float | None

The measure of an asset’s sensitivity to market movements compared to a chosen benchmark index, indicating how much the asset’s price tends to move relative to the benchmark’s movements.

tracking_error: float | None

The standard deviation of the variance between a portfolio’s returns and those of its benchmark index, measuring the extent to which the portfolio’s performance deviates from the benchmark.

upside_capture_ratio: float | None

The ratio of a portfolio’s positive returns compared to its benchmark’s positive returns, showcasing the portfolio’s ability to capture gains during favorable market conditions.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticRequest(*, simulatedTrades: Trades | None = None, compoundingFrequency: CompoundingFrequencyInput | None = CompoundingFrequencyInput.DAILY, markTime: MarkTime | None = MarkTime.UTC, returnsType: ReturnsType | None = ReturnsType.SIMPLE, baseCurrencyId: UUID | None = None, portfolio: PortfolioCompositionAndTrades, benchmarks: Dict[str, PortfolioByMetadataIdOrCompositionValue] | None = None)[source]

Bases: BasePortfolioAnalyticRequest

Public API request to compute a set of performance statistics for a given portfolio. If simulated_trades are provided, the system will compute twice: once with the base portfolio, and again with the base portfolio + simulated_trades applied.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

benchmarks: Dict[str, PortfolioByMetadataIdOrCompositionValue] | None

For benchmark-relative measures, which benchmark indices, baskets or assets should be used for purposes of comparison?

portfolio: PortfolioCompositionAndTrades

The base set of positions and trades to use for computing performance statistics.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticResult(*, summary: PortfolioAnalyticSummary, returns: Dict[str, PortfolioAnalyticSimpleReturn], volatility: Dict[str, PortfolioAnalyticVolatility], statistics: PortfolioAnalyticStatisticsGroup, pearsonCorrelation: PortfolioAnalyticPearsonCorrelationGroup, absolutePerformance: PortfolioAnalyticAbsolutePerformance, relativePerformance: Dict[str, PortfolioAnalyticRelativePerformance] | None = None)[source]

Bases: CamelModel

Value object combining various portfolio performance statistics by type for a single portfolio.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

absolute_performance: PortfolioAnalyticAbsolutePerformance

Absolute perforamnce measures for the input portfolio.

pearson_correlation: PortfolioAnalyticPearsonCorrelationGroup

Pairwise correlations by portfolio and asset.

relative_performance: Dict[str, PortfolioAnalyticRelativePerformance] | None

For each benchmark provided, a summary of the benchmark-relative performance.

returns: Dict[str, PortfolioAnalyticSimpleReturn]

For each portfolio analyzed provide a summary of the returns using simple returns only for now. Log returns will be supported in a subsequent release.

statistics: PortfolioAnalyticStatisticsGroup

For each portfolio analyzed provide a summary of basic ratios, drawdown, etc..

summary: PortfolioAnalyticSummary

High-level P&L summary for this portfolio.

volatility: Dict[str, PortfolioAnalyticVolatility]

For each portfolio analyzed provide a summary of the volatility measures.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticSimpleReturn(*, cumulativeReturn: float | None = None, annualisedReturn: float | None = None)[source]

Bases: CamelModel

Value object carrying return measures based on simple returns, the percentage change in the value of the portfolio’s constituents from its initial value to its final value.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

annualised_return: float | None

The average rate of growth or change in value of an investment expressed as an annual percentage. It considers the compound effect of returns over multiple periods to provide a standardized measure of performance over time, facilitating comparison between investments with different holding periods.

cumulative_return: float | None

The total amount of growth or change in value of an investment over a specific period, calculated by considering all gains and losses during that timeframe. It represents the net effect of multiple returns, showcasing the overall performance and change in value of the investment from its starting point to the end of the period.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticStatistics(*, mean: float | None = None, stddev: float | None = None, skew: float | None = None, kurtosis: float | None = None)[source]

Bases: CamelModel

Simple distributional measures of the portfolio returns.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

kurtosis: float | None

Kurtosis gauges the thickness of the tails and the concentration of returns around the mean in the probability distribution of portfolio returns. High kurtosis indicates heavy tails and a greater concentration of returns, potentially leading to more frequent extreme values. Low kurtosis implies lighter tails and less concentration around the mean. Kurtosis offers insights into the likelihood of extreme events and the overall shape of the return distribution.

mean: float | None

Average value in the distribution of portfolio returns.

skew: float | None

Skewness measures the asymmetry of the probability distribution of portfolio returns. Positive skew indicates that the distribution has a longer tail on the right, implying more extreme positive returns, while negative skew implies a longer tail on the left, suggesting more extreme negative returns. Skewness helps assess the potential for returns to deviate from the average in one direction.

stddev: float | None

Standard deviation in the distribution of portfolio returns.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticStatisticsGroup(*, byPortfolios: Dict[str, PortfolioAnalyticStatistics], byAssets: Dict[UUID | str, PortfolioAnalyticStatistics])[source]

Bases: CamelModel

Value object that groups the performance statistics by portfolio and constituent asset.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

by_assets: Dict[UUID | str, PortfolioAnalyticStatistics]

Grouping of portfolio statistics by unique asset ID.

by_portfolios: Dict[str, PortfolioAnalyticStatistics]

Grouping of portfolio statistics by portfolio ID.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticSummary(*, asOfTimes: List[datetime], tradingPnl: List[float | None], holdingPnl: List[float | None], commission: List[float | None], netPnl: List[float | None], buyAmount: List[float | None], sellAmount: List[float | None], tradeAmount: List[float | None], transferAmount: List[float | None], totalPnl: List[float | None], longAmount: List[float | None], shortAmount: List[float | None], cashChange: List[float | None], cash: List[float | None], gmv: List[float | None], npv: List[float | None])[source]

Bases: CamelModel

Value object carrying the highest-level summaries of portfolio performance.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

as_of_times: List[datetime]

Series of timestamps corresponding to the start of each reporting period.

buy_amount: List[float | None]

Total asset value bought in the period.

cash: List[float | None]

Total cash position as of period end.

cash_change: List[float | None]

Cash position change in the period.

commission: List[float | None]

Total commission for the period.

gmv: List[float | None]

Series of gross market values of the assets held over time.

holding_pnl: List[float | None]

P&L resulted from holdin position from previous period end.

long_amount: List[float | None]

Total long position values.

net_pnl: List[float | None]

Series of net P&L measures for the portfolio, accounting for both trading P&L and the increase or decrease in the value of the assets held.

npv: List[float | None]

Series of net market values of the assets held over time.

sell_amount: List[float | None]

Total asset value sold in the period.

short_amount: List[float | None]

Total short position values.

total_pnl: List[float | None]

Cumulative net P&L till given period.

trade_amount: List[float | None]

Sum of buy amount and sell amount in the period.

trading_pnl: List[float | None]

P&L due to trades within the period.

transfer_amount: List[float | None]

Total amount transfered in or out of the portfolio in the period.

class serenity_types.valuation.portfolio_analytic.PortfolioAnalyticVolatility(*, annualisedVolatility: float | None = None, upsideVolatility: float | None = None, downsideVolatility: float | None = None)[source]

Bases: CamelModel

Value object for carrying the various portfolio volatility measures.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

annualised_volatility: float | None

Portfolio returns volatility, expressed as a fraction.

downside_volatility: float | None

Portfolio returns volatility limited to the negative variations from average, the right tail of the distribution, expressed as a fraction.

upside_volatility: float | None

Portfolio returns volatility limited to the positive variations from average, the right tail of the distribution, expressed as a fraction.

class serenity_types.valuation.portfolio_analytic.PortfolioFromAllocationRequest(*, initialWeights: List[AssetWeight], initialCashQuantity: float, startDatetime: datetime, endDatetime: datetime | None = None, closeFrequency: PortfolioTimeseriesFrequency | None = PortfolioTimeseriesFrequency.DAILY, markTime: MarkTime | None = MarkTime.UTC, rebalancingFrequency: RebalancingFrequency | None = RebalancingFrequency.DAILY)[source]

Bases: CamelModel

API request to create a portfolio from an initial cash position and a set of weights and a rebalancing rule. The server then generates a series of positions at a given frequency, e.g. daily, rebalancing periodically to bring the positions in line with the desired weights. This in turn generates a set of trades.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

classmethod check_initial_weights_sum(values)[source]
close_frequency: PortfolioTimeseriesFrequency | None

When generating the position time series, the frequency of balance snapshots. Where DAILY, the selected mark_time is used as daily close times.

end_datetime: datetime | None

The ending timestamp for generating the portfolio time series. Defaults to latest datetime.

initial_cash_quantity: float

Amount of cash in the portfolio at inception. In current implementation defaults to USD.

initial_weights: List[AssetWeight]

The model portfolio allocation in terms of weights. At start_datetime the system will buy the assets using the initial_cash_quantity and then periodically accordingly to rebalance_frequency will generate buys and sells to bring the allocation back in line with the initial weights.

mark_time: MarkTime | None

The close time convention to use for close-on-close prices in the 24x7 market. Defaults to UTC midnight.

rebalancing_frequency: RebalancingFrequency | None

Frequency at which the system revaluates positions and weights to bring the allocation back in line with the initial_weights.

start_datetime: datetime

The starting timestamp for generating the portfolio time series.

class serenity_types.valuation.portfolio_analytic.PortfolioFromTradesRequest(*, initialPositions: List[AssetPosition], trades: Trades | None = None, transfers: Transfers | None = None, startDatetime: datetime, endDatetime: datetime | None = None, closeFrequency: PortfolioTimeseriesFrequency | None = PortfolioTimeseriesFrequency.DAILY)[source]

Bases: CamelModel

API request to create a portfolio from an initial set of asset position and a set of trades and transfers. Trades model buys and sells on exchange over the life of the portfolio; transfers model movement of assets in and out of the portfolio over its lifetime, including cash moves for subscriptions and redemptions where applicable.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

close_frequency: PortfolioTimeseriesFrequency | None

When generating the position time series, the frequency of balance snapshots.

end_datetime: datetime | None

The ending timestamp for generating the portfolio time series. Defaults to latest datetime.

initial_positions: List[AssetPosition]

Initial quantities of assets contained in the portfolio before trades and transfers are applied over time, if any. If you just want to represent an unchanging portfolio composition, provide your current positions here with no trades or transfers; this lets you conduct a pro forma analysis.

classmethod merge_duplicated_asset_positions(values)[source]
start_datetime: datetime

The starting timestamp for generating the portfolio time series.

trades: Trades | None

Optional set of buys and sells to execute from start_datetime to end_datetime.

transfers: Transfers | None

Optional set of transfers of assets in and out of the portfolio to execute from start_datetime to end_datetime.