Created
April 21, 2022 19:59
-
-
Save FerusAndBeyond/9bf24f128a86fdb3de20a37837e03861 to your computer and use it in GitHub Desktop.
Cross-correlation part2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy.signal import correlate | |
from scipy.signal import correlation_lags | |
# Function to calculate cross-correlation, | |
# extract the best matching shift and then shift | |
# one of the series appropriately. | |
def shift_for_maximum_correlation(x, y): | |
correlation = correlate(x, y, mode="full") | |
lags = correlation_lags(x.size, y.size, mode="full") | |
lag = lags[np.argmax(correlation)] | |
print(f"Best lag: {lag}") | |
if lag < 0: | |
y = y.iloc[abs(lag):].reset_index(drop=True) | |
else: | |
x = x.iloc[lag:].reset_index(drop=True) | |
return x, y | |
# Plot results after shifting | |
for x, y in shifted_versions: | |
shifted_x, shifted_y = shift_for_maximum_correlation(x, y) | |
plot_correlation(shifted_x, shifted_y, text="after shifting") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment