Skip to content

Instantly share code, notes, and snippets.

@FerusAndBeyond
Last active April 21, 2022 20:18
Show Gist options
  • Save FerusAndBeyond/adbf196469f0f35506994ee2761f12c3 to your computer and use it in GitHub Desktop.
Save FerusAndBeyond/adbf196469f0f35506994ee2761f12c3 to your computer and use it in GitHub Desktop.
Cross-correlation part 1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Generate two series that are correlated
original_x = pd.Series(np.random.uniform(size=100))
original_y = 1.3*original_x + np.random.normal(0, 0.1, size=100)
# Now create shifted versions,
# I create two examples, one where x is shifted
# and one where y is.
shifted_versions = [
(original_x.iloc[10:].reset_index(drop=True), original_y),
(original_x, original_y.iloc[20:].reset_index(drop=True)),
]
# Function to calculate correlation
def correlation(x, y):
shortest = min(x.shape[0], y.shape[0])
return np.corrcoef(x.iloc[:shortest].values, y.iloc[:shortest].values)[0, 1]
# Function to plot time series and show the correlation
def plot_correlation(x, y, text):
# plot
plt.subplots(figsize=(10, 6))
x.plot(label="x")
y.plot(label="y")
plt.title(f"Correlation {text}: {correlation(x, y)}")
plt.legend(loc="best")
plt.show()
# Show results without shifting
for x, y in shifted_versions:
plot_correlation(x, y, "before shifting")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment