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.
- 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
- 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:
- 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
dframeis not apandas.Seriesor apandas.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_rangeis not provided and the combination ofdaysandend_dtis incomplete.- Return type:
- from_deepcopy()[source]
Create copy of OpenTimeSeries object.
- pandas_df()[source]
Populate .tsdf Pandas DataFrame from the .dates and .values lists.
- 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:
- value_to_ret()[source]
Convert series of values into series of returns.
- value_to_diff(periods=1)[source]
Convert series of values to series of their period differences.
- to_cumret()[source]
Convert series of returns into cumulative series of values.
- from_1d_rate_to_cumret(days_in_year=365, divider=1.0)[source]
Convert series of 1-day rates into series of cumulative values.
- resample(freq='BME')[source]
Resamples the timeseries frequency.
- 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:
- Returns:
An OpenTimeSeries object.
- Raises:
ResampleDataLossError – If called on a return series (
valuetypeisValueType.RTRN), since summation across sparser frequency would be required to avoid data loss.- Return type:
- 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.
- set_new_label(lvl_zero=None, lvl_one=None, *, delete_lvl_one=False)[source]
Set the column labels of the .tsdf Pandas Dataframe.
- 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].
The OpenTimeSeries class is the core component for analyzing individual financial time series. It provides comprehensive functionality for:
Loading data from various sources (arrays, DataFrames, fixed rates)
Calculating financial metrics and risk measures
Performing time series transformations
Creating visualizations
Exporting results
Class Methods for Construction
- classmethod OpenTimeSeries.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:
- classmethod OpenTimeSeries.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
dframeis not apandas.Seriesor apandas.DataFrame.- Return type:
Self
- classmethod OpenTimeSeries.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_rangeis not provided and the combination ofdaysandend_dtis incomplete.- Return type:
Properties
Non-numerical Properties
- OpenTimeSeries.timeseries_id: str
- OpenTimeSeries.instrument_id: str
- OpenTimeSeries.dates: DateListType
- OpenTimeSeries.values: ValueListType
- OpenTimeSeries.currency: CurrencyStringType
- OpenTimeSeries.domestic: CurrencyStringType
- OpenTimeSeries.local_ccy: bool
- OpenTimeSeries.name: str
- OpenTimeSeries.countries: CountriesType
- OpenTimeSeries.valuetype: ValueType
Common Properties
- OpenTimeSeries.first_idx
The first date in the timeseries.
- Returns:
The first date in the timeseries.
- OpenTimeSeries.last_idx
The last date in the timeseries.
- Returns:
The last date in the timeseries.
- OpenTimeSeries.length
Number of observations.
- Returns:
Number of observations.
- OpenTimeSeries.span_of_days
Number of days from the first date to the last.
- Returns:
Number of days from the first date to the last.
- OpenTimeSeries.tsdf: DataFrame
- OpenTimeSeries.max_drawdown_date
Date when the maximum drawdown occurred.
Reference: https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp.
Returns:
- datetime.date | pandas.Series[dt.date]
Date when the maximum drawdown occurred
- OpenTimeSeries.periods_in_a_year
The average number of observations per year.
- Returns:
The average number of observations per year.
- OpenTimeSeries.yearfrac
Length of series in years assuming 365.25 days per year.
- Returns:
Length of the timeseries in years assuming 365.25 days per year.
Financial Metrics
- OpenTimeSeries.all_properties = <function OpenTimeSeries.all_properties>[source]
- Parameters:
self (Self)
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)
- Return type:
- OpenTimeSeries.arithmetic_ret
Annualized arithmetic mean of returns.
Reference: https://www.investopedia.com/terms/a/arithmeticmean.asp.
Returns:
- SeriesOrFloat_co
Annualized arithmetic mean of returns. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.geo_ret
Compounded Annual Growth Rate (CAGR).
Reference: https://www.investopedia.com/terms/c/cagr.asp.
Returns:
- SeriesOrFloat_co
Compounded Annual Growth Rate (CAGR). Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.value_ret
Simple return.
Returns:
- SeriesOrFloat_co
Simple return. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.vol
Annualized volatility.
Based on Pandas .std() which is the equivalent of stdev.s([…]) in MS Excel.
Reference: https://www.investopedia.com/terms/v/volatility.asp.
Returns:
- SeriesOrFloat_co
Annualized volatility. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.downside_deviation
Downside Deviation.
Standard deviation of returns that are below a Minimum Accepted Return of zero. It is used to calculate the Sortino Ratio.
Reference: https://www.investopedia.com/terms/d/downside-deviation.asp.
Returns:
- SeriesOrFloat_co
Downside deviation. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.ret_vol_ratio
Ratio of annualized arithmetic mean of returns and annualized volatility.
Returns:
- SeriesOrFloat_co
Ratio of the annualized arithmetic mean of returns and annualized volatility. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.sortino_ratio
Sortino ratio.
Reference: https://www.investopedia.com/terms/s/sortinoratio.asp.
Returns:
- SeriesOrFloat_co
Sortino ratio calculated as the annualized arithmetic mean of returns / downside deviation. The ratio implies that the riskfree asset has zero volatility, and a minimum acceptable return of zero. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.kappa3_ratio
Kappa-3 ratio.
The Kappa-3 ratio is a generalized downside-risk ratio defined as annualized arithmetic return divided by the cubic-root of the lower partial moment of order 3 (with respect to a minimum acceptable return, MAR). It penalizes larger downside outcomes more heavily than the Sortino ratio (which uses order 2).
Returns:
- SeriesOrFloat_co
Kappa-3 ratio calculation with the riskfree rate and. Minimum Acceptable Return (MAR) both set to zero. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.omega_ratio
Omega ratio.
Reference: https://en.wikipedia.org/wiki/Omega_ratio.
Returns:
- SeriesOrFloat_co
Omega ratio calculation. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.var_down
Downside 95% Value At Risk (VaR).
The equivalent of percentile.inc([…], 1-level) over returns in MS Excel. https://www.investopedia.com/terms/v/var.asp.
Returns:
- SeriesOrFloat_co
Downside 95% Value At Risk (VaR). Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.cvar_down
Downside 95% Conditional Value At Risk “CVaR”.
Reference: https://www.investopedia.com/terms/c/conditional_value_at_risk.asp.
Returns:
- SeriesOrFloat_co
Downside 95% Conditional Value At Risk “CVaR”. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.worst
Most negative percentage change.
Returns:
- SeriesOrFloat_co
Most negative percentage change. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.worst_month
Most negative month.
Returns:
- SeriesOrFloat_co
Most negative month. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.max_drawdown
Maximum drawdown without any limit on date range.
Reference: https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp.
Returns:
- SeriesOrFloat_co
Maximum drawdown without any limit on date range. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.max_drawdown_cal_year
Maximum drawdown in a single calendar year.
Reference: https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp.
Returns:
- SeriesOrFloat_co
Maximum drawdown in a single calendar year. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.positive_share
The share of percentage changes that are greater than zero.
Returns:
- SeriesOrFloat_co
The share of percentage changes that are greater than zero. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.vol_from_var
Implied annualized volatility from Downside 95% Value at Risk.
Assumes that returns are normally distributed.
Returns:
- SeriesOrFloat_co
Implied annualized volatility from the Downside 95% VaR using the assumption that returns are normally distributed. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.skew
Skew of the return distribution.
Reference: https://www.investopedia.com/terms/s/skewness.asp.
Returns:
- SeriesOrFloat_co
Skew of the return distribution. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.kurtosis
Kurtosis of the return distribution.
Reference: https://www.investopedia.com/terms/k/kurtosis.asp.
Returns:
- SeriesOrFloat_co
Kurtosis of the return distribution. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
- OpenTimeSeries.z_score
Z-score.
Reference: https://www.investopedia.com/terms/z/zscore.asp.
Returns:
- SeriesOrFloat_co
Z-score as (last return - mean return) / standard deviation of returns. Returns float for OpenTimeSeries, Series[float] for OpenFrame.
Methods
Data Manipulation
- OpenTimeSeries.pandas_df()[source]
Populate .tsdf Pandas DataFrame from the .dates and .values lists.
- OpenTimeSeries.set_new_label(lvl_zero=None, lvl_one=None, *, delete_lvl_one=False)[source]
Set the column labels of the .tsdf Pandas Dataframe.
- OpenTimeSeries.running_adjustment(adjustment, days_in_year=365)[source]
Add or subtract a fee from the timeseries return.
- OpenTimeSeries.from_1d_rate_to_cumret(days_in_year=365, divider=1.0)[source]
Convert series of 1-day rates into series of cumulative values.
- OpenTimeSeries.align_index_to_local_cdays(countries=None, markets=None, custom_holidays=None, method='nearest')
Align the index of
.tsdfwith local calendar business days.- Parameters:
countries (CountriesType | None) – Country code(s) (ISO 3166-1 alpha-2).
markets (list[str] | str | None) – Market code(s) supported by
exchange_calendars.custom_holidays (list[str] | str | None) – Missing holidays that should be added.
method (LiteralPandasReindexMethod) – Method for reindexing when aligning to business days.
self (Self)
- Returns:
The modified object.
- Return type:
Self
- OpenTimeSeries.resample(freq='BME')[source]
Resamples the timeseries frequency.
- OpenTimeSeries.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:
- Returns:
An OpenTimeSeries object.
- Raises:
ResampleDataLossError – If called on a return series (
valuetypeisValueType.RTRN), since summation across sparser frequency would be required to avoid data loss.- Return type:
- OpenTimeSeries.value_nan_handle(method='fill')
Handle missing values in a value series.
- Parameters:
method (LiteralNanMethod) – Method used to handle NaN. Either
"fill"(last known) or"drop".self (Self)
- Returns:
The modified object.
- Return type:
Self
- OpenTimeSeries.return_nan_handle(method='fill')
Handle missing values in a return series.
- Parameters:
method (LiteralNanMethod) – Method used to handle NaN. Either
"fill"(zero) or"drop".self (Self)
- Returns:
The modified object.
- Return type:
Self
Transformations
- OpenTimeSeries.to_cumret()[source]
Convert series of returns into cumulative series of values.
- OpenTimeSeries.value_to_ret()[source]
Convert series of values into series of returns.
- OpenTimeSeries.value_to_diff(periods=1)[source]
Convert series of values to series of their period differences.
- OpenTimeSeries.value_to_log()
Convert value series to log-weighted series.
Equivalent to
LN(value[t] / value[t=0])in Excel.
Analysis Methods
- OpenTimeSeries.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]
- OpenTimeSeries.value_ret_calendar_period(year, month=None)
Calculate simple return for a specific calendar period.
- OpenTimeSeries.rolling_return(column=0, observations=21)
Calculate rolling returns.
- OpenTimeSeries.rolling_vol(column=0, observations=21, periods_in_a_year_fixed=None, dlta_degr_freedms=1)
Calculate rolling annualized volatilities.
- Parameters:
- Returns:
DataFrame with rolling annualized volatilities.
- Return type:
DataFrame
- OpenTimeSeries.rolling_var_down(column=0, level=0.95, observations=252, interpolation='lower')
Calculate rolling annualized downside Value At Risk (VaR).
- Parameters:
- Returns:
DataFrame with rolling annualized downside VaR.
- Return type:
DataFrame
- OpenTimeSeries.rolling_cvar_down(column=0, level=0.95, observations=252)
Calculate rolling annualized downside CVaR.
- OpenTimeSeries.calc_range(months_offset=None, from_dt=None, to_dt=None)
Create a user-defined date range aligned to index.
- Parameters:
- Returns:
A tuple
(earlier, later)representing the start and end date of the chosen date range aligned to existing index values.- Raises:
DateAlignmentError – If the implied range is outside series bounds.
- Return type:
- OpenTimeSeries.outliers(threshold=3.0, months_from_last=None, from_date=None, to_date=None)
Detect outliers using z-score analysis.
Identifies data points where the absolute z-score exceeds the threshold. For OpenTimeSeries, returns a Series with dates and outlier values. For OpenFrame, returns a DataFrame with dates and outlier values for each column.
- Parameters:
- Returns:
Series of outliers. For OpenFrame: DataFrame of outliers. Empty if none found.
- Return type:
For OpenTimeSeries
Financial Metrics Methods
- OpenTimeSeries.arithmetic_ret_func(months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)
Annualized arithmetic mean of returns.
Reference:
https://www.investopedia.com/terms/a/arithmeticmean.asp.- Parameters:
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.
self (Self)
- Returns:
Annualized arithmetic mean of returns. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.geo_ret_func(months_from_last=None, from_date=None, to_date=None)
Compounded Annual Growth Rate (CAGR).
Reference:
https://www.investopedia.com/terms/c/cagr.asp.- Parameters:
- Returns:
CAGR. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Raises:
InitialValueZeroError – If initial value is zero or there are negative values.
- Return type:
SeriesOrFloat_co
- OpenTimeSeries.value_ret_func(months_from_last=None, from_date=None, to_date=None)
Calculate simple return.
- Parameters:
- Returns:
Simple return. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Raises:
InitialValueZeroError – If initial value is zero.
- Return type:
SeriesOrFloat_co
- OpenTimeSeries.vol_func(months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)
Annualized volatility.
Based on
pandas.Series.std()(ExcelSTDEV.Sequivalent). Reference:https://www.investopedia.com/terms/v/volatility.asp.- Parameters:
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.
self (Self)
- Returns:
Annualized volatility. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.lower_partial_moment_func(min_accepted_return=0.0, order=2, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)
Lower partial moment and downside deviation (order=2).
If
orderis 2 calculates standard deviation of returns below MAR=0. For general orderp, returns(LPM_p)^(1/p).- Parameters:
min_accepted_return (float) – Annualized Minimum Accepted Return (MAR).
order (Literal[2, 3]) – Order of partial moment (2 or 3).
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.
self (Self)
- Returns:
Downside deviation if
orderis 2; otherwise rooted lower partial moment. Float for OpenTimeSeries,Series[float]for OpenFrame.- Raises:
ValueError – If
orderis not 2 or 3.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.ret_vol_ratio_func(riskfree_rate=0.0, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)
Ratio between arithmetic mean of returns and annualized volatility.
If
riskfree_rateprovided, computes the Sharpe ratio as(arithmetic return - risk-free) / volatility. Assumes zero volatility for the risk-free asset. Reference:https://www.investopedia.com/terms/s/sharperatio.asp.- Parameters:
riskfree_rate (float) – Return of the zero volatility asset.
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.
self (Self)
- Returns:
Ratio value. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.sortino_ratio_func(riskfree_rate=0.0, min_accepted_return=0.0, order=2, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)
Sortino ratio or Kappa-3 ratio.
Sortino:
(return - riskfree_rate) / downside deviationusing arithmetic mean of returns. Kappa-3 whenorder=3penalizes larger downside more than Sortino.- Parameters:
riskfree_rate (float) – Return of the zero volatility asset.
min_accepted_return (float) – Annualized Minimum Accepted Return (MAR).
order (Literal[2, 3]) – Order of partial moment (2 for Sortino, 3 for Kappa-3).
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.
self (Self)
- Returns:
Ratio value. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.omega_ratio_func(min_accepted_return=0.0, months_from_last=None, from_date=None, to_date=None)
Omega Ratio.
Compares returns above MAR to the total downside risk below MAR. Reference:
https://en.wikipedia.org/wiki/Omega_ratio.- Parameters:
- Returns:
Omega ratio. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.var_down_func(level=0.95, months_from_last=None, from_date=None, to_date=None, interpolation='lower')
Downside Value At Risk (VaR).
Equivalent to
PERCENTILE.INC(returns, 1-level)in Excel. Reference:https://www.investopedia.com/terms/v/var.asp.- Parameters:
level (float) – The sought VaR level.
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
interpolation (LiteralQuantileInterp) – Interpolation used by
DataFrame.quantile.self (Self)
- Returns:
Downside VaR. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.cvar_down_func(level=0.95, months_from_last=None, from_date=None, to_date=None)
Downside Conditional Value At Risk (CVaR).
Reference:
https://www.investopedia.com/terms/c/conditional_value_at_risk.asp.- Parameters:
- Returns:
Downside CVaR. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.worst_func(observations=1, months_from_last=None, from_date=None, to_date=None)
Most negative percentage change over a rolling window.
- Parameters:
- Returns:
Most negative percentage change. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.max_drawdown_func(months_from_last=None, from_date=None, to_date=None, min_periods=1)
Maximum drawdown without any limit on date range.
Reference:
https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp.- Parameters:
- Returns:
Maximum drawdown. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.positive_share_func(months_from_last=None, from_date=None, to_date=None)
Share of percentage changes greater than zero.
- Parameters:
- Returns:
Share of positive returns. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.vol_from_var_func(level=0.95, months_from_last=None, from_date=None, to_date=None, interpolation='lower', periods_in_a_year_fixed=None, *, drift_adjust=False)
Implied annualized volatility from downside VaR.
Assumes normally distributed returns.
- Parameters:
level (float) – The sought VaR level.
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
interpolation (LiteralQuantileInterp) – Interpolation type used by
DataFrame.quantile.periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.
drift_adjust (bool) – Adjustment to remove the bias implied by the average return.
self (Self)
- Returns:
Implied annualized volatility. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.skew_func(months_from_last=None, from_date=None, to_date=None)
Skew of the return distribution.
Reference:
https://www.investopedia.com/terms/s/skewness.asp.- Parameters:
- Returns:
Skewness. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.kurtosis_func(months_from_last=None, from_date=None, to_date=None)
Kurtosis of the return distribution.
Reference:
https://www.investopedia.com/terms/k/kurtosis.asp.- Parameters:
- Returns:
Kurtosis. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.z_score_func(months_from_last=None, from_date=None, to_date=None)
Z-score of the last return.
Computed as
(last return - mean return) / std dev of returns. Reference:https://www.investopedia.com/terms/z/zscore.asp.- Parameters:
- Returns:
Z-score. Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
- OpenTimeSeries.target_weight_from_var(target_vol=0.175, level=0.95, min_leverage_local=0.0, max_leverage_local=99999.0, months_from_last=None, from_date=None, to_date=None, interpolation='lower', periods_in_a_year_fixed=None, *, drift_adjust=False)
Target weight from VaR.
Computes a position weight multiplier from the ratio between a VaR implied volatility and a given target volatility. Multiplier = 1.0 → target met.
- Parameters:
target_vol (float) – Target volatility.
level (float) – The sought VaR level.
min_leverage_local (float) – Minimum adjustment factor.
max_leverage_local (float) – Maximum adjustment factor.
months_from_last (int | None) – Number of months offset as positive integer. Overrides use of
from_dateandto_date.from_date (dt.date | None) – Specific from date.
to_date (dt.date | None) – Specific to date.
interpolation (LiteralQuantileInterp) – Interpolation type used by
DataFrame.quantile.periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.
drift_adjust (bool) – Adjustment to remove the bias implied by the average return.
self (Self)
- Returns:
Weight multiplier (or implied volatility if used downstream). Float for OpenTimeSeries,
Series[float]for OpenFrame.- Return type:
SeriesOrFloat_co
Visualization
The plotting methods generate fully responsive HTML output that automatically adapts to different screen sizes and device orientations. Plots are optimized for both desktop and mobile viewing with separate title containers and responsive CSS styling.
- OpenTimeSeries.plot_series(mode='lines', title=None, tick_fmt=None, filename=None, directory=None, labels=None, output_type='file', include_plotlyjs='cdn', *, auto_open=True, add_logo=True, show_last=False)
Create a Plotly Scatter Figure.
- Parameters:
mode (LiteralLinePlotMode) – The type of scatter to use.
title (str | None) – A title above the plot.
tick_fmt (str | None) – Tick format for the y-axis, e.g.
'%'or'.1%'.filename (str | None) – Name of the Plotly HTML file.
directory (DirectoryPath | None) – Directory where the Plotly HTML file is saved.
labels (list[str] | None) – Labels to override the column names of
self.tsdf.output_type (LiteralPlotlyOutput) – Determines output type.
include_plotlyjs (LiteralPlotlyJSlib) – How the plotly.js library is included.
auto_open (bool) – Whether to open a browser window with the plot.
add_logo (bool) – If True, a Captor logo is added to the plot.
show_last (bool) – If True, highlight the last point in red with a label.
self (Self)
- Returns:
A tuple
(figure, output)whereoutputis either a div string or a file path.- Return type:
- OpenTimeSeries.plot_bars(mode='group', title=None, tick_fmt=None, filename=None, directory=None, labels=None, output_type='file', include_plotlyjs='cdn', *, auto_open=True, add_logo=True)
Create a Plotly Bar Figure.
- Parameters:
mode (LiteralBarPlotMode) – The type of bar to use.
title (str | None) – A title above the plot.
tick_fmt (str | None) – Tick format for the y-axis, e.g.
'%'or'.1%'.filename (str | None) – Name of the Plotly HTML file.
directory (DirectoryPath | None) – Directory where the Plotly HTML file is saved.
labels (list[str] | None) – Labels to override the column names of
self.tsdf.output_type (LiteralPlotlyOutput) – Determines output type.
include_plotlyjs (LiteralPlotlyJSlib) – How the plotly.js library is included.
auto_open (bool) – Whether to open a browser window with the plot.
add_logo (bool) – If True, a Captor logo is added to the plot.
self (Self)
- Returns:
A tuple
(figure, output)whereoutputis either a div string or a file path.- Return type:
- OpenTimeSeries.plot_histogram(plot_type='bars', histnorm='probability', barmode='overlay', xbins_size=None, opacity=0.75, bargap=0.0, bargroupgap=0.0, curve_type='kde', title=None, x_fmt=None, y_fmt=None, filename=None, directory=None, labels=None, output_type='file', include_plotlyjs='cdn', *, cumulative=False, show_rug=False, auto_open=True, add_logo=True)
Create a Plotly Histogram Figure.
- Parameters:
plot_type (LiteralPlotlyHistogramPlotType) – Type of plot,
"bars"or"lines".histnorm (LiteralPlotlyHistogramHistNorm) – Normalization mode.
barmode (LiteralPlotlyHistogramBarMode) – How bar traces are displayed relative to one another.
xbins_size (float | None) – Width of each bin along the x-axis in data units.
opacity (float) – Trace opacity between 0 and 1.
bargap (float) – Gap between bars of adjacent location coordinates.
bargroupgap (float) – Gap between bar groups at the same location coordinate.
curve_type (LiteralPlotlyHistogramCurveType) – Type of distribution curve to overlay on the histogram.
title (str | None) – A title above the plot.
x_fmt (str | None) – Tick format for the x-axis.
y_fmt (str | None) – Tick format for the y-axis.
filename (str | None) – Name of the Plotly HTML file.
directory (DirectoryPath | None) – Directory where the Plotly HTML file is saved.
labels (list[str] | None) – Labels to override the column names of
self.tsdf.output_type (LiteralPlotlyOutput) – Determines output type.
include_plotlyjs (LiteralPlotlyJSlib) – How the plotly.js library is included.
cumulative (bool) – Whether to compute a cumulative histogram.
show_rug (bool) – Whether to draw a rug plot alongside the distribution.
auto_open (bool) – Whether to open a browser window with the plot.
add_logo (bool) – If True, a Captor logo is added to the plot.
self (Self)
- Returns:
A tuple
(figure, output)whereoutputis either a div string or a file path.- Return type:
Export Methods
- OpenTimeSeries.to_json(what_output, filename, directory=None)
Dump timeseries data into a JSON file.
- Parameters:
what_output (LiteralJsonOutput) – Whether to export raw values or
tsdfvalues.filename (str) – Filename including extension.
directory (DirectoryPath | None) – Folder where the file will be written.
self (Self)
- Returns:
A list of dictionaries with the data of the series.
- Return type:
list[dict[str, str | bool | ValueType | list[str] | list[float]]]
- OpenTimeSeries.to_xlsx(filename, sheet_title=None, directory=None, *, overwrite=True)
Save
.tsdfDataFrame to an Excel spreadsheet file.- Parameters:
- Returns:
The Excel file path.
- Raises:
NameError – If
filenamedoes not end with.xlsx.FileExistsError – If the file exists and
overwriteis False.
- Return type:
Utility Functions
- openseries.timeseries_chain(front, back, old_fee=0.0)[source]
Chain two timeseries together.
The function assumes that the two series have at least one date in common.
- Parameters:
front (TypeOpenTimeSeries) – Earlier series to chain with.
back (TypeOpenTimeSeries) – Later series to chain with.
old_fee (float) – Fee to apply to earlier series. Defaults to 0.0.
- Returns:
An OpenTimeSeries object or a subclass thereof.
- Return type:
TypeOpenTimeSeries