Skip to content

Instantly share code, notes, and snippets.

@Bastien-Brd
Last active September 26, 2016 15:34
Show Gist options
  • Save Bastien-Brd/33a1aaa7657e7130fce659b2836e4b33 to your computer and use it in GitHub Desktop.
Save Bastien-Brd/33a1aaa7657e7130fce659b2836e4b33 to your computer and use it in GitHub Desktop.
import pandas as pd
def rolling_apply_function_of_two_series(func, series1, series2, window=12):
'''
Pandas has a DataFrame.rolling() method, allowing to apply a function of a series/array on a rolling window of the data frame.
However, only functions of one argument (function of one array) are supported.
This is a workaround: allowing to apply a function of two series on a rolling window.
This assumes the two input series have the same index (or at least that the index of series1 overlaps the index of series2)
:param func: A function of two series, returning a scalar
:param series1:
:param series2:
:param window: An integer defining the size of the window.
:return: A series, where each element is the result of 'func' applied to a window of size 'window' of the previous rows of the input series
'''
# Align the series2 (typically a benchmark series) with the index of the series1 (typically the fund series)
# and put them in one data frame of 2 columns
df = pd.concat([series1, series2.reindex(series1.index)], axis=1)
# Add a third column serving as integers index
df['integer_index'] = range(len(df))
# Define a function that calculates the input 'function' over a window defined by an integer,
# taking series1 and series2 values over that window as argument
def func_on_window(ii, df):
x_df = df.iloc[map(int, ii)]
return func(x_df[x_df.columns[0]], x_df[x_df.columns[1]])
# Apply this function on rolling window on the integers column
return df['integer_index'].rolling(window=window, min_periods=window).apply(lambda x: func_on_window(x, df)).fillna(0.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment