pyform package

Submodules

pyform.returnseries module

class pyform.returnseries.CashSeries(series, name: Optional[str] = None)

Bases: pyform.returnseries.ReturnSeries

classmethod constant(annualized_return: Optional[Union[float, int]] = 0, start: Optional[str] = '1980-01-01', end: Optional[str] = '2029-12-31')

Creates a constant cash daily returns stream

Parameters

annualized_return – Annualized return of the cash, in decimals. i.e. 1% annual cash return will be entered as annualized_return=0.01. Defaults to 0.

Returns

constant return cash stream

Return type

pyform.CashSeries

classmethod read_fred_libor_1m()

Creates one month libor daily returns from fred data

Returns

one month libor daily returns

Return type

pyform.CashSeries

class pyform.returnseries.ReturnSeries(series, name: Optional[str] = None)

Bases: pyform.timeseries.TimeSeries

A return series that’s datetime indexed and has one column of returns data

add_bm(benchmark: pyform.returnseries.ReturnSeries, name: Optional[str] = None)

Adds a benchmark for the return series.

A benchmark is useful and needed in order to calculate:

  • ‘correlation’: is the correlation between the return series and

    the benchmark

  • ‘beta’: is the CAPM beta between the return series and the benchmark

Parameters
  • benchmark – A benchmark. Should be a ReturnSeries object.

  • name – name of the benchmark. This will be used to display results. Defaults to “None”, which will use the column name of the benchmark.

add_rf(risk_free: pyform.returnseries.ReturnSeries, name: Optional[str] = None)

Adds a risk free rate for the return series.

A risk free rate is useful and needed in order to calculate:

  • ‘sharpe ratio’

Parameters
  • risk_free – A risk free rate. Should be a ReturnSeries object.

  • name – name of the risk free rate. This will be used to display results. Defaults to “None”, which will use the column name of the risk free rate.

get_ann_ret(method: Optional[str] = 'geometric', include_bm: Optional[bool] = True, meta: Optional[bool] = False)

Computes annualized return of the series

Parameters
  • method – method to use when compounding return. Defaults to “geometric”.

  • include_bm – whether to compute annualized return for benchmarks as well. Defaults to True.

  • meta

    whether to include meta data in output. Defaults to False. Available meta are:

    • method: method used to compound annualized return

    • start: start date for calculating annualized return

    • end: end date for calculating annualized return

Returns

annualized return results with the following columns

  • name: name of the series

  • field: name of the field. In this case, it is ‘annualized return’

    for all

  • value: annualized return value, in decimals

Data described in meta will also be available in the returned DataFrame if meta is set to True.

Return type

pd.DataFrame

get_ann_vol(freq: Optional[str] = 'M', include_bm: Optional[bool] = True, method: Optional[str] = 'sample', compound_method: Optional[str] = 'geometric', meta: Optional[bool] = False) → pandas.core.frame.DataFrame

Computes annualized volatility of the series

Parameters
  • freq – Returns are converted to the same frequency before volatility is compuated. Defaults to “M”.

  • include_bm – whether to compute annualized volatility for benchmarks as well. Defaults to True.

  • method – {‘sample’, ‘population’}. method used to compute volatility (standard deviation). Defaults to “sample”.

  • compound_method – method to use when compounding return. Defaults to “geometric”.

  • meta

    whether to include meta data in output. Defaults to False. Available meta are:

    • freq: frequency of the series

    • method: method used to compute annualized volatility

    • start: start date for calculating annualized volatility

    • end: end date for calculating annualized volatility

Returns

annualized volatility results with the following columns

  • name: name of the series

  • field: name of the field. In this case, it is ‘annualized volatility’

    for all

  • value: annualized volatility value, in decimals

Data described in meta will also be available in the returned DataFrame if meta is set to True.

Return type

pd.DataFrame

get_corr(freq: Optional[str] = 'M', method: Optional[str] = 'pearson', compound_method: Optional[str] = 'geometric', meta: Optional[bool] = False) → pandas.core.frame.DataFrame

Calculates correlation of the return series with its benchmarks

Parameters
  • freq – Returns are converted to the same frequency before correlation is compuated. Defaults to “M”.

  • method

    {‘pearson’, ‘kendall’, ‘spearman’}. Defaults to “pearson”.

    • pearson : standard correlation coefficient

    • kendall : Kendall Tau correlation coefficient

    • spearman : Spearman rank correlation

  • compound_method – {‘geometric’, ‘arithmetic’, ‘continuous’}. Defaults to “geometric”.

  • meta

    whether to include meta data in output. Defaults to False. Available meta are:

    • freq: frequency used to compute correlation

    • method: method used to compute correlation

    • start: start date for calculating correlation

    • end: end date for calculating correlation

    • total: total number of data points in returns series

    • skipped: number of data points skipped when computing correlation

Raises

ValueError – when no benchmark is set

Returns

correlation results with the following columns

  • benchmark: name of the benchmark

  • field: name of the field. In this case, it is ‘correlation’ for all

  • value: correlation value

Data described in meta will also be available in the returned DataFrame if meta is set to True.

Return type

pd.DataFrame

get_index_series(freq: Optional[str] = 'M', method: Optional[str] = 'geometric', include_bm: Optional[bool] = True) → Dict[str, pandas.core.frame.DataFrame]
get_rolling_ann_ret(window: Optional[int] = 36, freq: Optional[str] = 'M', method: Optional[str] = 'geometric', include_bm: Optional[bool] = True) → Dict[str, pandas.core.frame.DataFrame]

Computes rolling annualized returns of the series

Parameters
  • window – the rolling window. Defaults to 36.

  • freq – Returns are converted to the same frequency before annualized return is compuated. Defaults to “M”.

  • compound_method – method to use when compounding return to desired frequency. Defaults to “geometric”.

  • include_bm – whether to compute rolling annualized returns for benchmarks as well. Defaults to True.

Returns

dictionary of rolling annualized returns

  • key: name of the series

  • value: rolling annualized returns, in a datetime indexed pandas

    dataframe

Return type

Dict[pd.DataFrame]

get_rolling_ann_vol(window: Optional[int] = 36, freq: Optional[str] = 'M', method: Optional[str] = 'sample', include_bm: Optional[bool] = True, compound_method: Optional[str] = 'geometric') → Dict[str, pandas.core.frame.DataFrame]

Computes rolling volatility (standard deviation) of the series

Parameters
  • window – the rolling window. Defaults to 36.

  • freq – Returns are converted to the same frequency before volatility is compuated. Defaults to “M”.

  • method – {‘sample’, ‘population’}. method used to compute volatility (standard deviation). Defaults to “sample”.

  • include_bm – whether to compute rolling volatility for benchmarks as well. Defaults to True.

  • compound_method – method to use when compounding return. Defaults to “geometric”.

Returns

dictionary of rolling annualized volatilities

  • key: name of the series

  • value: rolling annualized volatilities, in a datetime indexed

    pandas dataframe

Return type

Dict[pd.DataFrame]

get_rolling_tot_ret(window: Optional[int] = 36, freq: Optional[str] = 'M', include_bm: Optional[bool] = True, method: Optional[str] = 'geometric') → Dict[str, pandas.core.frame.DataFrame]

Computes rolling total return of the series

Parameters
  • window – the rolling window. Defaults to 36.

  • freq – frequency of the series. Defaults to “M”.

  • include_bm – whether to compute rolling total return for benchmarks as well. Defaults to True.

  • method – method to use when compounding total return. Defaults to “geometric”.

Returns

dictionary of rolling total returns

  • key: name of the series

  • value: rolling total returns, in a datetime indexed pandas dataframe

Return type

Dict[pd.DataFrame]

get_sharpe(freq: Optional[str] = 'M', risk_free: Optional[Union[float, int, str]] = 0, include_bm: Optional[bool] = True, compound_method: Optional[str] = 'geometric', meta: Optional[bool] = False) → pandas.core.frame.DataFrame

Computes Sharpe ratio of the series

Parameters
  • freq – Returns are converted to the same frequency before Sharpe ratio is compuated. Defaults to “M”.

  • risk_free – the risk free rate to use. Can be a float or a string. If is float, use the value as annualized risk free return. Should be given in decimals. i.e. 1% annual cash return will be entered as annualized_return=0.01. If is string, look for the corresponding DataFrame of risk free rate in self.risk_free. self.risk_free can be set via the add_rf() class method. Defaults to 0.

  • include_bm – whether to compute Sharpe ratio for benchmarks as well. Defaults to True.

  • compound_method – method to use when compounding return. Defaults to “geometric”.

  • meta

    whether to include meta data in output. Defaults to False. Available meta are:

    • freq: frequency of the series

    • risk_free: the risk free rate used

    • start: start date for calculating Sharpe ratio

    • end: end date for calculating Sharpe ratio

Returns

Sharpe ratio with the following columns

  • names: name of the series

  • field: name of the field. In this case, it is ‘Sharpe ratio’

    for all

  • value: Shapre ratio value

Data described in meta will also be available in the returned DataFrame if meta is set to True.

Return type

pd.DataFrame

get_tot_ret(include_bm: Optional[bool] = True, method: Optional[str] = 'geometric', meta: Optional[bool] = False) → pandas.core.frame.DataFrame

Computes total return of the series

Parameters
  • include_bm – whether to compute total return for benchmarks as well. Defaults to True.

  • method – method to use when compounding total return. Defaults to “geometric”.

  • meta

    whether to include meta data in output. Defaults to False. Available meta are:

    • method: method used to compound total return

    • start: start date for calculating total return

    • end: end date for calculating total return

Returns

total return results with the following columns

  • name: name of the series

  • field: name of the field. In this case, it is ‘total return’ for all

  • value: total return value, in decimals

Data described in meta will also be available in the returned DataFrame if meta is set to True.

Return type

pd.DataFrame

to_month(method: Optional[str] = 'geometric') → pandas.core.frame.DataFrame

Converts return series to monthly frequency.

Parameters

method – compounding method. Defaults to “geometric”.

Returns

return series, in monthly frequency

Return type

pd.DataFrame

to_period(freq: str, method: str) → pandas.core.frame.DataFrame

Converts return series to a different (and lower) frequency.

Parameters
  • freq – frequency to convert the return series to. Available options can be found here.

  • method

    compounding method when converting to lower frequency.

    • ’geometric’: geometric compounding (1+r1) * (1+r2) - 1

    • ’arithmetic’: arithmetic compounding r1 + r2

    • ’continuous’: continous compounding exp(r1+r2) - 1

Returns

return series in desired frequency

Return type

pd.DataFrame

to_quarter(method: Optional[str] = 'geometric') → pandas.core.frame.DataFrame

Converts return series to quarterly frequency.

Parameters

method – compounding method. Defaults to “geometric”.

Returns

return series, in quarterly frequency

Return type

pd.DataFrame

to_week(method: Optional[str] = 'geometric') → pandas.core.frame.DataFrame

Converts return series to weekly frequency.

Parameters

method – compounding method. Defaults to “geometric”.

Returns

return series, in weekly frequency

Return type

pd.DataFrame

to_year(method: Optional[str] = 'geometric') → pandas.core.frame.DataFrame

Converts return series to annual frequency.

Parameters

method – compounding method. Defaults to “geometric”.

Returns

return series, in annual frequency

Return type

pd.DataFrame

pyform.timeseries module

class pyform.timeseries.TimeSeries(df: pandas.core.frame.DataFrame)

Bases: object

TimeSeries is a representation of a form of data that changes with time.

For a timeseries object, time index should be unique, meaning it would only accept a “wide” dataframe and not a “long” dataframe.

Args:

df: a dataframe with datetime index, or a ‘date’/’datetime’ column

align_daterange(series: pyform.timeseries.TimeSeries)

Aligns daterange of the incoming series with the main series

Parameters

series – series’ to align daterange for

classmethod read_csv(path: str)

Creates a time series object from a csv file

Parameters

path – path to the csv file

Returns

a TimeSeries object

Return type

pyform.TimeSeries

classmethod read_db(query: str)
classmethod read_excel(path: str, sheet_name: Union[str, int] = 0)

Creates a time series object from a Excel file

Note

using this method requires additional dependency openpyxl

Parameters
  • path – path to the Excel file

  • sheet_name – the index or name of the sheet to read in. Defaults to 0.

Returns

a TimeSeries object

Return type

pyform.TimeSeries

reset()

Resets TimeSeries to its initial state

set_daterange(start: Optional[str] = None, end: Optional[str] = None)

Sets the period of the series we are interested in.

Parameters
  • start – the start date, in YYYY-MM-DD HH:MM:SS, hour is optional. Defaults to None.

  • end – the end date, in YYYY-MM-DD HH:MM:SS, hour is optional. Defaults to None.

Module contents