serenity_sdk package

serenity_sdk.api.analytics

class serenity_sdk.api.analytics.PortfolioAnalyticsApi(client: SerenityClient)[source]

Bases: SerenityApi

Helper class for the Portfolio Analytics API, which lets clients create portfolios parametrically and then run performance analysis on those rich portfolios, both basic portfolio statistics (Sharpe, Sortino, max drawdown, etc.) and more sophisticated Brinson single- and multi-period portfolio performance attribution.

Parameters:

client – the raw client to delegate to when making API calls

create_portfolio_from_allocation(request: PortfolioFromAllocationRequest) Response[PortfolioTimeseriesAndTrades][source]

Given a set of weights and a rebalancing frequency, takes an initial cash position, trades into it, and periodically rebalances. The output is the portfolio positions and trades.

create_portfolio_from_trades(request: PortfolioFromTradesRequest) Response[PortfolioTimeseriesAndTrades][source]

Given an initial set of positions and a series of trades and transfers plus the frequency of closing snapshots (e.g. daily close), produces a full portfolio object with the timeseries of positions and trades.

serenity_sdk.api.core

class serenity_sdk.api.core.SerenityApi(client: SerenityClient, api_group: str)[source]

Bases: ABC

Higher-level wrapper around a particular API endpoint like the Risk API or Model API. Subclasses add typed operations and various helper functions specific to that API group.

Parameters:
  • client – the raw client to delegate to when making API calls

  • api_group – the specific API group to target, e.g. risk or refdata

serenity_sdk.api.model

class serenity_sdk.api.model.ModelApi(client: SerenityClient)[source]

Bases: SerenityApi

Helper class for the Model Metadata API, which lets clients introspect model parameters and other information about available risk models. This endpoint is also required for looking up the appropriate Model Configuration ID in the forthcoming Risk API upgrade so you can specify which configuration you want to use for risk attribution, scenarios and other risk tools.

Parameters:

client – the raw client to delegate to when making API calls

get_model_classes(as_of_date: date | None = None) List[Any][source]

Gets the list of available model classes, e.g. Market Risk, Liquidity Risk or VaR. These are the high-level groups of models supported by Serenity.

Parameters:

as_of_date – the effective date for the model metadata in the database, else latest if None

get_model_configurations(as_of_date: date | None = None) List[Any][source]

Gets the list of available model classes, e.g. Market Risk, Liquidity Risk or VaR. These are the high-level groups of models supported by Serenity.

Parameters:

as_of_date – the effective date for the model metadata in the database, else latest if None

get_models(as_of_date: date | None = None) List[Any][source]

Gets the list of available model classes, e.g. Market Risk, Liquidity Risk or VaR. These are the high-level groups of models supported by Serenity.

Parameters:

as_of_date – the effective date for the model metadata in the database, else latest if None

load_model_metadata(as_of_date: date | None = None) ModelMetadata[source]

Helper method that preloads all the model metadata into memory for easy access.

Parameters:

as_of_date – the effective date for the model metadata in the database, else latest if None

serenity_sdk.api.portfolio

class serenity_sdk.api.portfolio.PortfolioApi(client: SerenityClient)[source]

Bases: SerenityApi

Parameters:

client – the raw client to delegate to when making API calls

create_portfolio_metadata(request: PortfolioMetadataCreateRequest) PortfolioMetadata[source]

Creates a new Portfolio Metadata.

Parameters:

request – the request with the necessary details to create a new PortfolioMetadata

Returns:

the created PortfolioMetadata

create_portfolio_snapshot(request: PortfolioSnapshotCreateRequest) PortfolioSnapshot[source]

Creates a Portfolio Snapshot.

Parameters:

request – the request with the necessary details to create a new PortfolioSnapshot

Returns:

the created PortfolioSnapshot

delete_portfolio_metadata(metadata_id: UUID)[source]

Marks the Portfolio Metadata as deleted.

Parameters:

metadata_id – the PortfolioMetadata to delete

delete_portfolio_snapshot(snapshot_id: UUID) bool[source]

Mark the Portfolio Snapshot as deleted.

Parameters:

snapshot_id – the PortfolioSnapshot to delete

get_balances_by_metadata_id(request: PortfolioAccountBalanceRequest) List[Balance][source]

Get Balances by account_ids in Portfolio Metadata

Parameters:

request – the request with the metadata_id

Returns:

a list of Balance

get_portfolio_metadata(metadata_id: UUID) PortfolioMetadata[source]

Get the Portfolio Metadata.

Parameters:

metadata_id – the PortfolioMetadata’s unique identity

Returns:

PortfolioMetadata

get_portfolio_snapshot(snapshot_id: UUID) PortfolioSnapshot[source]

Get the Portfolio Snapshot.

Parameters:

snapshot_id – the PortfolioSnapshot’s unique identity

Returns:

PortfolioSnapshot

list_portfolio_metadata(offset: int | None = 0, limit: int | None = 1000) List[PortfolioMetadata][source]

List all PortfolioMetadata not marked as deleted.

Parameters:
  • offset – the number of records to skip in the page.

  • limit – the maximum number of items that should be returned.

Returns:

a list PortfolioMetadata

list_portfolio_snapshots(metadata_id: UUID, offset: int | None = 0, limit: int | None = 1000) List[PortfolioSnapshot][source]

List all PortfolioSnapshot entries that are associated with the given metadata_id

Parameters:
  • metadata_id – the PortfolioMetadata id to retrieve the snapshots from.

  • offset – the number of records to skip in the page.

  • limit – the maximum number of items that should be returned.

Returns:

a list PortfolioSnapshot

to_legacy_portfolio(portfolio_snapshot: PortfolioSnapshot) Portfolio[source]

Convert the PortfolioSnapshot to a Portfolio type that’s compatible with the current SDK Api.

Parameters:

portfolio_snapshot – The PortfolioSnapshot to convert

Returns:

Portfolio

update_portfolio_metadata(metadata_id: UUID, request: PortfolioMetadataUpdateRequest) PortfolioMetadata[source]

Creates a copy of the Portfolio Metadata and increases the version by 1.

Parameters:

request – the request with all the details needed to update the PortfolioMetadata

Returns:

the updated PortfolioMetadata

update_portfolio_snapshot(snapshot_id: UUID, request: PortfolioSnapshotUpdateRequest) PortfolioSnapshot[source]

Creates a copy of the Portfolio Snapshot and increases the version by 1.

Parameters:

request – the request with the necessary details to update an PortfolioSnapshot

Returns:

the updated PortfolioSnapshot

serenity_sdk.api.pricing

class serenity_sdk.api.pricing.PricerApi(client: SerenityClient)[source]

Bases: SerenityApi

Parameters:

client – the raw client to delegate to when making API calls

compute_option_valuations(request: OptionValuationRequest) List[OptionValuationResult][source]

Given a list of options, market data and market data override parameters, value all the options.

Parameters:

request – the set of options to value using the given market data and overrides

Returns:

ordered list of option valuations with PV, greeks, market data, etc.

compute_strategy_valuation(request: StrategyValuationRequest) StrategyValuationResult[source]

Calculate the value of a strategy (e.g. a spread) given a set of options and market data.

get_available_volatility_surface_versions(vol_surface_id: UUID | None = None, start_datetime: datetime | None = None, end_datetime: datetime | None = None) List[VolatilitySurfaceAvailability][source]

Gets a list of generic volsurface descriptions and their available versions.

Parameters:
  • vol_surface_id – optional specific vol_surface_id to be retrieved; defaults to all available in the chosen date/time range

  • end_datetime – optional end of date/time range (inclusive) to query for available surface parameterizations and their versions; defaults to UNIX epoch

  • end_datetime – optional end of date/time range (inclusive) to query for available surface parameterizations and their versions; defaults to now

get_available_yield_curve_versions(yield_curve_id: UUID | None = None, start_datetime: datetime | None = None, end_datetime: datetime | None = None) List[YieldCurveAvailability][source]

Gets a list of generic yield curve descriptions and their available versions.

Parameters:
  • yield_curve_id – optional specific yield_curve_id to be retrieved; defaults to all available in the chosen date/time range

  • start_datetime – optional start of date/time range (inclusive) to query for available curve parameterizations and their versions; defaults to UNIX epoch

  • end_datetime – optional end of date/time range (inclusive)to query for available curve parameterizations and their versions; defaults to now

get_supported_currencies(as_of_date: date | None = None) List[Currency][source]

Gets a list of currencies that can be used for quote asset and base currency; currently USD only.

Parameters:

as_of_date – optional date to use when loading reference data; defaults to latest, from cache

get_supported_futures(as_of_date: date | None = None, underlier_asset_id: UUID | None = None) List[Future][source]

Gets a list of active futures that may be referenced in projection curve points; currently Deribit BTC and ETH futures only.

Parameters:
  • as_of_date – optional date to use when loading reference data; defaults to latest, from cache

  • underlier_asset_id – optional filter to limit to futures on the given underlier, defaults to all

get_supported_options(as_of_date: date | None = None, underlier_asset_id: UUID | None = None) List[ListedOption][source]

Gets a list of active listed options that can be priced using the API; currently only Deribit BTC and ETH options.

Parameters:
  • as_of_date – optional date to use when loading reference data; defaults to latest, from cache

  • underlier_asset_id – optional filter to limit to options on the given underlier, defaults to all

get_supported_underliers(as_of_date: date | None = None) List[TokenAsset][source]

Gets all the underlying tokens supported by the system for derivatives pricing (currently only BTC and ETH).

Parameters:

as_of_date – optional date to use when loading reference data; defaults to latest, from cache

get_volatility_surface_version(vol_surface_id: UUID, as_of_time: datetime | None = datetime.datetime(2024, 1, 7, 1, 32, 59, 487067)) VolatilitySurfaceVersion[source]

Gets the volsurface given a unique identifier for the parameter set and an as-of time to pick up the most recent version as of that date/time. These JSON objects can be very large, so in general the protocol should be to list what’s available.

Parameters:

vol_surface_id – the specific combination of parameters (VolModel, etc.) that you want to retrieve

Returns:

the raw and interpolated VS as of the given time for the given set of parameters

get_yield_curve_version(yield_curve_id: UUID, as_of_time: datetime | None = datetime.datetime(2024, 1, 7, 1, 32, 59, 487099)) YieldCurveVersion[source]

Gets the yield curve given a unique identifier. These JSON objects can be very large so in general the protocol should be to list what’s available for a time range and then retrieve each one.

Parameters:
  • yield_curve_id – the specific combination of parameters that you want to retrieve

  • as_of_time – the effective date/time for the version; defaults to latest

Returns:

the raw and interpolated YC as of the given time for the given set of parameters

serenity_sdk.api.provider

class serenity_sdk.api.provider.SerenityApiProvider(client: SerenityClient)[source]

Bases: object

Simple entrypoint that gives you access to the full set of Serenity API’s from a single class.

Parameters:

client – the raw client to wrap around for every typed endpoint

account() AccountApi[source]

Gets a typed wrapper for all the Account API functions.

model() ModelApi[source]

Gets a typed wrapper for all the ModelOps (model metadata) API functions.

portfolio() PortfolioApi[source]

Gets a typed wrapper for all the Portfolio Storage API functions.

portfolio_analytics() PortfolioAnalyticsApi[source]

Gets a typed wrapper for all the Portfolio Analytics functions.

pricer() PricerApi[source]

Gets a typed wrapper for all the pricing API’s for derivatives.

refdata() RefdataApi[source]

Gets a typed wrapper around all the supported reference data API calls.

risk() RiskApi[source]

Gets a typed wrapper aorund all the supported risk-related API calls. Currently this mixes factor risk attribution and VaR-related calls, but we may break this out later.

risk_analytics() RiskAnalyticsAPI[source]

Gets a typed wrapper for all the Risk Analytics functions.

scenarios() ScenariosApi[source]

Gets a typed wrapper for executing scenarios and managing custom scenarios.

storage() StorageApi[source]

Gets a typed wrapper for all the Storage functions.

valuation() ValuationApi[source]

Gets a typed wrapper for all the portfolio valuation API functions.

serenity_sdk.api.refdata

class serenity_sdk.api.refdata.RefdataApi(client: SerenityClient)[source]

Bases: SerenityApi

The refdata API group covers access to the Serenity Asset Master and other supporting reference data needed for constructing portfolios and running risk models.

Parameters:

client – the raw client to delegate to when making API calls

describe_assets(asset_ids: List[UUID]) List[Asset][source]

get the description of the assets for any :class:serenity_types.refdata.asset.AssetType matching the search criteria.

Parameters:

asset_ids – asset ids (uuid in string format)

Returns:

dictionary of asset id to asset description

get_asset_summaries(as_of_date: date | None = None) List[Any][source]

Gets the list of asset records in the asset master. In general you should prefer to use load_asset_master() instead, which will help parsing the JSON records, rather than this lower-level call.

Parameters:

as_of_date – the effective date for all loaded refdata, else latest if None

Returns:

a list of JSON-formatted asset summary objects

get_asset_types(as_of_date: date | None = None) Dict[source]

Gets the list of supported asset types in the system, e.g. TOKEN

Returns:

a map from name to description

get_currency(iso_currency_code: str) Currency[source]

A convenience method that wraps the search_assets() call underneath to return the serenity_types.refdata.currency.Currency based on the the iso_currency_code.

Parameters:

iso_currency_code – the ISO currency code to get. The param is case_sensitive. E.g USD https://www.iban.com/currency-codes

Returns:

the serenity_types.refdata.currency.Currency that matches the ISO code

get_exchanges(as_of_date: date | None = None) Dict[str, UUID][source]

Gets the list of supported exchanges in the system, e.g. BINANCE

Returns:

a list of exchange objects

get_sector_taxonomies(as_of_date: date | None = None) Dict[str, UUID][source]

Gets a mapping from a short key like DACS or DATS to the sectory taxonomy ID (UUID). This will be required in the next release if you wish to override the sector taxonomy in use for risk attribution.

Returns:

a map from taxonomy short name to taxonomy UUID

get_symbol_authorities(as_of_date: date | None = None) Dict[source]

Gets the list of supported symbol authorities, e.g. KAIKO, DAR or COINGECKO

Returns:

a map from name to description

get_tokens(native_symbols: List[str]) Dict[str, TokenAsset][source]

A convenience method that wraps the search_assets() call underneath to return the serenity_types.refdata.token.TokenAsset based on the the native_symbols.

Parameters:

native_symbols – the list for the tokens to search. Please note that the symbols are case sensitive

Returns:

a dict with the native_symbol as key and value serenity_types.refdata.token.TokenAsset

load_asset_master(as_of_date: date | None = None) AssetMaster[source]

Bulk load operation that loads the whole asset master into memory so it can be used to help build portfolios bassed on inputs in different symbologies, and so it can be queried without hitting the server multiple times. Reference data is always as of a date, as it can change over time, but if a date is not provided the system will default to the latest date.

Parameters:

as_of_date – the effective date for all loaded refdata, else latest if None

Returns:

an AssetMaster object containing all asset-linked reference data

search_assets(request: AssetSearchRequest) List[Asset][source]

Searches the asset master and returns the typed description of the assets for any :class:serenity_types.refdata.asset.AssetType matching the search criteria.

Parameters:

request – search parameters used to query the backend

Returns:

a list of type-specific descriptions matching the query

serenity_sdk.api.risk_analytics

class serenity_sdk.api.risk_analytics.RiskAnalyticsAPI(client: SerenityClient)[source]

Bases: SerenityApi

Helper class for the Risk Analytics API.

Parameters:

client – the raw client to delegate to when making API calls

compute_greek_measures(as_of_time: datetime | None = None, pf_as_of_time: datetime | None = None, pf_metadata_id: UUID | None = None, pf_balances: List[Balance] | None = None, simulation_id: UUID | None = None) GreekMeasureResponse[source]

Calculate the greek measures of the given portfolio balances.

compute_portfolio_performance_attribution(request: BrinsonAttributionRequest) Response[BrinsonAttributionOutput][source]

Given a rich portfolio object with periodic positions, trades and transfers, computes the Brinson performance attribution, assessing to what degree the performance is due to active management.

compute_portfolio_statistics(request: PortfolioAnalyticRequest) Response[PortfolioAnalyticOutput][source]

Given a rich portfolio object with periodic positions, trades and transfers, computes standard portfolio analytics like Sharpe, Sortino, max drawdown, etc.. Optionally you can also include a set of “simulated trades” so you can see how portfolio performance would differ if you execute those trades, essentially perform a what-if analysis on past trading decisions or alternative portfolios.

serenity_sdk.api.risk

class serenity_sdk.api.risk.RiskApi(client: SerenityClient)[source]

Bases: SerenityApi

The risk API group covers risk attribution, VaR and (in a future release) scenario analysis.

Parameters:

client – the raw client to delegate to when making API calls

compute_risk_attrib(ctx: CalculationContext, portfolio: Portfolio, sector_taxonomy_id: UUID | None = None) RiskAttributionResult[source]

Given a portfolio, breaks down the volatility and variance of the portfolio in various slices, e.g. by asset, by sector & asset, by sector & factor, and by factor. These different pivots of the risk can help you identify areas of risk concentration. All risk calculations are always as of a given date, which among other things determines precomputed model values that will be applied, e.g. for a factor risk model, as-of date determines the factor loadings.

Note that sector_taxonomy support will be dropped with the next release, once the refdata endpoint for looking up sector_taxonomy_id is available.

Parameters:
  • ctx – the common risk calculation parameters to use, e.g. as-of date or factor risk model ID

  • portfolio – the portfolio on which to perform risk attribution

  • sector_taxonomy_id – the unique ID of the sector taxonomy for pivoting, else DACS if None

Returns:

a typed wrapper around the risk attribution results

compute_risk_measures(ctx: RiskMeasureContext, portfolio: Portfolio) PortfolioRiskResponse[source]

Computes risk measures for a portfolio. :param ctx: request and as_of_time :param portfolio: the portfolio to calculate risk measures for

get_asset_covariance_matrix(ctx: CalculationContext, asset_master: AssetMaster, portfolio: Portfolio | None = None) DataFrame[source]

Gets the asset covariance matrix with asset ID’s translated to native symbols, as a DataFrame.

Parameters:

ctx – the common risk calculation parameters to use, specifically the as-of date and model ID in this case

Returns:

a DataFrame pivoted by assetId1 and assetId2 with the asset covariance value as a column

get_asset_factor_exposures(ctx: CalculationContext, asset_master: AssetMaster, portfolio: Portfolio | None = None) DataFrame[source]

Gets the factor exposures by assets as a DataFrame.

Parameters:
  • ctx – the common risk calculation parameters to use, specifically the as-of date and model ID in this case

  • asset_master – an AssetMaster to use to resolve UUID to native symbols

  • portfolio – optional Portfolio used to subset the matrix to just assets in the portfolio

Returns:

a DataFrame pivoted by assetId and factor with the exposure value as a column

get_asset_residual_covariance_matrix(ctx: CalculationContext, asset_master: AssetMaster, portfolio: Portfolio | None = None) DataFrame[source]

Gets the asset residual covariance matrix with asset ID’s translated to native symbols, as a DataFrame.

Parameters:

ctx – the common risk calculation parameters to use, specifically the as-of date and model ID in this case

Returns:

a DataFrame pivoted by assetId1 and assetId2 with the asset residual value as a column

get_factor_correlation_matrix(ctx: CalculationContext) DataFrame[source]

Gets the factor correlation matrix.

Parameters:

ctx – the common risk calculation parameters to use, specifically the as-of date and model ID in this case

Returns:

a DataFrame pivoted by factor1 and factor2 with the factor correlation coefficient value as a column

get_factor_covariance_matrix(ctx: CalculationContext) DataFrame[source]

Gets the factor covariance matrix.

Parameters:

ctx – the common risk calculation parameters to use, specifically the as-of date and model ID in this case

Returns:

a DataFrame pivoted by factor1 and factor2 with the factor covariance value as a column

get_factor_portfolios(ctx: CalculationContext) Dict[str, Portfolio][source]

Gets the factor index compositions for each factor.

Parameters:

ctx – the common risk calculation parameters to use, specifically the as-of date and model ID in this case

Returns:

a mapping from factor name to the factor portfolio

get_factor_returns(ctx: CalculationContext) Styler[source]

Gets the factor returns as a DataFrame.

Parameters:

ctx – the common risk calculation parameters to use, specifically the as-of date and model ID in this case

Returns:

a DataFrame indexed by closeDate and factor with the return value as a column

serenity_sdk.api.scenarios

class serenity_sdk.api.scenarios.ScenariosApi(client: SerenityClient)[source]

Bases: SerenityApi

The scenarios API group covers stress testing facilities.

Parameters:

client – the raw client to delegate to when making API calls

clone_scenario(request: ScenarioCloneRequest) Response[ScenarioDefinition][source]

Given the UUID for a custom or predefined scenario, makes a copy and creates a new custom scenario, allocating a UUID for it.

Parameters:

request – details of the scenario to clone, including new cloned scenario name.

Returns:

cloned definition, including newly-allocated UUID and with the ownerId updated to the user who did the clone operation

create_custom_scenario(request: ScenarioDefinition) Response[ScenarioDefinition][source]

Creates a new custom scenario and allocates a UUID for it.

Parameters:

request – the initial definition to create, with no UUID or version number

Returns:

updated definition with new version number, updated lastUpdated and lastUpdatedBy fields

delete_custom_scenario(scenario_id: UUID) Response[ScenarioDefinition][source]

Performs a soft delete of the given custom scenario UUID in the database.

Parameters:

scenario_id – unique ID of the scenario to delete

Returns:

the soft-deleted scenario definition

generate_custom_scenario(request: CustomScenarioGeneratorRequest) Response[ScenarioDefinition][source]

Generates a custom scenario with auto-generated shocks using the specified date ranges and model config. The time span from the start date to the end date must not exceed 30 days.

Parameters:

request – the request to generate shocks using the specified date ranges and model config

Returns:

a scenario definition with auto generated shocks

get_custom_scenarios(include_deleted: bool | None = False) Response[List[serenity_types.risk.scenarios.ScenarioDefinition]][source]

Lists all known custom scenarios, including the UUID’s required for other operations. At this time it should be scoped to current organization, i.e. all entitled users for a given client site should be able to see all custom scenarios.

Parameters:

include_deleted – whether to include soft-deleted custom scenarios for this installation

Returns:

all known custom scenarios, or empty if none defined.

get_predefined_scenarios() Response[List[serenity_types.risk.scenarios.ScenarioDefinition]][source]

Lists all versions of the given custom scenario; note unlike getCustomSecenarios, the list of ScenarioDefinitions returned will all have the same UUID, just different version numbers. If the scenario was soft-deleted, the last version will have the deleted flag set.

Returns:

all known predefined scenarios

get_scenario(scenario_id: UUID) Response[ScenarioDefinition][source]

Helper method that gets a single scenario given a UUID. Normally the front-end will not use this: the expectation is that the relatively small universe of scenarios known to a particular organization will all be loaded via the getXxx operations.

Returns:

the latest scenario version for the given scenario ID

get_scenario_result(run_id: UUID) Response[ScenarioResult][source]

Given the UUID for a scenario run, gets its state and (if completed successfully) results.

Parameters:

run_id – unique ID for the run result to retrieve

get_scenario_run(run_id: UUID) Response[ScenarioRun][source]

Gets a single run by its unique ID.

Parameters:

run_id – unique ID of the run

Returns:

the requested run

get_scenario_runs(owner_id: str) Response[List[serenity_types.risk.scenarios.ScenarioRun]][source]

Gets all scenario runs initiated by the current user.

Parameters:

owner_id – username of the person who created this scenario run; if empty, return current user’s runs only (the normal case for Serenity UX)

Returns:

all the user’s runs, or empty if no runs

run_scenario(request: ScenarioRequest) Response[ScenarioResult][source]

Given the UUID for a custom or predefined scenario, a portfolio and a set of runtime parameters, executes the scenario asynchronously. All known runs for the user can be listed and for now getScenarioRun can be polled to get the state and results. User ID should be specified in header.

Note the client may either run a scenario by reference (UUID) or by value (ScenarioDefinition). The latter is used to allow the client to run arbitrary, transient scenarios.

update_custom_scenario(scenario: ScenarioDefinition) Response[ScenarioDefinition][source]

Stores a new version of the given custom scenario in the database.

Parameters:

scenario – the initial definition to create, with version number equal to the latest version number known to the client; the UUID is implied in path and can be left out

Returns:

updated definition with new version number, updated lastUpdated and lastUpdatedBy fields

serenity_sdk.api.storage

class serenity_sdk.api.storage.StorageApi(client: SerenityClient)[source]

Bases: SerenityApi

Helper class for the Storage API, which lets clients generate URL and token to access Serenity generated files.

Parameters:

client – the raw client to delegate to when making API calls

get_ctm_download_url_and_token(dataset_content: DatasetContent) DatasetContentUrlAndToken[source]

Generates the URL and SAS token to access the specified dataset content.

serenity_sdk.api.valuation

class serenity_sdk.api.valuation.ValuationApi(client: SerenityClient)[source]

Bases: SerenityApi

The valuation API group covers basic tools for NAV and other portfolio valuation calcs.

Parameters:

client – the raw client to delegate to when making API calls

compute_portfolio_net_delta_value(ctx: PricingContext, portfolio: Portfolio) NetDeltaPortfolioPositions[source]

Given a pricing context (mark time, date, base currency) convert the net delta equivalent of the given portfolio.

Parameters:
  • ctx – the pricing parameters to use, e.g. which base currency and the as-of date for prices

  • portfolio – the portfolio to value

Returns:

a parsed NetDeltaPortfolioPositions the converted net delta of the asset positions

compute_portfolio_value(ctx: PricingContext, portfolio: Portfolio) ValuationResult[source]

Computes portfolio NAV and other high-level valuation details at both the portfolio level and position-by-position.

Parameters:
  • ctx – the pricing parameters to use, e.g. which base currency and the as-of date for prices

  • portfolio – the portfolio to value

Returns:

a parsed ValuationResult containing all portfolio & position values

serenity_sdk.client.auth

class serenity_sdk.client.auth.AuthHeaders(credential: BaseAuthCredential)[source]

Bases: object

Helper object that carries all the headers required for API authentication and authorization.

Creates an initial access token using the given credentials and scopes.

Parameters:

credential – the credential object that returns the access token

ensure_not_expired()[source]

Check whether we need to refresh the bearer token now.

get_http_headers() Dict[str, str][source]

Gets the current set of headers including latest Bearer token for authentication.

Returns:

a mapping between HTTP header and header value

serenity_sdk.client.auth.create_auth_headers(credential: BaseAuthCredential) AuthHeaders[source]

Helper function for the standard requests module to construct the appropriate HTTP headers for a given set of API endpoints and a user application’s client ID. The latter is used by Serenity to distinguish between different client applications on the backend.

serenity_sdk.client.auth.get_credential_user_app(config: ConnectionConfig) BaseAuthCredential[source]

Standard mechanism to acquire a credential for accessing the Serenity API. You can create one or more user applications using the Serenity Admin screen, and as part of setup you will be given the application’s client ID and secret.

Parameters:

config – Serenity API Management API configuration from load_local_config()

Returns:

the Auth0 credential object including token and expiry

serenity_sdk.client.auth0_client_cred_auth

class serenity_sdk.client.auth0_client_cred_auth.Auth0ClientCredAuth(config: ConnectionConfig)[source]

Bases: BaseAuthCredential

Class to authenticate with the Serenity API using the Auth0 Client Credentials Flow. This class is for internal use and normally you should not need to instantiate it.

Parameters:

config – The loaded connection configuration params to use for the authentication process

get_token() AuthToken[source]

Gets an access token from the Auth0 API following the client credentials flow.

serenity_sdk.client.auth0_device_auth

class serenity_sdk.client.auth0_device_auth.Auth0DeviceAuth(config: ConnectionConfig)[source]

Bases: BaseAuthCredential

Class to authenticate with the Serenity API using the Auth0 Device Code Flow. This class is for internal use and normally you should not need to instantiate it.

Parameters:

config – The loaded connection configuration params to use for the authentication process

get_token() AuthToken[source]

Gets an access token from the Auth0 API. This method will block until either the user has completed the authentication process or a timeout has occurred.

serenity_sdk.client.base_auth

class serenity_sdk.client.base_auth.AuthToken[source]

Bases: object

Internal Class to hold the credential’s access token and expiry time

class serenity_sdk.client.base_auth.BaseAuthCredential[source]

Bases: ABC

abstract get_token() AuthToken[source]

serenity_sdk.client.config

class serenity_sdk.client.config.ConnectionConfig(domain: str, user_audience: str, url: str, env: Environment, user_client_id: str | None = None, client_id: str | None = None, client_secret: str | None = None)[source]

Bases: object

The configuration object used to connect to Serenity. This object is used by the SerenityClient to make API calls.

See also

load_local_config(): utility function to load configs from local files

Builds a connection configuration from the given parameters.

Parameters:
  • domain – the domain of the connection

  • user_audience – the audience for user authentication

  • user_client_id – the client ID for user authentication (required only for device code login)

  • client_id – the client ID for client authentication (required only for client credentials login)

  • client_secret – the client secret for client authentication (required only for client credentials login)

  • url – the base URL of the Serenity API

  • env – the environment to use for connection purposes (e.g. Environment.PROD)

get_url() str[source]

Gets the client-specific URL to use for all API requests

class serenity_sdk.client.config.Environment(value)[source]

Bases: Enum

The operational environment (e.g. test vs. production) to use for connection purposes.

DEV = 'DEV'

Serenity’s development environment

PROD = 'PROD'

Serenity’s production environment

TEST = 'TEST'

Serenity’s UAT (QA) environment

class serenity_sdk.client.config.FileConnectionConfig(config: Any, config_path: str)[source]

Bases: ConnectionConfig

Internal class that handles interpreting the JSON config file generated by the Serenity UX API Management function. This class is for internal use and normally you should not need to instantiate it.

See also

load_local_config(): utility function to load configs from local files

Builds a connection configuration from a parsed JSON object.

Parameters:
  • config – a parsed JSON object containing a Serenity API configuration

  • config_path – for error messages – the path from which the JSON was loaded

class serenity_sdk.client.config.Region(value)[source]

Bases: Enum

The regional installation of Serenity to use for connection purposes. Not currently used.

EASTUS = 'eastus'
EASTUS_2 = 'eastus2'
GLOBAL = ''
serenity_sdk.client.config.load_local_config(config_id: str, config_dir: str | None = None) FileConnectionConfig[source]

Helper function that lets you read a JSON config file with client ID and client secret from $HOME/.serenity/${config_id}.json on your local machine.

Parameters:
  • config_id – short name of a configuration to load from $HOME/.serenity

  • config_dir – optional override to load from a directory other than $HOME/,serenity

Returns:

a populated, validated ConnectionConfig object to use with SerenityClient

serenity_sdk.client.raw

class serenity_sdk.client.raw.APIPathMapper(env: Environment = Environment.PROD)[source]

Bases: object

Helper class for adapting from the original API path scheme to the new uniform scheme going live on 1 October 2022 to ease transitions.

Internal helper class that takes care of re-mapping API paths; once we are in full production we will switch to using API versions to support these transitions.

Parameters:

env – target Serenity environment, if not production

get_api_path(input_path: str) str[source]

Given the new API path, return the corresponding path currently supported in production. If there is no configuration for this path, this call raises UnsupportedOperationException.

Parameters:

input_path – the API path requested by the caller

Returns:

the correct API path for the target environment

class serenity_sdk.client.raw.CallType(value)[source]

Bases: Enum

Types of REST calls supported. All values correspond to HTTP methods from RFC 9110.

DELETE = 'DELETE'

Used for soft-delete operations in the API, e.g. delete a custom scenario

GET = 'GET'

Used for basic retrieval operations in the API

PATCH = 'PATCH'

Used for updating objects in the Serenity platform, e.g. updating a custom scenario

POST = 'POST'

Used for compute-type operations like risk attribution and backtesting VaR.

PUT = 'PUT'

Used to add content to the Serenity platform, e.g. adding a new custom scenario

class serenity_sdk.client.raw.SerenityClient(config: ConnectionConfig)[source]

Bases: object

Low-level client object which can be used for direct calls to any REST endpoint.

Parameters:

config – the Serenity platform connection configuration

See also

SerenityApiProvider for an easier-to-use API wrapper

call_api(api_group: str, api_path: str, params: Dict[str, Any] = {}, body_json: Any | None = None, call_type: CallType = CallType.GET, api_version: str | None = None) Any[source]

Low-level function that lets you call any Serenity REST API endpoint. For the call arguments you can pass a dictionary of request parameters or a JSON object, or both. In future versions of the SDK we will offer higher-level calls to ease usage.

Parameters:
  • api_group – API take like risk or refdata

  • api_path – the requested API sub-path to call (non including group or version prefix)

  • params – any GET-style parameters to include in the call

  • body_json – a JSON object to POST or PATCH on the server

  • api_version – overwrite the API version to be called

Returns:

the raw JSON response object

exception serenity_sdk.client.raw.SerenityError(detail: Any, request_json: Any | None = None)[source]

Bases: Exception

Generic error when the API fails, e.g. due to body parsing error on POST

exception serenity_sdk.client.raw.UnsupportedOperationError(api_path: str, env: Environment)[source]

Bases: Exception

Error raised if there is a request for an API operation that is not (yet) supported.

serenity_sdk.renderers.table

class serenity_sdk.renderers.table.FactorRiskTables(result: RiskAttributionResult)[source]

Bases: object

Helper class that formats RiskAttributionResult objects as Pandas DataFrame objects to ease tabular display in Jupyter notebooks.

to_asset_risk_data_frame(asset_master: AssetMaster) DataFrame[source]

Creates a DataFrame with a flattened version of all the by-asset risk data:

  • assetId

  • assetNativeSymbol

  • assetSerenitySymbol

  • absoluteFactorRisk

  • absoluteSpecificRisk

  • absoluteTotalRisk

  • relativeFactorRisk

  • relativeSpecificRisk

  • relativeTotalRisk

  • marginalFactorRisk

  • marginalSpecificRisk

  • marginalTotalRisk

to_factor_risk_data_frame() DataFrame[source]

Creates a DataFrame with a flattened version of the all the by-factor risk data at the portfolio level:

  • factor

  • absoluteRiskContribution

  • relativeRiskContribution

  • marginalRiskContribution

  • factorExposureBaseCcy

to_sector_factor_risk_data_frame() DataFrame[source]

Creates a DataFrame with a flattened version of the all the by-sector, by-factor risk data; depending on whether it is based on old-style parentSector / Sector vs. full sector levels, you will get back a multi-level index with two or three index columns, with various intermediate level in the sector hierarchy populated. This is really better visualized as a treetable, and the Serenity front-end provides that view.

  • sectorLevel1

  • sectorLevel2

  • sectorLevel3

  • factor

  • absoluteRisk

  • relativeRisk

  • marginalRisk

  • factorExposure

  • factorExposureBaseCcy

to_sector_risk_data_frame() DataFrame[source]

Creates a DataFrame with a flattened version of the all the by-sector risk data; depending on whether it is based on old-style parentSector / Sector vs. full sector levels, you will get back a multi-level index with two or three index columns, with various intermediate level in the sector hierarchy populated. This is really better visualized as a treetable, and the Serenity front-end provides that view.

  • sectorLevel1

  • sectorLevel2

  • sectorLevel3

  • absoluteFactorRisk

  • absoluteSpecificRisk

  • absoluteTotalRisk

  • relativeFactorRisk

  • relativeSpecificRisk

  • relativeTotalRisk

to_total_risk_data_frame() DataFrame[source]

Summarizes the portfolio’s factor, specific and total risk in both volatility and variance.

Returns:

a DataFrame with factorRisk, specificRisk and totalRisk columns corresponding to the portion of the risk explained by the model, the portfion of the risk that is idiosyncratic to the assets in that portfolio, and the overall risk. Index corresponds to both volatility and variance.

serenity_sdk.types.common

class serenity_sdk.types.common.CalculationContext(as_of_date: date | None = None, model_config_id: UUID | None = None, mark_time: MarkTime = MarkTime.NY_EOD, base_currency_id: UUID | None = None)[source]

Bases: object

Parameter object that groups together the common inputs for risk calculations. Everything gets defaulted, so you need only populate any overrides.

as_of_date: date | None = None

The effective date for all data loaded from Serenity’s bitemporal database

base_currency_id: UUID | None = None

The currency to use to expresss the value of portfolios, positions and exposures; in current version only USD is supported but later on can be any asset

mark_time: MarkTime = 'NY_EOD'

The mark time to use by convention for “close” in the 24x7 digital asset markets

model_config_id: UUID | None = None

The factor risk or VaR model to use for calculations or when loading pre-computed matrices and other results

class serenity_sdk.types.common.CashTreatment(value)[source]

Bases: Enum

How should the portfolio valuator treat stablecoins? Like cash, or tokens? If CashTreatment is FIAT_PEGGED_STABLECOINS, it will group together USD and USD-pegged stablecoins as “cash.”

FIAT_ONLY = 'FIAT_ONLY'

Only treat fiat currencies as cash

FIAT_PEGGED_STABLECOINS = 'FIAT_PEGGED_STABLECOINS'

Treat fiat-pegged stablecoins like cash

class serenity_sdk.types.common.MarkTime(value)[source]

Bases: Enum

Snapshot time to use for daily close price purposes; as crypto is a 24x7 market users can choose their preferred closing time for marking books. Note that UTC will not be supported until the next release.

HK_EOD = 'HK_EOD'

Prices as of 4:00PM Hong Kong-local time

LN_EOD = 'LN_EOD'

Prices as of 4:30PM London-local time

NY_EOD = 'NY_EOD'

Prices as of 4:30PM New York-local time

UTC = 'UTC'

Prices as of UTC midnight

class serenity_sdk.types.common.Portfolio(assets: Dict[UUID, float])[source]

Bases: object

Simple value object that can be used as an input for risk attribution, VaR calculations and other client functions that require a portfolio as input. In general a user provides the desired portfolio composition in their chosen symbology and then the AssetMoster object can be used to do cross-referencing between multiple symbologies and Serenity’s internal asset ID: UUID values. This lets users work with easy-to-understand portfolio definitions while making it a one-liner to translate for Serenity.

Parameters:

assets – a mapping from asset ID to qty, where negative qty is taken as a short position

get_assets() Dict[UUID, float][source]

Gets the underlying map of asset ID to qty.

to_asset_positions() List[Dict[str, Any]][source]

Internal helper that converts a Portfolio to the preferred format for risk attribution, VaR compution, VaR backtest, etc.

class serenity_sdk.types.common.PricingContext(as_of_date: date | None = None, mark_time: MarkTime = MarkTime.NY_EOD, cash_treatment: CashTreatment = CashTreatment.FIAT_ONLY, base_currency_id: UUID | None = None)[source]

Bases: object

Parameter object that groups together the common inputs for valuation. Everything gets defaulted, so you need only populate any overrides.

as_of_date: date | None = None

The effective date for all data loaded from Serenity’s bitemporal database

base_currency_id: UUID | None = None

The currency to use to expresss the value of portfolios, positions and exposures; in current version only USD is supported but later on can be any asset

cash_treatment: CashTreatment = 'FIAT_ONLY'

How the valuation logic should define “cash position”

mark_time: MarkTime = 'NY_EOD'

The mark time to use by convention for “close” in the 24x7 digital asset markets

class serenity_sdk.types.common.SectorPath(sector_levels: List[str])[source]

Bases: object

create_lookup_key(leaf_name: str)[source]

Helper function that joins the path segments with a terminal node like an asset ID or a factor name. This gives you a unique key for building tables that are indexed by these tuples.

sector_levels: List[str]

serenity_sdk.types.factors

class serenity_sdk.types.factors.FactorExposureValue(factor_exposure: float, factor_exposure_base_ccy: float)[source]

Bases: object

Information about the exposure of the portfolio, sector or asset to a particular factor

factor_exposure: float

The betas of the model’s regression of asset returns vs. each factor; also called factor loadings

factor_exposure_base_ccy: float

The notional value of factor exposure for the portfolio, sector or asset, as a weighted sum of normalized betas

class serenity_sdk.types.factors.Risk(factor_risk: float, specific_risk: float, total_risk: float)[source]

Bases: object

A set of risk metrics, breaking out factor vs. idiosyncratic risk.

factor_risk: float

The portion of the portfolio risk explained by the factor risk model

specific_risk: float

The portion of the risk not explained by the model; sometimes called idiosyncratic risk

total_risk: float

The total risk in the portfolio, sector or asset, inclusive of both explained factor risk and asset-specific risk

class serenity_sdk.types.factors.RiskAttributionResult(raw_json: Any)[source]

Bases: object

Result class that helps users interpret the fairly complex structured output from risk attribution, specifically helping break down the various pivots by asset, sector, etc.. We strongly recommend using this to ease migrations when output formats change.

Parameters:

raw_json – the raw JSON result object from the server

get_absolute_risk_by_asset() Dict[UUID, Risk][source]

Extracts the per-asset absolute risk values as a simple map.

get_absolute_risk_by_sector() Dict[SectorPath, Risk][source]

Extracts the per-sector absolute risk values as a simple map; note that every path (e.g. sectorLevel1, sectorLevel1/sectorLevel2, etc.) is represented in the map, so you can pull risks at any level in the tree.

get_asset_sectors() Dict[UUID, SectorPath][source]

Gets a mapping from assetId to SectorPath. Not yet supported.

get_marginal_risk_by_asset() Dict[UUID, Risk][source]

Extracts the per-asset asset marginal risk values as a simple map.

get_portfolio_risk_by_factor() Dict[str, TotalFactorRisk][source]

Extracts the per-factor risks as a simple map.

get_portfolio_variance() Risk[source]

Extracts the top-level risk expressed in variance.

get_portfolio_volatility() Risk[source]

Extracts the top-level risk expressed in volatility.

get_raw_output() Any[source]

Gets the full JSON object returned from the risk attribution API.

get_relative_risk_by_asset() Dict[UUID, Risk][source]

Extracts the per-asset relative risk values as a simple map.

get_relative_risk_by_sector() Dict[SectorPath, Risk][source]

Extracts the per-sector relative risk values as a simple map; note that every path (e.g. sectorLevel1, sectorLevel1/sectorLevel2, etc.) is represented in the map, so you can pull risks at any level in the tree.

get_sector_factor_exposures() Dict[SectorPath, List[SectorFactorExposure]][source]

Gets a mapping from sector path to the factor exposure for that sector, by factor name.

class serenity_sdk.types.factors.SectorFactorExposure(factor: str, sector_path: SectorPath, absolute_risk: float, relative_risk: float, marginal_risk: float, factor_exposure: FactorExposureValue)[source]

Bases: object

Sector-specific risk metrics and factor exposures

absolute_risk: float

The sector’s risk expressed as absolute volatility %

factor: str

The name of the factor, e.g. Market or Momentum

factor_exposure: FactorExposureValue

The sector’s exposure to the risk of the given factor

marginal_risk: float

The portfolio’s sensitivity to the particular risk measure for this sector path

relative_risk: float

The sector path’s risk expressed as a fraction of portfolio risk

sector_path: SectorPath

The fully-qualified path to this particular sector, sector / sub-sector, etc..

class serenity_sdk.types.factors.TotalFactorRisk(factor: str, absolute_risk_contribution: float, relative_risk_contribution: float, marginal_risk_contribution: float, factor_exposure: FactorExposureValue)[source]

Bases: object

High-level summary of portfolio risk by factor

absolute_risk_contribution: float

The portfolio’s risk from this factor expressed as absolute volatility or variance

factor: str

The name of the factor, e.g. Market or Momentum

factor_exposure: FactorExposureValue

The portfolio’s exposure to the risk of the given factor

marginal_risk_contribution: float

The portfolio’s sensitivity to changes in the amount of exposure to this particular factor

relative_risk_contribution: float

The portfolio’s risk from this factor expressed as a fraction of portfolio risk

serenity_sdk.types.model

class serenity_sdk.types.model.ModelMetadata(model_classes: List[Any], models: List[Any], model_configs: List[Any])[source]

Bases: object

Helper class that encapsulates all the model metadata. You can get at the underlying calls directly from the ModelApi client or you can just load everything in this class and use it to traverse the metadata tree.

The most important call is probably get_model_configuration_id(), which lets you do a lookup of a ModelConfiguration ID by the short name. This is needed to specify model inputs for risk calcs.

get_model_class_names() List[str][source]

Enumerates the names of model classes, groupings of related models like Market Risk, Liquidity Risk or Value at Risk.

get_model_configuration_id(short_name: str) UUID[source]

Lookup function that gives you the UUID of a ModelConfiguration given its short name. Returns None if unknown.

get_model_configurations() Dict[source]

Enumerates the names of all model configurations; this corresponds to specific parameterizations of models, e.g. short time horizon and long time horizon variations of a factor risk model are two different configurations.

get_model_names() List[str][source]

Enumerates the names of all models; this corresponds to code implementations of different types of models.

serenity_sdk.types.refdata

class serenity_sdk.types.refdata.AssetMaster(asset_summaries: List[Any])[source]

Bases: object

Result class that holds the contents of the Serenity asset catalog in memory, making it easier to query it and also to create Portfolio objects from it.

create_portfolio(positions: Dict[str, float], symbology: str = 'NATIVE') Portfolio[source]

Mapping function that takes a set of raw positions in a given symbology and then converts them to Serenity’s internal identifiers and creates a Portfolio that can then be used with our tools. Note there are two ‘special’ symbologies, NATIVE and SERENITY. NATIVE uses the native blockchain symbol and SERENITY uses Serenity’s own native symbology, e.g. BTC and tok.btc.bitcoin respectively. The rest correspond to the API’s list of symbol authorities, e.g. COINGECKO.

Parameters:
  • positions – a raw mapping from symbol to weight, where negative weights indicate short positions

  • symbology – a name from the list of supported symbol authorities, e.g. COINGECKO, or one of two special symbologies, NATIVE or SERENITY; NATIVE uses the native blockchain symbol and SERENITY uses Serenity’s own native symbology, e.g. BTC and tok.btc.bitcoin respectively

get_asset_id_by_symbol(symbol: str, symbology: str = 'NATIVE')[source]

Lookup helper that looks up asset ID by symbol based on a given symbology.

Parameters:
  • symbol – a known symbol for this asset, e.g. BTC or bitcoin

  • symbology – a name from the list of supported symbol authorities, e.g. COINGECKO, or one of two special symbologies, NATIVE or SERENITY; NATIVE uses the native blockchain symbol and SERENITY uses Serenity’s own native symbology, e.g. BTC and tok.btc.bitcoin respectively

get_symbol_by_id(asset_id: UUID, symbology: str = 'NATIVE')[source]

Lookup helper that gets a particular symbol type for a given asset ID.

Parameters:
  • asset_id – Serenity’s unique ID for this asset

  • symbology – a name from the list of supported symbol authorities, e.g. COINGECKO, or one of two special symbologies, NATIVE or SERENITY; NATIVE uses the native blockchain symbol and SERENITY uses Serenity’s own native symbology, e.g. BTC and tok.btc.bitcoin respectively

serenity_sdk.types.valuation

class serenity_sdk.types.valuation.PortfolioValue(net_holdings_value: float, gross_holdings_value: float, cash_position_value: float, net_asset_value: float)[source]

Bases: object

Wrapper object holding all of the valuation output for a given portfolio

cash_position_value: float

The total value of the portfolio’s cash positionsm, as defined by CashTreatment

gross_holdings_value: float

The gross value of the portfolio’s assets excluding cash; the sum of the absolute values of all position values

net_asset_value: float

The sum of the net holdings and the cash positions, or NAV

net_holdings_value: float

The net value of the portfolio’s assets excluding cash; the sum of all position values

class serenity_sdk.types.valuation.PositionValue(value: float, price: float, quantity: float, weight: float)[source]

Bases: object

price: float

The price used to calculate this position value

quantity: float

The quantity of the asset used to calculate this position value

value: float

The value of this specific position, expressed in base currency

weight: float

The percentage weight of this asset in the whole portfolio; may be negative in long/short portfolios

class serenity_sdk.types.valuation.PositionValues(close: serenity_sdk.types.valuation.PositionValue, previous: serenity_sdk.types.valuation.PositionValue)[source]

Bases: object

close: PositionValue

The value of the position as of the most recent close, based on MarkTime

previous: PositionValue

The value of the position as of the previous close, based on MarkTime

class serenity_sdk.types.valuation.ValuationResult(close: serenity_sdk.types.valuation.PortfolioValue, previous: serenity_sdk.types.valuation.PortfolioValue, positions: Dict[uuid.UUID, serenity_sdk.types.valuation.PositionValues])[source]

Bases: object

close: PortfolioValue

The value of the portfolio as of the most recent close, based on MarkTime

positions: Dict[UUID, PositionValues]

The values of the individual constituents of the portfolio

previous: PortfolioValue

The value of the portfolio as of the previous close, based on MarkTime