![]() |
VOOZH | about |
Cross-correlation analysis is a powerful technique in signal processing and time series analysis used to measure the similarity between two series at different time lags. It reveals how one series (reference) is correlated with the other (target) when shifted by a specific amount. This information is valuable in various domains, including finance (identifying stock market correlations), neuroscience (analyzing brain activity), and engineering (evaluating system responses).
In this article, we'll explore four methods for performing cross-correlation analysis in Python, providing clear explanations and illustrative examples.
Cross-correlation Analysis in Python
Cross-correlation measures the similarity between two sequences as a function of the displacement of one relative to the other. denoted by for various time or spatial lags where represents the lag between the two datasets. Calculating Cross-correlation analysis in Python helps in:
There are major 4 methods to perform cross-correlation analysis in Python:
To show implementation let's generate an dataset comprising two time series signals, signal1 and signal2, using a combination of sine and cosine functions with added noise. This dataset simulates real-world scenarios where signals often exhibit complex patterns and noise.
In the code, we define two different functions for calculating mean, second cross_correlation fucntion that takes two signals x and y where:
mean(x) and mean(y): Calculates the mean of each signal.sum((a - x_mean) * (b - y_mean) for a, b in zip(x, y)): Calculates the numerator of the cross-correlation formula by summing the product of the differences between corresponding elements of x and y, centered around their means.x_sq_diff and y_sq_diff calculate the sum of squared differences for each signal.math.sqrt(x_sq_diff * y_sq_diff): Calculates the denominator of the cross-correlation formula by taking the square root of the product of the squared differences.Output:
Manual Correlation: 0.9837294963190838NumPy's corrcoef function is utilized to calculate the cross-correlation between signal1 and signal2.
Output:
NumPy Correlation: 0.9796920509627758SciPy's pearsonr function is employed to calculate the cross-correlation between signal1 and signal2. The Pearson correlation coefficient measures the linear relationship between two datasets.
Output:
SciPy Correlation: 0.9865169592702046Statsmodels OLS function is used to calculate the cross-correlation between signal1 and signal2.
Output:
Statsmodels Correlation: 0.9730755677920275 The manual implementation, NumPy, SciPy, and Statsmodels methods all yield correlation coefficients that indicate a strong positive correlation between signal1 and signal2. This underscores the versatility of Python in performing cross-correlation analysis, catering to a wide range of requirements and complexities.