openseries.OpenTimeSeries

class openseries.OpenTimeSeries(*, tsdf, timeseries_id, instrument_id, name, valuetype, dates, values, local_ccy, currency, domestic='SEK', countries='SE', markets=None, isin=None, label=None)[source]

Bases: _CommonModel[float]

OpenTimeSeries objects are at the core of the openseries package.

The intended use is to allow analyses of financial timeseries. It is only intended for daily or less frequent data samples.

Parameters:
  • timeseries_id (str) – Database identifier of the timeseries.

  • instrument_id (str) – Database identifier of the instrument associated with the timeseries.

  • name (str) – String identifier of the timeseries and/or instrument.

  • valuetype (ValueType) – Identifies if the series is a series of values or returns.

  • dates (Annotated[list[Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=True, min_length=10, max_length=10, pattern=^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$)]], MinLen(min_length=1)]) – Dates of the individual timeseries items. These dates will not be altered by methods.

  • values (Annotated[list[float], MinLen(min_length=1)]) – The value or return values of the timeseries items. These values will not be altered by methods.

  • local_ccy (bool) – Boolean flag indicating if timeseries is in local currency.

  • tsdf (DataFrame) – Pandas object holding dates and values that can be altered via methods.

  • currency (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, to_lower=None, strict=True, min_length=3, max_length=3, pattern=^[A-Z]{3}$)]) – ISO 4217 currency code of the timeseries.

  • domestic (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, to_lower=None, strict=True, min_length=3, max_length=3, pattern=^[A-Z]{3}$)]) – ISO 4217 currency code of the user’s home currency. Defaults to “SEK”.

  • countries (Annotated[set[Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, to_lower=None, strict=True, min_length=2, max_length=2, pattern=^[A-Z]{2}$)]], MinLen(min_length=1)] | Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, to_lower=None, strict=True, min_length=2, max_length=2, pattern=^[A-Z]{2}$)]) – (List of) country code(s) according to ISO 3166-1 alpha-2. Defaults to “SE”.

  • markets (list[str] | str | None) – (List of) markets code(s) supported by exchange_calendars. Optional.

  • isin (str | None) – ISO 6166 identifier code of the associated instrument. Optional.

  • label (str | None) – Placeholder for a name of the timeseries. Optional.

__init__(**data)

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

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:

data (Any)

Return type:

None

Methods

__init__(**data)

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

align_index_to_local_cdays([countries, ...])

Align the index of .tsdf with local calendar business days.

all_properties([properties])

Calculate chosen properties.

arithmetic_ret_func([months_from_last, ...])

Annualized arithmetic mean of returns.

calc_range([months_offset, from_dt, to_dt])

Create a user-defined date range aligned to index.

construct([_fields_set])

copy(*[, include, exclude, update, deep])

Returns a copy of the model.

cvar_down_func([level, months_from_last, ...])

Downside Conditional Value At Risk (CVaR).

dict(*[, include, exclude, by_alias, ...])

ewma_vol_func([lmbda, day_chunk, ...])

Exponentially Weighted Moving Average Model for Volatility.

from_1d_rate_to_cumret([days_in_year, divider])

Convert series of 1-day rates into series of cumulative values.

from_arrays(name, dates, values[, ...])

Create series from a list of dates and a list of values.

from_deepcopy()

Create copy of OpenTimeSeries object.

from_df(dframe[, column_nmbr, valuetype, ...])

Create series from a Pandas DataFrame or Series.

from_fixed_rate(rate[, d_range, days, ...])

Create series from values accruing with a given fixed rate return.

from_orm(obj)

geo_ret_func([months_from_last, from_date, ...])

Compounded Annual Growth Rate (CAGR).

json(*[, include, exclude, by_alias, ...])

kurtosis_func([months_from_last, from_date, ...])

Kurtosis of the return distribution.

lower_partial_moment_func([...])

Lower partial moment and downside deviation (order=2).

max_drawdown_func([months_from_last, ...])

Maximum drawdown without any limit on date range.

model_construct([_fields_set])

Creates a new instance of the Model class with validated data.

model_copy(*[, update, deep])

!!! abstract "Usage Documentation"

model_dump(*[, mode, include, exclude, ...])

!!! abstract "Usage Documentation"

model_dump_json(*[, indent, ensure_ascii, ...])

!!! abstract "Usage Documentation"

model_json_schema([by_alias, ref_template, ...])

Generates a JSON schema for a model class.

model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

model_post_init(context, /)

Override this method to perform additional initialization after __init__ and model_construct.

model_rebuild(*[, force, raise_errors, ...])

Try to rebuild the pydantic-core schema for the model.

model_validate(obj, *[, strict, extra, ...])

Validate a pydantic model instance.

model_validate_json(json_data, *[, strict, ...])

!!! abstract "Usage Documentation"

model_validate_strings(obj, *[, strict, ...])

Validate the given object with string data against the Pydantic model.

omega_ratio_func([min_accepted_return, ...])

Omega Ratio.

outliers([threshold, months_from_last, ...])

Detect outliers using z-score analysis.

pandas_df()

Populate .tsdf Pandas DataFrame from the .dates and .values lists.

parse_file(path, *[, content_type, ...])

parse_obj(obj)

parse_raw(b, *[, content_type, encoding, ...])

plot_bars([mode, title, tick_fmt, filename, ...])

Create a Plotly Bar Figure.

plot_histogram([plot_type, histnorm, ...])

Create a Plotly Histogram Figure.

plot_series([mode, title, tick_fmt, ...])

Create a Plotly Scatter Figure.

positive_share_func([months_from_last, ...])

Share of percentage changes greater than zero.

resample([freq])

Resamples the timeseries frequency.

resample_to_business_period_ends([freq, method])

Resamples timeseries frequency to the business calendar month end dates.

ret_vol_ratio_func([riskfree_rate, ...])

Ratio between arithmetic mean of returns and annualized volatility.

return_nan_handle([method])

Handle missing values in a return series.

rolling_cvar_down([column, level, observations])

Calculate rolling annualized downside CVaR.

rolling_return([column, observations])

Calculate rolling returns.

rolling_var_down([column, level, ...])

Calculate rolling annualized downside Value At Risk (VaR).

rolling_vol([column, observations, ...])

Calculate rolling annualized volatilities.

running_adjustment(adjustment[, days_in_year])

Add or subtract a fee from the timeseries return.

schema([by_alias, ref_template])

schema_json(*[, by_alias, ref_template])

set_new_label([lvl_zero, lvl_one, ...])

Set the column labels of the .tsdf Pandas Dataframe.

skew_func([months_from_last, from_date, to_date])

Skew of the return distribution.

sortino_ratio_func([riskfree_rate, ...])

Sortino ratio or Kappa-3 ratio.

target_weight_from_var([target_vol, level, ...])

Target weight from VaR.

to_cumret()

Convert series of returns into cumulative series of values.

to_drawdown_series()

Convert timeseries into a drawdown series.

to_json(what_output, filename[, directory])

Dump timeseries data into a JSON file.

to_xlsx(filename[, sheet_title, directory, ...])

Save .tsdf DataFrame to an Excel spreadsheet file.

update_forward_refs(**localns)

validate(value)

value_nan_handle([method])

Handle missing values in a value series.

value_ret_calendar_period(year[, month])

Calculate simple return for a specific calendar period.

value_ret_func([months_from_last, ...])

Calculate simple return.

value_to_diff([periods])

Convert series of values to series of their period differences.

value_to_log()

Convert value series to log-weighted series.

value_to_ret()

Convert series of values into series of returns.

var_down_func([level, months_from_last, ...])

Downside Value At Risk (VaR).

vol_from_var_func([level, months_from_last, ...])

Implied annualized volatility from downside VaR.

vol_func([months_from_last, from_date, ...])

Annualized volatility.

worst_func([observations, months_from_last, ...])

Most negative percentage change over a rolling window.

z_score_func([months_from_last, from_date, ...])

Z-score of the last return.

Attributes

arithmetic_ret

Annualized arithmetic mean of returns.

cvar_down

Downside 95% Conditional Value At Risk "CVaR".

downside_deviation

Downside Deviation.

first_idx

The first date in the timeseries.

geo_ret

Compounded Annual Growth Rate (CAGR).

kappa3_ratio

Kappa-3 ratio.

kurtosis

Kurtosis of the return distribution.

last_idx

The last date in the timeseries.

length

Number of observations.

max_drawdown

Maximum drawdown without any limit on date range.

max_drawdown_cal_year

Maximum drawdown in a single calendar year.

max_drawdown_date

Date when the maximum drawdown occurred.

model_computed_fields

model_config

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_extra

Get extra fields set during validation.

model_fields

model_fields_set

Returns the set of fields that have been explicitly set on this model instance.

omega_ratio

Omega ratio.

periods_in_a_year

The average number of observations per year.

positive_share

The share of percentage changes that are greater than zero.

ret_vol_ratio

Ratio of annualized arithmetic mean of returns and annualized volatility.

skew

Skew of the return distribution.

sortino_ratio

Sortino ratio.

span_of_days

Number of days from the first date to the last.

value_ret

Simple return.

var_down

Downside 95% Value At Risk (VaR).

vol

Annualized volatility.

vol_from_var

Implied annualized volatility from Downside 95% Value at Risk.

worst

Most negative percentage change.

worst_month

Most negative month.

yearfrac

Length of series in years assuming 365.25 days per year.

z_score

Z-score.

timeseries_id

instrument_id

name

valuetype

dates

values

local_ccy

tsdf

currency

domestic

countries

markets

isin

label

timeseries_id: str
instrument_id: str
name: str
valuetype: ValueType
dates: DateListType
values: ValueListType
local_ccy: bool
tsdf: DataFrame
currency: CurrencyStringType
domestic: CurrencyStringType
countries: CountriesType
markets: list[str] | str | None
isin: str | None
label: str | None
classmethod from_arrays(name, dates, values, valuetype=ValueType.PRICE, timeseries_id='', instrument_id='', isin=None, baseccy='SEK', *, local_ccy=True)[source]

Create series from a list of dates and a list of values.

Parameters:
  • name (str) – String identifier of the timeseries and/or instrument.

  • dates (Annotated[list[Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=True, min_length=10, max_length=10, pattern=^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$)]], MinLen(min_length=1)]) – List of date strings as ISO 8601 YYYY-MM-DD.

  • values (Annotated[list[float], MinLen(min_length=1)]) – Array of float values.

  • valuetype (ValueType) – Identifies if the series is a series of values or returns. Defaults to ValueType.PRICE.

  • timeseries_id (str) – Database identifier of the timeseries. Optional.

  • instrument_id (str) – Database identifier of the instrument associated with the timeseries. Optional.

  • isin (str | None) – ISO 6166 identifier code of the associated instrument. Optional.

  • baseccy (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, to_lower=None, strict=True, min_length=3, max_length=3, pattern=^[A-Z]{3}$)]) – ISO 4217 currency code of the timeseries. Defaults to “SEK”.

  • local_ccy (bool) – Boolean flag indicating if timeseries is in local currency. Defaults to True.

Returns:

An OpenTimeSeries object.

Return type:

Self

classmethod from_df(dframe, column_nmbr=0, valuetype=ValueType.PRICE, baseccy='SEK', *, local_ccy=True)[source]

Create series from a Pandas DataFrame or Series.

Parameters:
  • dframe (Series[float] | DataFrame) – Pandas DataFrame or Series.

  • column_nmbr (int) – Using iloc[:, column_nmbr] to pick column. Defaults to 0.

  • valuetype (ValueType) – Identifies if the series is a series of values or returns. Defaults to ValueType.PRICE.

  • baseccy (CurrencyStringType) – ISO 4217 currency code of the timeseries. Defaults to “SEK”.

  • local_ccy (bool) – Boolean flag indicating if timeseries is in local currency. Defaults to True.

Returns:

An OpenTimeSeries object.

Raises:

TypeError – If dframe is not a pandas.Series or a pandas.DataFrame.

Return type:

Self

classmethod from_fixed_rate(rate, d_range=None, days=None, end_dt=None, label='Series', valuetype=ValueType.PRICE, baseccy='SEK', *, local_ccy=True)[source]

Create series from values accruing with a given fixed rate return.

Providing a date_range of type Pandas DatetimeIndex takes priority over providing a combination of days and an end date.

Parameters:
  • rate (float) – The accrual rate.

  • d_range (DatetimeIndex | None) – A given range of dates. Optional.

  • days (int | None) – Number of days to generate when date_range not provided. Must be combined with end_dt. Optional.

  • end_dt (date | None) – End date of date range to generate when date_range not provided. Must be combined with days. Optional.

  • label (str) – Placeholder for a name of the timeseries.

  • valuetype (ValueType) – Identifies if the series is a series of values or returns. Defaults to ValueType.PRICE.

  • baseccy (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, to_lower=None, strict=True, min_length=3, max_length=3, pattern=^[A-Z]{3}$)]) – The currency of the timeseries. Defaults to “SEK”.

  • local_ccy (bool) – Boolean flag indicating if timeseries is in local currency. Defaults to True.

Returns:

An OpenTimeSeries object.

Raises:

IncorrectArgumentComboError – If d_range is not provided and the combination of days and end_dt is incomplete.

Return type:

Self

from_deepcopy()[source]

Create copy of OpenTimeSeries object.

Returns:

An OpenTimeSeries object.

Parameters:

self (Self)

Return type:

Self

pandas_df()[source]

Populate .tsdf Pandas DataFrame from the .dates and .values lists.

Returns:

An OpenTimeSeries object.

Parameters:

self (Self)

Return type:

Self

all_properties(properties=None)[source]

Calculate chosen properties.

Parameters:
  • properties (list[Literal['value_ret', 'geo_ret', 'arithmetic_ret', 'vol', 'downside_deviation', 'ret_vol_ratio', 'sortino_ratio', 'kappa3_ratio', 'z_score', 'skew', 'kurtosis', 'positive_share', 'var_down', 'cvar_down', 'vol_from_var', 'worst', 'worst_month', 'max_drawdown_cal_year', 'max_drawdown', 'max_drawdown_date', 'first_idx', 'last_idx', 'length', 'span_of_days', 'yearfrac', 'periods_in_a_year']] | None) – The properties to calculate. Defaults to calculating all available. Optional.

  • self (Self)

Returns:

Properties of the OpenTimeSeries.

Return type:

DataFrame

value_to_ret()[source]

Convert series of values into series of returns.

Returns:

The returns of the values in the series.

Parameters:

self (Self)

Return type:

Self

value_to_diff(periods=1)[source]

Convert series of values to series of their period differences.

Parameters:
  • periods (int) – The number of periods between observations over which difference is calculated. Defaults to 1.

  • self (Self)

Returns:

An OpenTimeSeries object.

Return type:

Self

to_cumret()[source]

Convert series of returns into cumulative series of values.

Returns:

An OpenTimeSeries object.

Parameters:

self (Self)

Return type:

Self

from_1d_rate_to_cumret(days_in_year=365, divider=1.0)[source]

Convert series of 1-day rates into series of cumulative values.

Parameters:
  • days_in_year (int) – Calendar days per year used as divisor. Defaults to 365.

  • divider (float) – Convenience divider for when the 1-day rate is not scaled correctly. Defaults to 1.0.

  • self (Self)

Returns:

An OpenTimeSeries object.

Return type:

Self

resample(freq='BME')[source]

Resamples the timeseries frequency.

Parameters:
  • freq (Literal['B', 'BME', 'BQE', 'BYE'] | str) – The date offset string that sets the resampled frequency. Defaults to “BME”.

  • self (Self)

Returns:

An OpenTimeSeries object.

Return type:

Self

resample_to_business_period_ends(freq='BME', method='nearest')[source]

Resamples timeseries frequency to the business calendar month end dates.

Stubs left in place. Stubs will be aligned to the shortest stub.

Parameters:
  • freq (Literal['B', 'BME', 'BQE', 'BYE']) – The date offset string that sets the resampled frequency. Defaults to BME.

  • method (Literal['pad', 'ffill', 'backfill', 'bfill', 'nearest'] | None) – Controls the method used to align values across columns. Defaults to nearest.

  • self (Self)

Returns:

An OpenTimeSeries object.

Raises:

ResampleDataLossError – If called on a return series (valuetype is ValueType.RTRN), since summation across sparser frequency would be required to avoid data loss.

Return type:

Self

ewma_vol_func(lmbda=0.94, day_chunk=11, dlta_degr_freedms=0, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Exponentially Weighted Moving Average Model for Volatility.

Reference: https://www.investopedia.com/articles/07/ewma.asp.

Parameters:
  • lmbda (float) – Scaling factor to determine weighting. Defaults to 0.94.

  • day_chunk (int) – Sampling the data which is assumed to be daily. Defaults to 11.

  • dlta_degr_freedms (int) – Variance bias factor taking the value 0 or 1. Defaults to 0.

  • months_from_last (int | None) – Number of months offset as positive integer. Overrides use of from_date and to_date. Optional.

  • from_date (dt.date | None) – Specific from date. Optional.

  • to_date (dt.date | None) – Specific to date. Optional.

  • periods_in_a_year_fixed (DaysInYearType | None) – Allows locking the periods-in-a-year to simplify test cases and comparisons. Optional.

  • self (Self)

Returns:

Series EWMA volatility.

Return type:

Series[float]

running_adjustment(adjustment, days_in_year=365)[source]

Add or subtract a fee from the timeseries return.

Parameters:
  • adjustment (float) – Fee to add or subtract.

  • days_in_year (int) – The calculation divisor and assumed number of days in a calendar year. Defaults to 365.

  • self (Self)

Returns:

An OpenTimeSeries object.

Return type:

Self

set_new_label(lvl_zero=None, lvl_one=None, *, delete_lvl_one=False)[source]

Set the column labels of the .tsdf Pandas Dataframe.

Parameters:
  • lvl_zero (str | None) – New level zero label. Optional.

  • lvl_one (ValueType | None) – New level one label. Optional.

  • delete_lvl_one (bool) – If True the level one label is deleted. Defaults to False.

  • self (Self)

Returns:

An OpenTimeSeries object.

Return type:

Self

model_config = {'arbitrary_types_allowed': True, 'revalidate_instances': 'always', 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].