Analyze signals that are a function of time to identify trends, cycles, or other patterns.
Auto-correlation Functions
Cross-correlation
ARIMA Models (using statsmodels library)
Assistant
Python
Advanced Signal Processing
Time-Series Analysis
Analyzing time-series data is crucial in various fields, including finance, engineering, meteorology, and more. Time-series analysis involves techniques to understand the underlying structure and function that produced the observations. This includes identifying trends, cycles, and patterns to make forecasts or detect anomalies.
In this guide, we'll cover:
Auto-correlation Functions
Cross-correlation
ARIMA Models (using the statsmodels library)
Auto-correlation Functions
Auto-correlation measures the correlation of a signal with a delayed version of itself over varying intervals (lags). It helps in identifying repeating patterns or periodic signals obscured by noise.
Example:
python
import numpy as np
import matplotlib.pyplot as plt
from pandas.plotting import autocorrelation_plot
import pandas as pd
# Generate a sample time series with a trend and seasonality
np.random.seed(42)
time = np.arange(0, 100)
trend = time * 0.1
seasonality = 2 * np.sin(2 * np.pi * time / 10)
noise = np.random.normal(0, 1, 100)
signal = trend + seasonality + noise
# Plot the time series
plt.figure(figsize=(12, 4))
plt.plot(time, signal)
plt.title('Sample Time Series')
plt.xlabel('Time')
plt.ylabel('Signal')
plt.show()
# Plot the autocorrelation
plt.figure(figsize=(12, 4))
autocorrelation_plot(pd.Series(signal))
plt.title('Auto-correlation Plot')
plt.show()
Explanation:
Signal Generation: We create a synthetic time series combining a linear trend, a sinusoidal seasonality component, and random noise.
Autocorrelation Plot: The autocorrelation_plot from pandas.plotting visualizes the autocorrelation of the time series at different lags.
Interpretation: Significant peaks at specific lags indicate the presence of periodicity or seasonality in the data.
Cross-correlation
Cross-correlation measures the similarity between two time series as a function of the lag of one relative to the other. It's useful for finding time delays between signals or identifying whether one signal is leading or lagging another.
Example:
python
import numpy as np
import matplotlib.pyplot as plt
# Generate two related signals
np.random.seed(42)
time = np.arange(0, 100)
signal1 = np.sin(2 * np.pi * time / 10) + np.random.normal(0, 0.5, 100)
# Introduce a lag in signal2
lag = 3
signal2 = np.roll(signal1, lag) + np.random.normal(0, 0.2, 100)
# Plot both signals
plt.figure(figsize=(12, 4))
plt.plot(time, signal1, label='Signal 1')
plt.plot(time, signal2, label='Signal 2 (Lagged)')
plt.title('Two Related Signals')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.legend()
plt.show()
# Compute cross-correlation
def cross_correlation(a, b):
result = np.correlate(a - np.mean(a), b - np.mean(b), mode='full')
return result / (np.std(a) * np.std(b) * len(a))
lags = np.arange(-len(signal1) + 1, len(signal1))
corr = cross_correlation(signal1, signal2)
# Plot cross-correlation
plt.figure(figsize=(12, 4))
plt.plot(lags, corr)
plt.title('Cross-correlation between Signal 1 and Signal 2')
plt.xlabel('Lag')
plt.ylabel('Cross-correlation')
plt.show()
# Find the lag with the highest cross-correlation
max_corr_index = np.argmax(corr)
max_corr_lag = lags[max_corr_index]
print(f'Maximum cross-correlation at lag {max_corr_lag}')
Explanation:
Signal Generation: signal2 is a lagged version of signal1, with added noise.
Cross-Correlation Function: We compute the cross-correlation using np.correlate. The function is normalized to produce the correlation coefficient.
Interpretation: The lag at which the cross-correlation is maximum indicates the time delay between the two signals.
ARIMA Models (using statsmodels library)
ARIMA (AutoRegressive Integrated Moving Average) models are a class of statistical models for analyzing and forecasting time series data. ARIMA models capture standard temporal structures in time series data, providing a baseline for more complex analyses.
Components of ARIMA:
AR (p): Autoregression – regression of the variable against itself at prior time steps.
I (d): Integration – differencing of raw observations to make the time series stationary.
MA (q): Moving Average – modeling the error term as a linear combination of error terms occurring contemporaneously and at various times in the past.
Installation:
If you don't have statsmodels installed, you can install it via pip:
bash
pip install statsmodels
Example:
python
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from sklearn.metrics import mean_squared_error
# Generate a non-stationary time series (e.g., random walk)
np.random.seed(42)
n = 200
noise = np.random.normal(0, 1, n)
signal = np.cumsum(noise) # Random walk
# Plot the time series
plt.figure(figsize=(12, 4))
plt.plot(signal)
plt.title('Non-Stationary Time Series (Random Walk)')
plt.xlabel('Time')
plt.ylabel('Value')
plt.show()
# Differencing to achieve stationarity
diff_signal = np.diff(signal)
# Plot ACF and PACF
fig, axes = plt.subplots(1, 2, figsize=(15, 4))
plot_acf(diff_signal, lags=30, ax=axes[0])
axes[0].set_title('ACF of Differenced Series')
plot_pacf(diff_signal, lags=30, ax=axes[1])
axes[1].set_title('PACF of Differenced Series')
plt.show()
# Split into training and testing sets
train_size = int(len(signal) * 0.8)
train, test = signal[:train_size], signal[train_size:]
# Build and fit ARIMA model
model = ARIMA(train, order=(1, 1, 1)) # p=1, d=1, q=1
model_fit = model.fit()
# Forecast
forecast = model_fit.forecast(steps=len(test))
# Evaluate forecast
mse = mean_squared_error(test, forecast)
print(f'Mean Squared Error of forecast: {mse:.3f}')
# Plot forecast vs actual
plt.figure(figsize=(12, 4))
plt.plot(np.arange(len(train)), train, label='Training Data')
plt.plot(np.arange(len(train), len(train) + len(test)), test, label='Actual Data')
plt.plot(np.arange(len(train), len(train) + len(test)), forecast, label='Forecasted Data')
plt.title('ARIMA Model Forecast')
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend()
plt.show()
# Print model summary
print(model_fit.summary())
Explanation:
Data Preparation: We simulate a non-stationary time series using a random walk.
Making Data Stationary: Differencing the series (d=1) transforms it into a stationary series suitable for ARIMA modeling.
Model Selection: ACF and PACF plots help determine the autoregressive (p) and moving average (q) components.
Model Fitting: The ARIMA model is fitted to the training data.
Forecasting: The model forecasts future values, which we compare against the test set.
Evaluation: We compute the Mean Squared Error (MSE) to quantify the forecast accuracy.
Key Concepts:
Stationarity: A stationary time series has a constant mean and variance over time. Stationarity is essential for many time-series models.
Differencing: A technique to transform a non-stationary time series into a stationary one by subtracting the previous observation.
ACF (Autocorrelation Function): Shows the correlation of the time series with its own lagged values.
PACF (Partial Autocorrelation Function): Shows the correlation of the residuals with lagged values after removing contributions from intermediate lags.
Additional Tips
Model Diagnostics: Always perform residual diagnostics to check if the model assumptions hold (e.g., residuals are white noise).
Parameter Selection: Use techniques like the Akaike Information Criterion (AIC) or Bayesian Information Criterion (BIC) to select the best model parameters.
Seasonality: If the data exhibits seasonality, consider using SARIMA models (Seasonal ARIMA).
Time-series analysis is a powerful tool in signal processing for understanding and forecasting temporal data. Python provides a rich set of libraries and functions to perform sophisticated analyses, from auto-correlation and cross-correlation to building complex ARIMA models. By leveraging these tools, you can uncover hidden patterns in your data and make informed predictions.
Feel free to ask if you need further assistance or have questions on specific aspects of time-series analysis!