openseries.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:
- __init__(constituents, weights=None)[source]
OpenFrame objects hold OpenTimeSeries in the list constituents.
The intended use is to allow comparisons across these timeseries.
Methods
__init__(constituents[, weights])OpenFrame objects hold OpenTimeSeries in the list constituents.
add_timeseries(new_series)To add an OpenTimeSeries object.
align_index_to_local_cdays([countries, ...])Align the index of
.tsdfwith local calendar business days.all_properties([properties])Calculate chosen timeseries properties.
arithmetic_ret_func([months_from_last, ...])Annualized arithmetic mean of returns.
beta(asset, market[, dlta_degr_freedms])Market Beta.
calc_range([months_offset, from_dt, to_dt])Create a user-defined date range aligned to index.
capture_ratio_func(ratio[, base_column, ...])Capture Ratio.
construct([_fields_set])copy(*[, include, exclude, update, deep])Returns a copy of the model.
cvar_down_func([level, months_from_last, ...])Downside Conditional Value At Risk (CVaR).
delete_timeseries(lvl_zero_item)To delete an OpenTimeSeries object.
dict(*[, include, exclude, by_alias, ...])ewma_risk([lmbda, day_chunk, ...])Exponentially Weighted Moving Average Volatilities and Correlation.
from_deepcopy()Create copy of the OpenFrame object.
from_orm(obj)geo_ret_func([months_from_last, from_date, ...])Compounded Annual Growth Rate (CAGR).
info_ratio_func([base_column, ...])Information Ratio.
jensen_alpha(asset, market[, riskfree_rate, ...])Jensen's alpha.
json(*[, include, exclude, by_alias, ...])kurtosis_func([months_from_last, from_date, ...])Kurtosis of the return distribution.
lower_partial_moment_func([...])Lower partial moment and downside deviation (order=2).
make_portfolio(name[, weight_strat])Calculate a basket timeseries based on the supplied weights.
max_drawdown_func([months_from_last, ...])Maximum drawdown without any limit on date range.
merge_series([how])Merge index of Pandas Dataframes of the constituent OpenTimeSeries.
model_construct([_fields_set])Creates a new instance of the Model class with validated data.
model_copy(*[, update, deep])!!! abstract "Usage Documentation"
model_dump(*[, mode, include, exclude, ...])!!! abstract "Usage Documentation"
model_dump_json(*[, indent, ensure_ascii, ...])!!! abstract "Usage Documentation"
model_json_schema([by_alias, ref_template, ...])Generates a JSON schema for a model class.
model_parametrized_name(params)Compute the class name for parametrizations of generic classes.
model_post_init(context, /)Override this method to perform additional initialization after __init__ and model_construct.
model_rebuild(*[, force, raise_errors, ...])Try to rebuild the pydantic-core schema for the model.
model_validate(obj, *[, strict, extra, ...])Validate a pydantic model instance.
model_validate_json(json_data, *[, strict, ...])!!! abstract "Usage Documentation"
model_validate_strings(obj, *[, strict, ...])Validate the given object with string data against the Pydantic model.
multi_factor_linear_regression(dependent_column)Perform a multi-factor linear regression.
omega_ratio_func([min_accepted_return, ...])Omega Ratio.
ord_least_squares_fit(y_column, x_column, *)Ordinary Least Squares fit.
outliers([threshold, months_from_last, ...])Detect outliers using z-score analysis.
parse_file(path, *[, content_type, ...])parse_obj(obj)parse_raw(b, *[, content_type, encoding, ...])plot_bars([mode, title, tick_fmt, filename, ...])Create a Plotly Bar Figure.
plot_histogram([plot_type, histnorm, ...])Create a Plotly Histogram Figure.
plot_series([mode, title, tick_fmt, ...])Create a Plotly Scatter Figure.
positive_share_func([months_from_last, ...])Share of percentage changes greater than zero.
rebalanced_portfolio(name[, items, ...])Create a rebalanced portfolio from the OpenFrame constituents.
relative([long_column, short_column, base_zero])Calculate cumulative relative return between two series.
resample([freq])Resample the timeseries frequency.
resample_to_business_period_ends([freq, method])Resamples timeseries frequency to the business calendar month end dates.
ret_vol_ratio_func([riskfree_rate, ...])Ratio between arithmetic mean of returns and annualized volatility.
return_nan_handle([method])Handle missing values in a return series.
rolling_beta([asset_column, market_column, ...])Calculate rolling Market Beta.
rolling_corr([first_column, second_column, ...])Calculate rolling Correlation.
rolling_cvar_down([column, level, observations])Calculate rolling annualized downside CVaR.
rolling_info_ratio([long_column, ...])Calculate rolling Information Ratio.
rolling_return([column, observations])Calculate rolling returns.
rolling_var_down([column, level, ...])Calculate rolling annualized downside Value At Risk (VaR).
rolling_vol([column, observations, ...])Calculate rolling annualized volatilities.
schema([by_alias, ref_template])schema_json(*[, by_alias, ref_template])skew_func([months_from_last, from_date, to_date])Skew of the return distribution.
sortino_ratio_func([riskfree_rate, ...])Sortino ratio or Kappa-3 ratio.
target_weight_from_var([target_vol, level, ...])Target weight from VaR.
to_cumret()Convert series of returns into cumulative series of values.
to_drawdown_series()Convert timeseries into a drawdown series.
to_json(what_output, filename[, directory])Dump timeseries data into a JSON file.
to_xlsx(filename[, sheet_title, directory, ...])Save
.tsdfDataFrame to an Excel spreadsheet file.tracking_error_func([base_column, ...])Tracking Error.
trunc_frame([start_cut, end_cut, where])Truncate DataFrame such that all timeseries have the same time span.
update_forward_refs(**localns)validate(value)value_nan_handle([method])Handle missing values in a value series.
value_ret_calendar_period(year[, month])Calculate simple return for a specific calendar period.
value_ret_func([months_from_last, ...])Calculate simple return.
value_to_diff([periods])Convert series of values to series of their period differences.
value_to_log()Convert value series to log-weighted series.
value_to_ret()Convert series of values into series of returns.
var_down_func([level, months_from_last, ...])Downside Value At Risk (VaR).
vol_from_var_func([level, months_from_last, ...])Implied annualized volatility from downside VaR.
vol_func([months_from_last, from_date, ...])Annualized volatility.
worst_func([observations, months_from_last, ...])Most negative percentage change over a rolling window.
z_score_func([months_from_last, from_date, ...])Z-score of the last return.
Attributes
arithmetic_retAnnualized arithmetic mean of returns.
columns_lvl_oneLevel 1 values of the MultiIndex columns in the .tsdf DataFrame.
columns_lvl_zeroLevel 0 values of the MultiIndex columns in the .tsdf DataFrame.
correl_matrixCorrelation matrix.
cvar_downDownside 95% Conditional Value At Risk "CVaR".
downside_deviationDownside Deviation.
first_idxThe first date in the timeseries.
first_indicesThe first dates in the timeseries of all constituents.
geo_retCompounded Annual Growth Rate (CAGR).
item_countNumber of constituents.
kappa3_ratioKappa-3 ratio.
kurtosisKurtosis of the return distribution.
last_idxThe last date in the timeseries.
last_indicesThe last dates in the timeseries of all constituents.
lengthNumber of observations.
lengths_of_itemsNumber of observations of all constituents.
max_drawdownMaximum drawdown without any limit on date range.
max_drawdown_cal_yearMaximum drawdown in a single calendar year.
max_drawdown_dateDate when the maximum drawdown occurred.
model_computed_fieldsmodel_configConfiguration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
model_extraGet extra fields set during validation.
model_fieldsmodel_fields_setReturns the set of fields that have been explicitly set on this model instance.
omega_ratioOmega ratio.
periods_in_a_yearThe average number of observations per year.
positive_shareThe share of percentage changes that are greater than zero.
ret_vol_ratioRatio of annualized arithmetic mean of returns and annualized volatility.
skewSkew of the return distribution.
sortino_ratioSortino ratio.
span_of_daysNumber of days from the first date to the last.
span_of_days_allNumber of days from the first date to the last for all items in the frame.
value_retSimple return.
var_downDownside 95% Value At Risk (VaR).
volAnnualized volatility.
vol_from_varImplied annualized volatility from Downside 95% Value at Risk.
worstMost negative percentage change.
worst_monthMost negative month.
yearfracLength of series in years assuming 365.25 days per year.
z_scoreZ-score.
constituentstsdfweights- constituents: list[OpenTimeSeries]
- tsdf: DataFrame
- __init__(constituents, weights=None)[source]
OpenFrame objects hold OpenTimeSeries in the list constituents.
The intended use is to allow comparisons across these timeseries.
- from_deepcopy()[source]
Create copy of the OpenFrame object.
- merge_series(how='outer')[source]
Merge index of Pandas Dataframes of the constituent OpenTimeSeries.
- 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:
- 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.
- 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.
- resample(freq='BME')[source]
Resample 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 OpenFrame object.
- Return type:
- 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.
- delete_timeseries(lvl_zero_item)[source]
To delete an OpenTimeSeries object.
- 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:
- 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:
- Returns:
Beta as Co-variance of x & y divided by Variance of x.
- Return type:
- 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:
- 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:
- make_portfolio(name, weight_strat=None)[source]
Calculate a basket timeseries based on the supplied weights.
- 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:
- 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:
- 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:
- 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:
- 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