I need to apply the coint function from the statsmodels library to 207 times series with 1397 points each, two by two.
Currently, it takes between 35-40 minutes on my computer with an Intel 24 Cores CPU, last generation.
I tried to use Cython, or Data processing hacks from this article but I get the exact same processing time.
Here is the code to reproduce it:
# Data generation (no improvement needed)
df_timeseries = pd.DataFrame(np.random.uniform(low=2.25, high=2784.07,size=(1397, 207)))
# Downcasting to float 16 (could be unsigned too)
df_timeseries[df_timeseries.columns] = df_timeseries[df_timeseries.columns].astype(np.float16)
The cointegration function requires two time series, so I build a permutation of time series data frame column names:
from more_itertools import distinct_permutations as idp
# Shape: 42642 rows, 2 columns
df_permut = pd.DataFrame(idp(df_timeseries.columns, 2), columns=['ts1', 'ts2'])
Then, I apply the coint
function to the permutation dataframe and extract only the p-value
from the return (coint function returns coint_t, pvalue, crit_value
):
import statsmodels.tsa.stattools as st
df_permut["pvalue"] = df_permut.apply(
lambda x:
[*st.coint(
df_timeseries[x['ts1']].values,
df_timeseries[x['ts2']].values
)][1], axis=1)
This last part takes about 40 mins to run. I know that statsmodels is quite optimized and there is no chance I can imporved the coint
method (I did try by extracting the code and removing the numerous unwanted check, but the linear regression runs from statsmodels take most of the time)
I don't believe there is many places for improvements on my code as the coint method is the most resource greedy.
How to drastically improve the speed? If there is no way, is that a path to move the coint method to GPU?