visualize cross-correlation with statsmodels ccf and multiple lags

Viewed 89

I want to cross-correlate my dependent y with some lagged independent x and plot that correlation (exactly like I can plot with plot_acf):

correlate(y(t), x1(t-1))
correlate(y(t), x1(t-2))
correlate(y(t), x1(t-3))
correlate(y(t), x2(t-1))
correlate(y(t), x2(t-2))
correlate(y(t), x2(t-3))
...

This is my function in python:

def ccf(y, x, lag, axx, axy, title):
    ccs = smt.ccf(y, x)[:lag]
    nlags = len(ccs)
    conf_level = 0.05
    xlabel = np.arange(len(ccs))
    acf_value = ccs
    acf_interval = conf_level
    axs[axx,axy].hlines(y=0, xmin=np.min(xlabel)-2, xmax=np.max(xlabel)+2, linewidth=0.5)
    axs[axx,axy].scatter(x=xlabel, y=acf_value)
    axs[axx,axy].set_ylim(-0.25, 0.25)
    axs[axx,axy].vlines(x=xlabel, ymin=0, ymax=acf_value, linewidth=0.5)
    axs[axx,axy].fill_between(x=xlabel, y1=-conf_level, y2=conf_level, alpha=0.25, linewidth=0, color='C0')
    axs[axx,axy].set_title(title)

Sources: https://setscholars.net/python-data-visualisation-for-business-analyst-how-to-do-cross-correlation-plot-in-python/ https://programmer.ink/think/reproduction-of-acf-and-pacf-in-python.html

fig, axs = plt.subplots(14, 2, figsize=(25, 50))
...
ccf(df['_unr__Faulty'],  df['DriveCabinetTemp'], 40, 13, 0, "CCF: DriveCabinetTemp")
ccf(df['_unr__Faulty'],  df['DriveCabinetHumidity'], 40, 13, 1, "CCF: DriveCabinetHumidity")
plt.tight_layout()
plt.show()

It looks promising: enter image description here

But I can't figure out from the documentation if this is the correct way to do. https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.ccf.html

Is the order of x and y for ccf() correct? And is it correlate(y(t), x1(t-1)), correlate(y(t), x1(t-2)) and not something like correlate(y(t-1), x1(t-1)), correlate(y(t-2), x1(t-2)).

0 Answers
Related