0


使用递归图 recurrence plot 表征时间序列

在本文中,我将展示如何使用递归图 Recurrence Plots 来描述不同类型的时间序列。我们将查看具有500个数据点的各种模拟时间序列。我们可以通过可视化时间序列的递归图并将其与其他已知的不同时间序列的递归图进行比较,从而直观地表征时间序列。

递归图

Recurrence Plots(RP)是一种用于可视化和分析时间序列或动态系统的方法。它将时间序列转化为图形化的表示形式,以便分析时间序列中的重复模式和结构。Recurrence Plots 是非常有用的,尤其是在时间序列数据中存在周期性、重复事件或关联结构时。

Recurrence Plots 的基本原理是测量时间序列中各点之间的相似性。如果两个时间点之间的距离小于某个给定的阈值,就会在 Recurrence Plot 中绘制一个点,表示这两个时间点之间存在重复性。这些点在二维平面上组成了一种图像。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. def recurrence_plot(data, threshold=0.1):
  4. """
  5. Generate a recurrence plot from a time series.
  6. :param data: Time series data
  7. :param threshold: Threshold to determine recurrence
  8. :return: Recurrence plot
  9. """
  10. # Calculate the distance matrix
  11. N = len(data)
  12. distance_matrix = np.zeros((N, N))
  13. for i in range(N):
  14. for j in range(N):
  15. distance_matrix[i, j] = np.abs(data[i] - data[j])
  16. # Create the recurrence plot
  17. recurrence_plot = np.where(distance_matrix <= threshold, 1, 0)
  18. return recurrence_plot

上面的代码创建了一个二进制距离矩阵,如果时间序列i和j的值相差在0.1以内(阈值),则它们的值为1,否则为0。得到的矩阵可以看作是一幅图像。

白噪声

接下来我们将可视化白噪声。首先,我们需要创建一系列模拟的白噪声:

  1. # Set a seed for reproducibility
  2. np.random.seed(0)
  3. # Generate 500 data points of white noise
  4. white_noise = np.random.normal(size=500)
  5. # Plot the white noise time series
  6. plt.figure(figsize=(10, 6))
  7. plt.plot(white_noise, label='White Noise')
  8. plt.title('White Noise Time Series')
  9. plt.xlabel('Time')
  10. plt.ylabel('Value')
  11. plt.legend()
  12. plt.grid(True)
  13. plt.show()

递归图为这种白噪声提供了有趣的可视化效果。对于任何一种白噪声,图看起来都是一样的:

  1. # Generate and plot the recurrence plot
  2. recurrence = recurrence_plot(white_noise, threshold=0.1)
  3. plt.figure(figsize=(8, 8))
  4. plt.imshow(recurrence, cmap='binary', origin='lower')
  5. plt.title('Recurrence Plot')
  6. plt.xlabel('Time')
  7. plt.ylabel('Time')
  8. plt.colorbar(label='Recurrence')
  9. plt.show()

可以直观地看到一个嘈杂的过程。可以看到图中对角线总是黑色的。

随机游走

接下来让我们看看随机游走(Random Walk)是什么样子的:

  1. # Generate 500 data points of a random walk
  2. steps = np.random.choice([-1, 1], size=500) # Generate random steps: -1 or 1
  3. random_walk = np.cumsum(steps) # Cumulative sum to generate the random walk
  4. # Plot the random walk time series
  5. plt.figure(figsize=(10, 6))
  6. plt.plot(random_walk, label='Random Walk')
  7. plt.title('Random Walk Time Series')
  8. plt.xlabel('Time')
  9. plt.ylabel('Value')
  10. plt.legend()
  11. plt.grid(True)
  12. plt.show()

  1. # Generate and plot the recurrence plot
  2. recurrence = recurrence_plot(random_walk, threshold=0.1)
  3. plt.figure(figsize=(8, 8))
  4. plt.imshow(recurrence, cmap='binary', origin='lower')
  5. plt.title('Recurrence Plot')
  6. plt.xlabel('Time')
  7. plt.ylabel('Time')
  8. plt.colorbar(label='Recurrence')
  9. plt.show()

SARIMA

SARIMA(4,1,4)(1,0,0,12)的模拟数据

  1. from statsmodels.tsa.statespace.sarimax import SARIMAX
  2. # Define SARIMA parameters
  3. p, d, q = 4, 1, 4 # Non-seasonal order
  4. P, D, Q, s = 1, 0, 0, 12 # Seasonal order
  5. # Simulate data
  6. model = SARIMAX(np.random.randn(100), order=(p, d, q), seasonal_order=(P, D, Q, s), trend='ct')
  7. fit = model.fit(disp=False) # Fit the model to random data to get parameters
  8. simulated_data = fit.simulate(nsimulations=500)
  9. # Plot the simulated time series
  10. plt.figure(figsize=(10, 6))
  11. plt.plot(simulated_data, label=f'SARIMA({p},{d},{q})({P},{D},{Q},{s})')
  12. plt.title('Simulated Time Series from SARIMA Model')
  13. plt.xlabel('Time')
  14. plt.ylabel('Value')
  15. plt.legend()
  16. plt.grid(True)
  17. plt.show()

  1. recurrence = recurrence_plot(simulated_data, threshold=0.1)
  2. plt.figure(figsize=(8, 8))
  3. plt.imshow(recurrence, cmap='binary', origin='lower')
  4. plt.title('Recurrence Plot')
  5. plt.xlabel('Time')
  6. plt.ylabel('Time')
  7. plt.colorbar(label='Recurrence')
  8. plt.show()

混沌的数据

  1. def logistic_map(x, r):
  2. """Logistic map function."""
  3. return r * x * (1 - x)
  4. # Initialize parameters
  5. N = 500 # Number of data points
  6. r = 3.9 # Parameter r, set to a value that causes chaotic behavior
  7. x0 = np.random.rand() # Initial value
  8. # Generate chaotic time series data
  9. chaotic_data = [x0]
  10. for _ in range(1, N):
  11. x_next = logistic_map(chaotic_data[-1], r)
  12. chaotic_data.append(x_next)
  13. # Plot the chaotic time series
  14. plt.figure(figsize=(10, 6))
  15. plt.plot(chaotic_data, label=f'Logistic Map (r={r})')
  16. plt.title('Chaotic Time Series')
  17. plt.xlabel('Time')
  18. plt.ylabel('Value')
  19. plt.legend()
  20. plt.grid(True)
  21. plt.show()

  1. recurrence = recurrence_plot(chaotic_data, threshold=0.1)
  2. plt.figure(figsize=(8, 8))
  3. plt.imshow(recurrence, cmap='binary', origin='lower')
  4. plt.title('Recurrence Plot')
  5. plt.xlabel('Time')
  6. plt.ylabel('Time')
  7. plt.colorbar(label='Recurrence')
  8. plt.show()

标准普尔500指数

作为最后一个例子,让我们看看从2013年10月28日至2023年10月27日的标准普尔500指数真实数据:

  1. import pandas as pd
  2. df = pd.read_csv('standard_and_poors_500_idx.csv', parse_dates=True)
  3. df['Date'] = pd.to_datetime(df['Date'])
  4. df.set_index('Date', inplace = True)
  5. df.drop(columns = ['Open', 'High', 'Low'], inplace = True)
  6. df.plot()
  7. plt.title('S&P 500 Index - 10/28/2013 to 10/27/2023')
  8. plt.ylabel('S&P 500 Index')
  9. plt.xlabel('Date');

  1. recurrence = recurrence_plot(df['Close/Last'], threshold=10)
  2. plt.figure(figsize=(8, 8))
  3. plt.imshow(recurrence, cmap='binary', origin='lower')
  4. plt.title('Recurrence Plot')
  5. plt.xlabel('Time')
  6. plt.ylabel('Time')
  7. plt.colorbar(label='Recurrence')
  8. plt.show()

选择合适的相似性阈值是 递归图分析的一个关键步骤。较小的阈值会导致更多的重复模式,而较大的阈值会导致更少的重复模式。阈值的选择通常需要根据数据的特性和分析目标进行调整。

这里我们不得不调整阈值,最终确得到的结果为10,这样可以获得更大的对比度。上面的递归图看起来很像随机游走递归图和无规则的混沌数据的混合体。

总结

在本文中,我们介绍了递归图以及如何使用Python创建递归图。递归图给了我们一种直观表征时间序列图的方法。递归图是一种强大的工具,用于揭示时间序列中的结构和模式,特别适用于那些具有周期性、重复性或复杂结构的数据。通过可视化和特征提取,研究人员可以更好地理解时间序列数据并进行进一步的分析。

从递归图中可以提取各种特征,以用于进一步的分析。这些特征可以包括重复点的分布、Lempel-Ziv复杂度、最长对角线长度等。

递归图在多个领域中得到了广泛应用,包括时间序列分析、振动分析、地震学、生态学、金融分析、生物医学等。它可用于检测周期性、异常事件、相位同步等。

作者:Sam Erickson

“使用递归图 recurrence plot 表征时间序列”的评论:

还没有评论