Package: openseries
OpenSeriesOpenSeriesis a project with tools to analyse financial timeseries of a single
asset or a group of assets. It is solely made for daily or less frequent data.CHANGELOGBasic UsageTo install:pipinstallopenseriescondainstall-cconda-forgeopenseriesAn example of how to make use of the OpenTimeSeries is shown below. The design
aligns with how we within our fund company's code base have a subclass of the
OpenTimeSeries with class methods for our different data sources. Combined with some
additional tools it allows us to efficiently present investment cases to clients.The code snippet can be pasted into a Python console to run it.
Install openseries and yfinance first.fromopenseries.seriesimportOpenTimeSeriesimportyfinanceasyfmsft=yf.Ticker("MSFT")history=msft.history(period="max")series=OpenTimeSeries.from_df(history.loc[:,"Close"])_=series.value_to_log().set_new_label("Microsoft Log Returns of Close Prices")_,_=series.plot_series()Sample output using the OpenFrame.all_properties() method:Scilla Global Equity C (simulation+fund) Global Low Volatility index, SEK
                                                ValueType.PRICE                  ValueType.PRICE
Total return                                           3.641282                         1.946319
Arithmetic return                                      0.096271                         0.069636
Geometric return                                       0.093057                          0.06464
Volatility                                             0.120279                         0.117866
Return vol ratio                                       0.800396                          0.59081
Downside deviation                                     0.085956                         0.086723
Sortino ratio                                          1.119993                         0.802975
Positive share                                         0.541783                         0.551996
Worst                                                 -0.071616                        -0.089415
Worst month                                           -0.122503                        -0.154485
Max drawdown                                          -0.309849                        -0.435444
Max drawdown in cal yr                                -0.309849                        -0.348681
Max drawdown dates                                   2020-03-23                       2009-03-09
CVaR 95.0%                                             -0.01793                        -0.018429
VaR 95.0%                                             -0.011365                        -0.010807
Imp vol from VaR 95%                                   0.109204                         0.103834
Z-score                                                0.587905                         0.103241
Skew                                                  -0.650782                        -0.888109
Kurtosis                                               8.511166                        17.527367
observations                                               4309                             4309
span of days                                               6301                             6301
first indices                                        2006-01-03                       2006-01-03
last indices                                         2023-04-05                       2023-04-05Usage example on Jupyter NbviewerDevelopment InstructionsThese instructions assume that you have a compatible Python version installed on
your machine and that you are OK to install this project in a virtual environment.The OpenTimeSeries and OpenFrame classes are both subclasses of
thePydantic BaseModel. Please refer to its documentation for information
on any attributes or methods inherited from this model.Windows Powershellgitclonehttps://github.com/CaptorAB/OpenSeries.gitcdOpenSeries./make.ps1makeMac Terminal/Linuxgitclonehttps://github.com/CaptorAB/OpenSeries.gitcdOpenSeries
makesourcesource_me
makeinstallTesting and Linting / Type-checkingRuff and Mypy checking is embedded in the pre-commit hook. Both
are also used in the project's GitHub workflows and are run when thelintalternative is chosen in the below commands.
Any silenced error codes can be found in thepyproject.tomlfile or in in-line comments.Windows Powershell./make.ps1test./make.ps1lintMac Terminal/LinuxmaketestmakelintTable of ContentsBasic UsageDevelopment InstructionsTesting and Linting / Type-checkingOn some files in the projectClass methods used to construct an OpenTimeSeriesOpenTimeSeries non-numerical propertiesOpenFrame non-numerical propertiesNon-numerical properties for both classesOpenTimeSeries only methodsOpenFrame only methodsMethods for both classesNumerical properties for both classesNumerical methods with period arguments for both classesOn some files in the projectFileDescriptionseries.pyDefines the classOpenTimeSeriesfor managing and analyzing a single timeseries. The module also defines a functiontimeseries_chainthat can be used to chain two timeseries objects together.frame.pyDefines the classOpenFramefor managing a group of timeseries, and e.g. calculate a portfolio timeseries from a rebalancing strategy between timeseries.simulation.pyDefines the classReturnSimulationto create simulated financial timeseries. Used in the project's test suiteClass methods used to construct objects.MethodApplies toDescriptionfrom_arraysOpenTimeSeriesClass method to create an OpenTimeSeries object from a list of date strings and a list of values.from_dfOpenTimeSeriesClass method to create an OpenTimeSeries object from a pandas.DataFrame or pandas.Series.from_fixed_rateOpenTimeSeriesClass method to create an OpenTimeSeries object from a fixed rate, number of days and an end date.from_deepcopyOpenTimeSeries,OpenFrameCreates a copy of an OpenTimeSeries object.Non-numerical or "helper" properties that apply only to theOpenTimeSeriesclass.PropertytypeApplies toDescriptiontimeseries_idstrOpenTimeSeriesPlaceholder for database identifier for the timeseries. Can be left as empty string.instrument_idstrOpenTimeSeriesPlaceholder for database identifier for the instrument associated with the timeseries. Can be left as empty string.dateslist[str]OpenTimeSeriesDates of the timeseries. Not edited by any method to allow reversion to original.valueslist[float]OpenTimeSeriesValues of the timeseries. Not edited by any method to allow reversion to original.currencystrOpenTimeSeriesCurrency of the timeseries. Only used if conversion/hedging methods are added.domesticstrOpenTimeSeriesDomestic currency of the user / investor. Only used if conversion/hedging methods are added.local_ccyboolOpenTimeSeriesIndicates if series should be in its local currency or the domestic currency of the user. Only used if conversion/hedging methods are added.namestrOpenTimeSeriesAn identifier field.isinstrOpenTimeSeriesISIN code of the associated instrument. If any.labelstrOpenTimeSeriesField used in outputs. Derived from name as default.countrieslistorstrOpenTimeSeries(List of) country code(s) according to ISO 3166-1 alpha-2 used to generate business days.valuetypeValueTypeOpenTimeSeriesField identifies the type of values in the series. ValueType is an Enum.Non-numerical or "helper" properties that apply only to theOpenFrameclass.PropertytypeApplies toDescriptionconstituentslist[OpenTimeSeries]OpenFrameA list of the OpenTimeSeries that make up an OpenFrame.columns_lvl_zerolistOpenFrameA list of the level zero column names in the OpenFrame pandas.DataFrame.columns_lvl_onelistOpenFrameA list of the level one column names in the OpenFrame pandas.DataFrame.item_countintOpenFrameNumber of columns in the OpenFrame pandas.DataFrame.weightslist[float]OpenFrameWeights used in the methodmake_portfolio.first_indicespandas.SeriesOpenFrameFirst dates of all the series in the OpenFrame.last_indicespandas.SeriesOpenFrameLast dates of all the series in the OpenFrame.lengths_of_itemspandas.SeriesOpenFrameNumber of items in each of the series in the OpenFrame.span_of_days_allpandas.SeriesOpenFrameNumber of days from the first to the last in each of the series.Non-numerical or "helper" properties that apply to both theOpenTimeSeriesand theOpenFrameclass.PropertytypeApplies toDescriptionfirst_idxdatetime.dateOpenTimeSeries,OpenFrameFirst date of the series.last_idxdatetime.dateOpenTimeSeries,OpenFrameLast date of the series.lengthintOpenTimeSeries,OpenFrameNumber of items in the series.span_of_daysintOpenTimeSeries,OpenFrameNumber of days from the first to the last date in the series.tsdfpandas.DataFrameOpenTimeSeries,OpenFrameThe Pandas DataFrame which gets edited by the class methods.max_drawdown_datedatetime.date,pandas.SeriesOpenTimeSeries,OpenFrameDate when the maximum drawdown occurred.periods_in_a_yearfloatOpenTimeSeries,OpenFrameThe number of observations in an average year for all days in the data.yearfracfloatOpenTimeSeries,OpenFrameLength of timeseries expressed as np.float64 fraction of a year with 365.25 days.Methods that apply only to theOpenTimeSeriesclass.MethodApplies toDescriptionsetup_classOpenTimeSeriesClass method that defines thedomestichome currency and thecountrieshome countries attributes.pandas_dfOpenTimeSeriesMethod to create thetsdfpandas.DataFrame from thedatesandvalues.set_new_labelOpenTimeSeriesMethod to change the pandas.DataFrame column MultiIndex.running_adjustmentOpenTimeSeriesAdjusts the series performance with afloatfactor.ewma_vol_funcOpenTimeSeriesReturns apandas.Serieswith volatility based onExponentially Weighted Moving Average.from_1d_rate_to_cumretOpenTimeSeriesConverts a series of 1-day rates into a cumulative valueseries.|Methods that apply only to theOpenFrameclass.MethodApplies toDescriptionmerge_seriesOpenFrameMerges the Pandas Dataframes of the constituent OpenTimeSeries.trunc_frameOpenFrameTruncates the OpenFrame to a common period.add_timeseriesOpenFrameAdds a given OpenTimeSeries to the OpenFrame.delete_timeseriesOpenFrameDeletes an OpenTimeSeries from the OpenFrame.relativeOpenFrameCalculates a new series that is the relative performance of two others.make_portfolioOpenFrameCalculates a portfolio timeseries based on the series and weights. Weights can be provided as a list, or a weight strategy can be chosen fromequal weights,equal risk,inverted volatilityorminimum varianceas defined in theffnpackage.ord_least_squares_fitOpenFramePerforms a regression and anOrdinary Least Squaresfit.betaOpenFrameCalculatesBetaof an asset relative a market.jensen_alphaOpenFrameCalculatesJensen's Alphaof an asset relative a market.tracking_error_funcOpenFrameCalculates thetracking errorsrelative to a selected series in the OpenFrame.info_ratio_funcOpenFrameCalculates theinformation ratiosrelative to a selected series in the OpenFrame.capture_ratio_funcOpenFrameCalculates up, down and up/downcapture ratiosrelative to a selected series.rolling_info_ratioOpenFrameReturns a pandas.DataFrame with the rollinginformation ratiobetween two series.rolling_betaOpenFrameReturns a pandas.DataFrame with the rollingBetaof an asset relative a market.rolling_corrOpenFrameCalculates and adds a series of rollingcorrelationsbetween two other series.ewma_riskOpenFrameReturns apandas.DataFramewith volatility and correlation based onExponentially Weighted Moving Average.Methods that apply to both theOpenTimeSeriesand theOpenFrameclass.MethodApplies toDescriptionalign_index_to_local_cdaysOpenTimeSeries,OpenFrameAligns the series dates to a business calendar. Defaults to Sweden.resampleOpenTimeSeries,OpenFrameResamples the series to a specific frequency.resample_to_business_period_endsOpenTimeSeries,OpenFrameResamples the series to month-end dates with monthly, quarterly or annual frequency.value_nan_handleOpenTimeSeries,OpenFrameFillsNanin a value series with the preceding non-Nan value.return_nan_handleOpenTimeSeries,OpenFrameReplacesNanin a return series with a 0.0float.to_cumretOpenTimeSeries,OpenFrameConverts a return series into a value series and/or resets a value series to be rebased from 1.0.to_jsonOpenTimeSeries,OpenFrameMethod to export the raw unaltered data to a json file.to_xlsxOpenTimeSeries,OpenFrameMethod to save the data in the .tsdf DataFrame to an Excel file.value_to_retOpenTimeSeries,OpenFrameConverts a value series into a percentage return series.value_to_diffOpenTimeSeries,OpenFrameConverts a value series into a series of differences.value_to_logOpenTimeSeries,OpenFrameConverts a value series into a logarithmic return series.value_ret_calendar_periodOpenTimeSeries,OpenFrameReturns the series simple return for a specific calendar period.plot_seriesOpenTimeSeries,OpenFrameOpens a HTMLPlotly Scatterplot of the series in a browser window.plot_barsOpenTimeSeries,OpenFrameOpens a HTMLPlotly Barplot of the series in a browser window.to_drawdown_seriesOpenTimeSeries,OpenFrameConverts the series into drawdown series.rolling_returnOpenTimeSeries,OpenFrameReturns a pandas.DataFrame with rolling returns.rolling_volOpenTimeSeries,OpenFrameReturns a pandas.DataFrame with rolling volatilities.rolling_var_downOpenTimeSeries,OpenFrameReturns a pandas.DataFrame with rolling VaR figures.rolling_cvar_downOpenTimeSeries,OpenFrameReturns a pandas.DataFrame with rolling CVaR figures.calc_rangeOpenTimeSeries,OpenFrameReturns the start and end dates of a range from specific period definitions. Used by the below numerical methods and not meant to be used independently.Numerical properties available for individualOpenTimeSeriesor on all series in anOpenFrame.PropertytypeApplies toDescriptionall_propertiespandas.DataFrameOpenTimeSeries,OpenFrameReturns most of the properties in one go.arithmetic_retfloat,pandas.SeriesOpenTimeSeries,OpenFrameAnnualized arithmetic mean of returns.geo_retfloat,pandas.SeriesOpenTimeSeries,OpenFrameCompound Annual Growth Rate(CAGR), a specific implementation of geometric mean.value_retfloat,pandas.SeriesOpenTimeSeries,OpenFrameSimple return from first to last observation.volfloat,pandas.SeriesOpenTimeSeries,OpenFrameAnnualizedvolatility. Pandas .std() is the equivalent of stdev.s([...]) in MS excel.downside_deviationfloat,pandas.SeriesOpenTimeSeries,OpenFrameDownside deviationis the volatility of all negative return observations. Minimum Accepted Return (MAR) set to zero.ret_vol_ratiofloat,pandas.SeriesOpenTimeSeries,OpenFrameRatio of arithmetic mean return and annualized volatility. It is theSharpe Ratiowith the riskfree rate set to zero.sortino_ratiofloat,pandas.SeriesOpenTimeSeries,OpenFrameTheSortino Ratiois the arithmetic mean return divided by the downside deviation. This attribute assumes that the riskfree rate and the MAR are both zero.var_downfloat,pandas.SeriesOpenTimeSeries,OpenFrameDownside 95%Value At Risk, "VaR". The equivalent of percentile.inc([...], 1-level) over returns in MS Excel. For other confidence levels use the corresponding method.cvar_downfloat,pandas.SeriesOpenTimeSeries,OpenFrameDownside 95%Conditional Value At Risk, "CVaR". For other confidence levels use the corresponding method.worstfloat,pandas.SeriesOpenTimeSeries,OpenFrameMost negative percentage change of a single observation.worst_monthfloat,pandas.SeriesOpenTimeSeries,OpenFrameMost negative month.max_drawdownfloat,pandas.SeriesOpenTimeSeries,OpenFrameMaximum drawdown.max_drawdown_cal_yearfloat,pandas.SeriesOpenTimeSeries,OpenFrameMax drawdown in a single calendar year.positive_sharefloat,pandas.SeriesOpenTimeSeries,OpenFrameThe share of percentage changes that are positive.vol_from_varfloat,pandas.SeriesOpenTimeSeries,OpenFrameImplied annualized volatility from the Downside VaR using the assumption that returns are normally distributed.skewfloat,pandas.SeriesOpenTimeSeries,OpenFrameSkewof the return distribution.kurtosisfloat,pandas.SeriesOpenTimeSeries,OpenFrameKurtosisof the return distribution.z_scorefloat,pandas.SeriesOpenTimeSeries,OpenFrameZ-scoreas (last return - mean return) / standard deviation of returns.correl_matrixpandas.DataFrameOpenFrameA correlation matrix.Methods below are identical to the Numerical Properties above.They are simply methods that take different date or length inputs to return the
properties for subset periods.MethodtypeApplies toDescriptionarithmetic_ret_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameAnnualized arithmetic mean of returns.geo_ret_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameCompound Annual Growth Rate(CAGR), a specific implementation of geometric mean.value_ret_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameSimple return from first to last observation.vol_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameAnnualizedvolatility. Pandas .std() is the equivalent of stdev.s([...]) in MS excel.downside_deviation_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameDownside deviationis the volatility of all negative return observations. MAR and riskfree rate can be set.ret_vol_ratio_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameRatio of arithmetic mean return and annualized volatility. It is theSharpe Ratiowith the riskfree rate set to zero. A riskfree rate can be set as a float or a series chosen for the frame function.sortino_ratio_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameTheSortino Ratiois the arithmetic mean return divided by the downside deviation. A riskfree rate can be set as a float or a series chosen for the frame function. MAR is set to zero.var_down_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameDownside 95%Value At Risk, "VaR". The equivalent of percentile.inc([...], 1-level) over returns in MS Excel. Default is 95% confidence level.cvar_down_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameDownside 95%Conditional Value At Risk, "CVaR". Default is 95% confidence level.worst_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameMost negative percentage change for a given number of observations (default=1).max_drawdown_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameMaximum drawdown.positive_share_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameThe share of percentage changes that are positive.vol_from_var_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameImplied annualized volatility from the Downside VaR using the assumption that returns are normally distributed.skew_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameSkewof the return distribution.kurtosis_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameKurtosisof the return distribution.z_score_funcfloat,pandas.SeriesOpenTimeSeries,OpenFrameZ-scoreas (last return - mean return) / standard deviation of returns.target_weight_from_varfloat,pandas.SeriesOpenTimeSeries,OpenFrameA position target weight from the ratio between a VaR implied volatility and a given target volatility.