OpenFrame

class openseries.OpenFrame(constituents, weights=None)[source]

Bases: _CommonModel[Series]

OpenFrame objects hold OpenTimeSeries in the list constituents.

The intended use is to allow comparisons across these timeseries.

Parameters:
  • constituents (list[OpenTimeSeries]) – List of objects of Class OpenTimeSeries.

  • weights (list[float] | None) – List of weights in float format. Optional.

constituents: list[OpenTimeSeries]
tsdf: DataFrame
weights: list[float] | None
__init__(constituents, weights=None)[source]

OpenFrame objects hold OpenTimeSeries in the list constituents.

The intended use is to allow comparisons across these timeseries.

Parameters:
  • constituents (list[OpenTimeSeries]) – List of objects of Class OpenTimeSeries.

  • weights (list[float] | None) – List of weights in float format. Optional.

  • self (Self)

Return type:

None

from_deepcopy()[source]

Create copy of the OpenFrame object.

Returns:

An OpenFrame object.

Parameters:

self (Self)

Return type:

Self

merge_series(how='outer')[source]

Merge index of Pandas Dataframes of the constituent OpenTimeSeries.

Parameters:
  • how (Literal['outer', 'inner']) – The Pandas merge method. Defaults to “outer”.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

all_properties(properties=None)[source]

Calculate chosen timeseries 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', 'max_drawdown_date', 'max_drawdown_cal_year', 'first_indices', 'last_indices', 'lengths_of_items', 'span_of_days_all']] | None) – The properties to calculate. Defaults to calculating all available. Optional.

  • self (Self)

Returns:

Properties of the constituent OpenTimeSeries.

Return type:

DataFrame

property lengths_of_items: Series[int]

Number of observations of all constituents.

Returns:

Number of observations of all constituents.

property item_count: int

Number of constituents.

Returns:

Number of constituents.

property columns_lvl_zero: list[str]

Level 0 values of the MultiIndex columns in the .tsdf DataFrame.

Returns:

Level 0 values of the MultiIndex columns in the .tsdf DataFrame.

property columns_lvl_one: list[ValueType]

Level 1 values of the MultiIndex columns in the .tsdf DataFrame.

Returns:

Level 1 values of the MultiIndex columns in the .tsdf DataFrame.

property first_indices: Series[dt.date]

The first dates in the timeseries of all constituents.

Returns:

The first dates in the timeseries of all constituents.

property last_indices: Series[dt.date]

The last dates in the timeseries of all constituents.

Returns:

The last dates in the timeseries of all constituents.

property span_of_days_all: Series[int]

Number of days from the first date to the last for all items in the frame.

Returns:

Number of days from the first date to the last for all items in the frame.

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 OpenFrame object.

Return type:

Self

to_cumret()[source]

Convert series of returns into cumulative series of values.

Returns:

An OpenFrame object.

Parameters:

self (Self)

Return type:

Self

resample(freq='BME')[source]

Resample 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 OpenFrame 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 OpenFrame object.

Return type:

Self

ewma_risk(lmbda=0.94, day_chunk=11, dlta_degr_freedms=0, first_column=0, second_column=1, corr_scale=2.0, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Exponentially Weighted Moving Average Volatilities and Correlation.

Exponentially Weighted Moving Average (EWMA) for Volatilities and Correlation.

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.

  • first_column (int) – Column of first timeseries. Defaults to 0.

  • second_column (int) – Column of second timeseries. Defaults to 1.

  • corr_scale (float) – Correlation scale factor. Defaults to 2.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 volatilities and correlation.

Return type:

DataFrame

property correl_matrix: DataFrame

Correlation matrix.

This property returns the correlation matrix of the time series in the frame.

Returns:

Correlation matrix of the time series in the frame.

add_timeseries(new_series)[source]

To add an OpenTimeSeries object.

Parameters:
  • new_series (OpenTimeSeries) – The timeseries to add.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

delete_timeseries(lvl_zero_item)[source]

To delete an OpenTimeSeries object.

Parameters:
  • lvl_zero_item (str) – The .tsdf column level 0 value of the timeseries to delete.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

trunc_frame(start_cut=None, end_cut=None, where='both')[source]

Truncate DataFrame such that all timeseries have the same time span.

Parameters:
  • start_cut (dt.date | None) – New first date. Optional.

  • end_cut (dt.date | None) – New last date. Optional.

  • where (LiteralTrunc) – Determines where dataframe is truncated also when start_cut or end_cut is None. Defaults to both.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

relative(long_column=0, short_column=1, *, base_zero=True)[source]

Calculate cumulative relative return between two series.

Parameters:
  • long_column (int) – Column number of timeseries bought. Defaults to 0.

  • short_column (int) – Column number of timeseries sold. Defaults to 1.

  • base_zero (bool) – If set to False 1.0 is added to allow for a capital base and to allow a volatility calculation. Defaults to True.

  • self (Self)

Return type:

None

tracking_error_func(base_column=-1, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Tracking Error.

Calculates Tracking Error which is the standard deviation of the difference between the fund and its index returns.

Reference: https://www.investopedia.com/terms/t/trackingerror.asp.

Parameters:
  • base_column (tuple[str, ValueType] | int) – Column of timeseries that is the denominator in the ratio. Defaults to -1.

  • 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:

Tracking Errors.

Return type:

Series[float]

info_ratio_func(base_column=-1, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Information Ratio.

The Information Ratio equals ( fund return less index return ) divided by the Tracking Error. And the Tracking Error is the standard deviation of the difference between the fund and its index returns. The ratio is calculated using the annualized arithmetic mean of returns.

Parameters:
  • base_column (tuple[str, ValueType] | int) – Column of timeseries that is the denominator in the ratio. Defaults to -1.

  • 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:

Information Ratios.

Return type:

Series[float]

capture_ratio_func(ratio, base_column=-1, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Capture Ratio.

The Up (Down) Capture Ratio is calculated by dividing the CAGR of the asset during periods that the benchmark returns are positive (negative) by the CAGR of the benchmark during the same periods. CaptureRatio.BOTH is the Up ratio divided by the Down ratio. Source: ‘Capture Ratios: A Popular Method of Measuring Portfolio Performance in Practice’, Don R. Cox and Delbert C. Goff, Journal of Economics and Finance Education (Vol 2 Winter 2013).

Reference: https://www.economics-finance.org/jefe/volume12-2/11ArticleCox.pdf.

Parameters:
  • ratio (LiteralCaptureRatio) – The ratio to calculate.

  • base_column (tuple[str, ValueType] | int) – Column of timeseries that is the denominator in the ratio. Defaults to -1.

  • 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:

Capture Ratios.

Return type:

Series[float]

beta(asset, market, dlta_degr_freedms=1)[source]

Market Beta.

Calculates Beta as Co-variance of asset & market divided by Variance of the market.

Reference: https://www.investopedia.com/terms/b/beta.asp.

Parameters:
  • asset (tuple[str, ValueType] | int) – The column of the asset.

  • market (tuple[str, ValueType] | int) – The column of the market against which Beta is measured.

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

  • self (Self)

Returns:

Beta as Co-variance of x & y divided by Variance of x.

Return type:

float

ord_least_squares_fit(y_column, x_column, *, fitted_series=True)[source]

Ordinary Least Squares fit.

Performs a linear regression and adds a new column with a fitted line using Ordinary Least Squares fit.

Parameters:
  • y_column (tuple[str, ValueType] | int) – The column level values of the dependent variable y.

  • x_column (tuple[str, ValueType] | int) – The column level values of the exogenous variable x.

  • fitted_series (bool) – If True the fit is added as a new column in the .tsdf Pandas.DataFrame. Defaults to True.

  • self (Self)

Returns:

A dictionary with the coefficient, intercept and rsquared outputs.

Return type:

dict[str, float]

jensen_alpha(asset, market, riskfree_rate=0.0, dlta_degr_freedms=1)[source]

Jensen’s alpha.

The Jensen’s measure, or Jensen’s alpha, is a risk-adjusted performance measure that represents the average return on a portfolio or investment, above or below that predicted by the capital asset pricing model (CAPM), given the portfolio’s or investment’s beta and the average market return. This metric is also commonly referred to as simply alpha.

Reference: https://www.investopedia.com/terms/j/jensensmeasure.asp.

Parameters:
  • asset (tuple[str, ValueType] | int) – The column of the asset.

  • market (tuple[str, ValueType] | int) – The column of the market against which Jensen’s alpha is measured.

  • riskfree_rate (float) – The return of the zero volatility riskfree asset. Defaults to 0.0.

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

  • self (Self)

Returns:

Jensen’s alpha.

Return type:

float

make_portfolio(name, weight_strat=None)[source]

Calculate a basket timeseries based on the supplied weights.

Parameters:
  • name (str) – Name of the basket timeseries.

  • weight_strat (Literal['eq_weights', 'inv_vol', 'max_div', 'min_vol_overweight'] | None) – Weight calculation strategies. Optional.

  • self (Self)

Returns:

A basket timeseries.

Return type:

DataFrame

rolling_info_ratio(long_column=0, short_column=1, observations=21, periods_in_a_year_fixed=None)[source]

Calculate rolling Information Ratio.

The Information Ratio equals ( fund return less index return ) divided by the Tracking Error. And the Tracking Error is the standard deviation of the difference between the fund and its index returns.

Parameters:
  • long_column (int) – Column of timeseries that is the numerator in the ratio. Defaults to 0.

  • short_column (int) – Column of timeseries that is the denominator in the ratio. Defaults to 1.

  • observations (int) – The length of the rolling window to use is set as number of observations. Defaults to 21.

  • periods_in_a_year_fixed (Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Strict(strict=True), Ge(ge=1), Le(le=366)])] | None) – Allows locking the periods-in-a-year to simplify test cases and comparisons. Optional.

  • self (Self)

Returns:

Rolling Information Ratios.

Return type:

DataFrame

rolling_beta(asset_column=0, market_column=1, observations=21, dlta_degr_freedms=1)[source]

Calculate rolling Market Beta.

Calculates Beta as Co-variance of asset & market divided by Variance of the market.

Reference: https://www.investopedia.com/terms/b/beta.asp.

Parameters:
  • asset_column (int) – Column of timeseries that is the asset. Defaults to 0.

  • market_column (int) – Column of timeseries that is the market. Defaults to 1.

  • observations (int) – The length of the rolling window to use is set as number of observations. Defaults to 21.

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

  • self (Self)

Returns:

Rolling Betas.

Return type:

DataFrame

rolling_corr(first_column=0, second_column=1, observations=21)[source]

Calculate rolling Correlation.

Calculates correlation between two series. The period with at least the given number of observations is the first period calculated.

Parameters:
  • first_column (int) – The position as integer of the first timeseries to compare. Defaults to 0.

  • second_column (int) – The position as integer of the second timeseries to compare. Defaults to 1.

  • observations (int) – The length of the rolling window to use is set as number of observations. Defaults to 21.

  • self (Self)

Returns:

Rolling Correlations.

Return type:

DataFrame

multi_factor_linear_regression(dependent_column)[source]

Perform a multi-factor linear regression.

This function treats one specified column in the DataFrame as the dependent variable (y) and uses all remaining columns as independent variables (X). It utilizes a scikit-learn LinearRegression model and returns a DataFrame with summary output and an OpenTimeSeries of predicted values.

Parameters:
  • dependent_column (tuple[str, ValueType]) – A tuple key to select the column in the OpenFrame.tsdf.columns to use as the dependent variable.

  • self (Self)

Returns:

  • A DataFrame with the R-squared, the intercept and the regression coefficients

  • An OpenTimeSeries of predicted values

Return type:

A tuple containing

Raises:
  • KeyError – If the column tuple is not found in the OpenFrame.tsdf.columns.

  • ValueError – If not all series are returnseries (ValueType.RTRN).

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].

rebalanced_portfolio(name, items=None, bal_weights=None, frequency=1, cash_index=None, *, equal_weights=False, drop_extras=True)[source]

Create a rebalanced portfolio from the OpenFrame constituents.

Parameters:
  • name (str) – Name of the portfolio.

  • items (list[str] | None) – List of items to include in the portfolio. If None, uses all items. Optional.

  • bal_weights (list[float] | None) – List of weights for rebalancing. If None, uses frame weights. Optional.

  • frequency (int) – Rebalancing frequency. Defaults to 1.

  • cash_index (OpenTimeSeries | None) – Cash index series for cash component. Optional.

  • equal_weights (bool) – If True, use equal weights for all items. Defaults to False.

  • drop_extras (bool) – If True, only return TWR series; if False, return all details. Defaults to True.

  • self (Self)

Returns:

OpenFrame containing the rebalanced portfolio.

Return type:

OpenFrame

The OpenFrame class manages collections of OpenTimeSeries objects and provides functionality for:

  • Multi-asset analysis and comparison

  • Portfolio construction and optimization

  • Correlation and regression analysis

  • Risk attribution and factor analysis

  • Batch processing of multiple time series

Class Methods for Construction

OpenFrame.from_deepcopy()[source]

Create copy of the OpenFrame object.

Returns:

An OpenFrame object.

Parameters:

self (Self)

Return type:

Self

Properties

Frame-specific Properties

OpenFrame.constituents: list[OpenTimeSeries]
OpenFrame.columns_lvl_zero

Level 0 values of the MultiIndex columns in the .tsdf DataFrame.

Returns:

Level 0 values of the MultiIndex columns in the .tsdf DataFrame.

OpenFrame.columns_lvl_one

Level 1 values of the MultiIndex columns in the .tsdf DataFrame.

Returns:

Level 1 values of the MultiIndex columns in the .tsdf DataFrame.

OpenFrame.item_count

Number of constituents.

Returns:

Number of constituents.

OpenFrame.weights: list[float] | None
OpenFrame.first_indices

The first dates in the timeseries of all constituents.

Returns:

The first dates in the timeseries of all constituents.

OpenFrame.last_indices

The last dates in the timeseries of all constituents.

Returns:

The last dates in the timeseries of all constituents.

OpenFrame.lengths_of_items

Number of observations of all constituents.

Returns:

Number of observations of all constituents.

OpenFrame.span_of_days_all

Number of days from the first date to the last for all items in the frame.

Returns:

Number of days from the first date to the last for all items in the frame.

Common Properties

OpenFrame.first_idx

The first date in the timeseries.

Returns:

The first date in the timeseries.

OpenFrame.last_idx

The last date in the timeseries.

Returns:

The last date in the timeseries.

OpenFrame.length

Number of observations.

Returns:

Number of observations.

OpenFrame.span_of_days

Number of days from the first date to the last.

Returns:

Number of days from the first date to the last.

OpenFrame.tsdf: DataFrame
OpenFrame.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

OpenFrame.periods_in_a_year

The average number of observations per year.

Returns:

The average number of observations per year.

OpenFrame.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

OpenFrame.all_properties = <function OpenFrame.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', 'max_drawdown_date', 'max_drawdown_cal_year', 'first_indices', 'last_indices', 'lengths_of_items', 'span_of_days_all']] | None)

Return type:

DataFrame

OpenFrame.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.

OpenFrame.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.

OpenFrame.value_ret

Simple return.

Returns:

SeriesOrFloat_co

Simple return. Returns float for OpenTimeSeries, Series[float] for OpenFrame.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.worst

Most negative percentage change.

Returns:

SeriesOrFloat_co

Most negative percentage change. Returns float for OpenTimeSeries, Series[float] for OpenFrame.

OpenFrame.worst_month

Most negative month.

Returns:

SeriesOrFloat_co

Most negative month. Returns float for OpenTimeSeries, Series[float] for OpenFrame.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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.

OpenFrame.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

Frame Management

OpenFrame.merge_series(how='outer')[source]

Merge index of Pandas Dataframes of the constituent OpenTimeSeries.

Parameters:
  • how (Literal['outer', 'inner']) – The Pandas merge method. Defaults to “outer”.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

OpenFrame.trunc_frame(start_cut=None, end_cut=None, where='both')[source]

Truncate DataFrame such that all timeseries have the same time span.

Parameters:
  • start_cut (dt.date | None) – New first date. Optional.

  • end_cut (dt.date | None) – New last date. Optional.

  • where (LiteralTrunc) – Determines where dataframe is truncated also when start_cut or end_cut is None. Defaults to both.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

OpenFrame.add_timeseries(new_series)[source]

To add an OpenTimeSeries object.

Parameters:
  • new_series (OpenTimeSeries) – The timeseries to add.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

OpenFrame.delete_timeseries(lvl_zero_item)[source]

To delete an OpenTimeSeries object.

Parameters:
  • lvl_zero_item (str) – The .tsdf column level 0 value of the timeseries to delete.

  • self (Self)

Returns:

An OpenFrame object.

Return type:

Self

Portfolio Analysis

OpenFrame.relative(long_column=0, short_column=1, *, base_zero=True)[source]

Calculate cumulative relative return between two series.

Parameters:
  • long_column (int) – Column number of timeseries bought. Defaults to 0.

  • short_column (int) – Column number of timeseries sold. Defaults to 1.

  • base_zero (bool) – If set to False 1.0 is added to allow for a capital base and to allow a volatility calculation. Defaults to True.

  • self (Self)

Return type:

None

OpenFrame.make_portfolio(name, weight_strat=None)[source]

Calculate a basket timeseries based on the supplied weights.

Parameters:
  • name (str) – Name of the basket timeseries.

  • weight_strat (Literal['eq_weights', 'inv_vol', 'max_div', 'min_vol_overweight'] | None) – Weight calculation strategies. Optional.

  • self (Self)

Returns:

A basket timeseries.

Return type:

DataFrame

OpenFrame.rebalanced_portfolio(name, items=None, bal_weights=None, frequency=1, cash_index=None, *, equal_weights=False, drop_extras=True)[source]

Create a rebalanced portfolio from the OpenFrame constituents.

Parameters:
  • name (str) – Name of the portfolio.

  • items (list[str] | None) – List of items to include in the portfolio. If None, uses all items. Optional.

  • bal_weights (list[float] | None) – List of weights for rebalancing. If None, uses frame weights. Optional.

  • frequency (int) – Rebalancing frequency. Defaults to 1.

  • cash_index (OpenTimeSeries | None) – Cash index series for cash component. Optional.

  • equal_weights (bool) – If True, use equal weights for all items. Defaults to False.

  • drop_extras (bool) – If True, only return TWR series; if False, return all details. Defaults to True.

  • self (Self)

Returns:

OpenFrame containing the rebalanced portfolio.

Return type:

OpenFrame

Statistical Analysis

OpenFrame.ord_least_squares_fit(y_column, x_column, *, fitted_series=True)[source]

Ordinary Least Squares fit.

Performs a linear regression and adds a new column with a fitted line using Ordinary Least Squares fit.

Parameters:
  • y_column (tuple[str, ValueType] | int) – The column level values of the dependent variable y.

  • x_column (tuple[str, ValueType] | int) – The column level values of the exogenous variable x.

  • fitted_series (bool) – If True the fit is added as a new column in the .tsdf Pandas.DataFrame. Defaults to True.

  • self (Self)

Returns:

A dictionary with the coefficient, intercept and rsquared outputs.

Return type:

dict[str, float]

OpenFrame.beta(asset, market, dlta_degr_freedms=1)[source]

Market Beta.

Calculates Beta as Co-variance of asset & market divided by Variance of the market.

Reference: https://www.investopedia.com/terms/b/beta.asp.

Parameters:
  • asset (tuple[str, ValueType] | int) – The column of the asset.

  • market (tuple[str, ValueType] | int) – The column of the market against which Beta is measured.

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

  • self (Self)

Returns:

Beta as Co-variance of x & y divided by Variance of x.

Return type:

float

OpenFrame.jensen_alpha(asset, market, riskfree_rate=0.0, dlta_degr_freedms=1)[source]

Jensen’s alpha.

The Jensen’s measure, or Jensen’s alpha, is a risk-adjusted performance measure that represents the average return on a portfolio or investment, above or below that predicted by the capital asset pricing model (CAPM), given the portfolio’s or investment’s beta and the average market return. This metric is also commonly referred to as simply alpha.

Reference: https://www.investopedia.com/terms/j/jensensmeasure.asp.

Parameters:
  • asset (tuple[str, ValueType] | int) – The column of the asset.

  • market (tuple[str, ValueType] | int) – The column of the market against which Jensen’s alpha is measured.

  • riskfree_rate (float) – The return of the zero volatility riskfree asset. Defaults to 0.0.

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

  • self (Self)

Returns:

Jensen’s alpha.

Return type:

float

OpenFrame.tracking_error_func(base_column=-1, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Tracking Error.

Calculates Tracking Error which is the standard deviation of the difference between the fund and its index returns.

Reference: https://www.investopedia.com/terms/t/trackingerror.asp.

Parameters:
  • base_column (tuple[str, ValueType] | int) – Column of timeseries that is the denominator in the ratio. Defaults to -1.

  • 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:

Tracking Errors.

Return type:

Series[float]

OpenFrame.info_ratio_func(base_column=-1, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Information Ratio.

The Information Ratio equals ( fund return less index return ) divided by the Tracking Error. And the Tracking Error is the standard deviation of the difference between the fund and its index returns. The ratio is calculated using the annualized arithmetic mean of returns.

Parameters:
  • base_column (tuple[str, ValueType] | int) – Column of timeseries that is the denominator in the ratio. Defaults to -1.

  • 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:

Information Ratios.

Return type:

Series[float]

OpenFrame.capture_ratio_func(ratio, base_column=-1, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Capture Ratio.

The Up (Down) Capture Ratio is calculated by dividing the CAGR of the asset during periods that the benchmark returns are positive (negative) by the CAGR of the benchmark during the same periods. CaptureRatio.BOTH is the Up ratio divided by the Down ratio. Source: ‘Capture Ratios: A Popular Method of Measuring Portfolio Performance in Practice’, Don R. Cox and Delbert C. Goff, Journal of Economics and Finance Education (Vol 2 Winter 2013).

Reference: https://www.economics-finance.org/jefe/volume12-2/11ArticleCox.pdf.

Parameters:
  • ratio (LiteralCaptureRatio) – The ratio to calculate.

  • base_column (tuple[str, ValueType] | int) – Column of timeseries that is the denominator in the ratio. Defaults to -1.

  • 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:

Capture Ratios.

Return type:

Series[float]

OpenFrame.multi_factor_linear_regression(dependent_column)[source]

Perform a multi-factor linear regression.

This function treats one specified column in the DataFrame as the dependent variable (y) and uses all remaining columns as independent variables (X). It utilizes a scikit-learn LinearRegression model and returns a DataFrame with summary output and an OpenTimeSeries of predicted values.

Parameters:
  • dependent_column (tuple[str, ValueType]) – A tuple key to select the column in the OpenFrame.tsdf.columns to use as the dependent variable.

  • self (Self)

Returns:

  • A DataFrame with the R-squared, the intercept and the regression coefficients

  • An OpenTimeSeries of predicted values

Return type:

A tuple containing

Raises:
  • KeyError – If the column tuple is not found in the OpenFrame.tsdf.columns.

  • ValueError – If not all series are returnseries (ValueType.RTRN).

Rolling Analysis

OpenFrame.rolling_info_ratio(long_column=0, short_column=1, observations=21, periods_in_a_year_fixed=None)[source]

Calculate rolling Information Ratio.

The Information Ratio equals ( fund return less index return ) divided by the Tracking Error. And the Tracking Error is the standard deviation of the difference between the fund and its index returns.

Parameters:
  • long_column (int) – Column of timeseries that is the numerator in the ratio. Defaults to 0.

  • short_column (int) – Column of timeseries that is the denominator in the ratio. Defaults to 1.

  • observations (int) – The length of the rolling window to use is set as number of observations. Defaults to 21.

  • periods_in_a_year_fixed (Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Strict(strict=True), Ge(ge=1), Le(le=366)])] | None) – Allows locking the periods-in-a-year to simplify test cases and comparisons. Optional.

  • self (Self)

Returns:

Rolling Information Ratios.

Return type:

DataFrame

OpenFrame.rolling_beta(asset_column=0, market_column=1, observations=21, dlta_degr_freedms=1)[source]

Calculate rolling Market Beta.

Calculates Beta as Co-variance of asset & market divided by Variance of the market.

Reference: https://www.investopedia.com/terms/b/beta.asp.

Parameters:
  • asset_column (int) – Column of timeseries that is the asset. Defaults to 0.

  • market_column (int) – Column of timeseries that is the market. Defaults to 1.

  • observations (int) – The length of the rolling window to use is set as number of observations. Defaults to 21.

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

  • self (Self)

Returns:

Rolling Betas.

Return type:

DataFrame

OpenFrame.rolling_corr(first_column=0, second_column=1, observations=21)[source]

Calculate rolling Correlation.

Calculates correlation between two series. The period with at least the given number of observations is the first period calculated.

Parameters:
  • first_column (int) – The position as integer of the first timeseries to compare. Defaults to 0.

  • second_column (int) – The position as integer of the second timeseries to compare. Defaults to 1.

  • observations (int) – The length of the rolling window to use is set as number of observations. Defaults to 21.

  • self (Self)

Returns:

Rolling Correlations.

Return type:

DataFrame

OpenFrame.rolling_return(column=0, observations=21)

Calculate rolling returns.

Parameters:
  • column (int) – Column position to calculate.

  • observations (int) – Number of observations in the overlapping window.

  • self (Self)

Returns:

DataFrame with rolling returns.

Return type:

DataFrame

OpenFrame.rolling_vol(column=0, observations=21, periods_in_a_year_fixed=None, dlta_degr_freedms=1)

Calculate rolling annualized volatilities.

Parameters:
  • column (int) – Column position to calculate.

  • observations (int) – Number of observations in the overlapping window.

  • periods_in_a_year_fixed (DaysInYearType | None) – Lock periods-in-a-year to simplify tests and comparisons.

  • dlta_degr_freedms (int) – Variance bias factor (0 or 1).

  • self (Self)

Returns:

DataFrame with rolling annualized volatilities.

Return type:

DataFrame

OpenFrame.rolling_var_down(column=0, level=0.95, observations=252, interpolation='lower')

Calculate rolling annualized downside Value At Risk (VaR).

Parameters:
  • column (int) – Column position to calculate.

  • level (float) – Value At Risk level.

  • observations (int) – Number of observations in the overlapping window.

  • interpolation (LiteralQuantileInterp) – Interpolation used by DataFrame.quantile.

  • self (Self)

Returns:

DataFrame with rolling annualized downside VaR.

Return type:

DataFrame

OpenFrame.rolling_cvar_down(column=0, level=0.95, observations=252)

Calculate rolling annualized downside CVaR.

Parameters:
  • column (int) – Column position to calculate.

  • level (float) – Conditional Value At Risk level.

  • observations (int) – Number of observations in the overlapping window.

  • self (Self)

Returns:

DataFrame with rolling annualized downside CVaR.

Return type:

DataFrame

Correlation and Risk

OpenFrame.correl_matrix

Correlation matrix.

This property returns the correlation matrix of the time series in the frame.

Returns:

Correlation matrix of the time series in the frame.

OpenFrame.ewma_risk(lmbda=0.94, day_chunk=11, dlta_degr_freedms=0, first_column=0, second_column=1, corr_scale=2.0, months_from_last=None, from_date=None, to_date=None, periods_in_a_year_fixed=None)[source]

Exponentially Weighted Moving Average Volatilities and Correlation.

Exponentially Weighted Moving Average (EWMA) for Volatilities and Correlation.

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.

  • first_column (int) – Column of first timeseries. Defaults to 0.

  • second_column (int) – Column of second timeseries. Defaults to 1.

  • corr_scale (float) – Correlation scale factor. Defaults to 2.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 volatilities and correlation.

Return type:

DataFrame

Data Manipulation

OpenFrame.align_index_to_local_cdays(countries=None, markets=None, custom_holidays=None, method='nearest')

Align the index of .tsdf with 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

OpenFrame.resample(freq='BME')[source]

Resample 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 OpenFrame object.

Return type:

Self

OpenFrame.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 OpenFrame object.

Return type:

Self

OpenFrame.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

OpenFrame.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

OpenFrame.to_cumret()[source]

Convert series of returns into cumulative series of values.

Returns:

An OpenFrame object.

Parameters:

self (Self)

Return type:

Self

OpenFrame.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

OpenFrame.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 OpenFrame object.

Return type:

Self

OpenFrame.value_to_log()

Convert value series to log-weighted series.

Equivalent to LN(value[t] / value[t=0]) in Excel.

Returns:

The modified object.

Parameters:

self (Self)

Return type:

Self

OpenFrame.to_drawdown_series()

Convert timeseries into a drawdown series.

Returns:

The modified object.

Parameters:

self (Self)

Return type:

Self

OpenFrame.value_ret_calendar_period(year, month=None)

Calculate simple return for a specific calendar period.

Parameters:
  • year (int) – Calendar year of the period to calculate.

  • month (int | None) – Calendar month of the period to calculate.

  • self (Self)

Returns:

Simple return for the period. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

Analysis Methods

OpenFrame.calc_range(months_offset=None, from_dt=None, to_dt=None)

Create a user-defined date range aligned to index.

Parameters:
  • months_offset (int | None) – Number of months offset as a positive integer. Overrides use of from_dt and to_dt.

  • from_dt (date | None) – Specific from date.

  • to_dt (date | None) – Specific to date.

  • self (Self)

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:

tuple[date, date]

OpenFrame.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:
  • threshold (float) – Z-score threshold; values with |z| > threshold are outliers.

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

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

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

  • self (Self)

Returns:

Series of outliers. For OpenFrame: DataFrame of outliers. Empty if none found.

Return type:

For OpenTimeSeries

Financial Metrics Methods

OpenFrame.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_date and to_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

OpenFrame.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:
  • months_from_last (int | None) – Number of months offset as positive integer. Overrides use of from_date and to_date.

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

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

  • self (Self)

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

OpenFrame.value_ret_func(months_from_last=None, from_date=None, to_date=None)

Calculate simple return.

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

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

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

  • self (Self)

Returns:

Simple return. Float for OpenTimeSeries, Series[float] for OpenFrame.

Raises:

InitialValueZeroError – If initial value is zero.

Return type:

SeriesOrFloat_co

OpenFrame.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() (Excel STDEV.S equivalent). 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_date and to_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

OpenFrame.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 order is 2 calculates standard deviation of returns below MAR=0. For general order p, 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_date and to_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 order is 2; otherwise rooted lower partial moment. Float for OpenTimeSeries, Series[float] for OpenFrame.

Raises:

ValueError – If order is not 2 or 3.

Return type:

SeriesOrFloat_co

OpenFrame.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_rate provided, 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_date and to_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

OpenFrame.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 deviation using arithmetic mean of returns. Kappa-3 when order=3 penalizes 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_date and to_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

OpenFrame.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:
  • min_accepted_return (float) – Annualized Minimum Accepted Return (MAR).

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

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

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

  • self (Self)

Returns:

Omega ratio. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.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_date and to_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

OpenFrame.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:
  • level (float) – The sought CVaR level.

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

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

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

  • self (Self)

Returns:

Downside CVaR. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.worst_func(observations=1, months_from_last=None, from_date=None, to_date=None)

Most negative percentage change over a rolling window.

Parameters:
  • observations (int) – Number of observations for the rolling window.

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

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

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

  • self (Self)

Returns:

Most negative percentage change. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.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:
  • months_from_last (int | None) – Number of months offset as positive integer. Overrides use of from_date and to_date.

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

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

  • min_periods (int) – Smallest number of observations for rolling max.

  • self (Self)

Returns:

Maximum drawdown. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.positive_share_func(months_from_last=None, from_date=None, to_date=None)

Share of percentage changes greater than zero.

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

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

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

  • self (Self)

Returns:

Share of positive returns. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.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_date and to_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

OpenFrame.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:
  • months_from_last (int | None) – Number of months offset as positive integer. Overrides use of from_date and to_date.

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

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

  • self (Self)

Returns:

Skewness. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.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:
  • months_from_last (int | None) – Number of months offset as positive integer. Overrides use of from_date and to_date.

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

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

  • self (Self)

Returns:

Kurtosis. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.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:
  • months_from_last (int | None) – Number of months offset as positive integer. Overrides use of from_date and to_date.

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

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

  • self (Self)

Returns:

Z-score. Float for OpenTimeSeries, Series[float] for OpenFrame.

Return type:

SeriesOrFloat_co

OpenFrame.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_date and to_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.

OpenFrame.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) where output is either a div string or a file path.

Return type:

tuple[Figure, str]

OpenFrame.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) where output is either a div string or a file path.

Return type:

tuple[Figure, str]

OpenFrame.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) where output is either a div string or a file path.

Return type:

tuple[Figure, str]

Export Methods

OpenFrame.to_json(what_output, filename, directory=None)

Dump timeseries data into a JSON file.

Parameters:
  • what_output (LiteralJsonOutput) – Whether to export raw values or tsdf values.

  • 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]]]

OpenFrame.to_xlsx(filename, sheet_title=None, directory=None, *, overwrite=True)

Save .tsdf DataFrame to an Excel spreadsheet file.

Parameters:
  • filename (str) – Filename that should include .xlsx.

  • sheet_title (str | None) – Name of the sheet in the Excel file.

  • directory (Annotated[Path, PathType(path_type=dir)] | None) – Directory where the Excel file is saved.

  • overwrite (bool) – Whether to overwrite an existing file.

  • self (Self)

Returns:

The Excel file path.

Raises:
Return type:

str