时间序列的小波滤波器处理(Python)

B站影视 2024-12-18 12:40 11

摘要:pip install PyWaveletsimport pywtimport numpy as npimport matplotlib.pyplot as plt# Step 1: Simulate financial time seriesnp.rando

pip install PyWaveletsimport pywtimport numpy as npimport matplotlib.pyplot as plt# Step 1: Simulate financial time seriesnp.random.seed(42)time = np.linspace(0, 1, 500)financial_data = np.sin(50 * np.pi * time) + np.random.normal(0, 0.5, len(time))# Step 2: Plot the original noisy signalplt.figure(figsize=(12, 6))plt.plot(time, financial_data, label='Noisy Financial Data', color='blue', alpha=0.8)plt.title('Original Noisy Financial Time Series')plt.xlabel('Time')plt.ylabel('Amplitude')plt.legendplt.grid(True)plt.tight_layoutoriginal_signal_path = "original_signal.png"plt.savefig(original_signal_path)plt.show# Step 3: Performwavelet decompositionwavelet = 'db4' # Daubechies waveletcoeffs = pywt.wavedec(financial_data, wavelet, level=3)# Step 4: Visualize wavelet decomposition (coefficients)plt.figure(figsize=(12, 10))# Approximation coefficientsplt.subplot(3, 1, 1)plt.plot(pywt.upcoef('a', coeffs[0], wavelet, level=3), color='green', label='Approximation Coefficients')plt.title('Approximation Coefficients (Low Frequency)')plt.ylabel('Amplitude')plt.legendplt.grid(True)plt.plot(pywt.upcoef('d', coeffs[1], wavelet, level=3), color='red', label='Detail Coefficients Level 1')plt.title('Detail Coefficients - Level 1')plt.ylabel('Amplitude')plt.legendplt.grid(True)# Detail coefficients (Level 2)plt.subplot(3, 1, 3)plt.plot(pywt.upcoef('d', coeffs[2], wavelet, level=2), color='orange', label='Detail Coefficients Level 2')plt.title('Detail Coefficients - Level 2')plt.xlabel('Time')plt.ylabel('Amplitude')plt.legendplt.grid(True)plt.tight_layoutdecomposition_path = "decomposition_coefficients.png"plt.savefig(decomposition_path)plt.show# Step 5: Reconstruct the signal using approximation coefficientsreconstructed_signal = pywt.waverec(coeffs[:1] + [None] * (len(coeffs) - 1), wavelet)# Adjust lengths for visualizationmin_length = min(len(time), len(reconstructed_signal))adjusted_time = time[:min_length]adjusted_original_signal = financial_data[:min_length]adjusted_reconstructed_signal = reconstructed_signal[:min_length]# Step 6: Plot original vs reconstructed signalplt.figure(figsize=(12, 6))plt.plot(adjusted_time, adjusted_original_signal, label='Original Signal', alpha=0.7, color='blue')plt.plot(adjusted_time, adjusted_reconstructed_signal, label='Reconstructed Signal', linestyle='--', alpha=0.9, color='orange')plt.title('Original vs Reconstructed Signal')plt.xlabel('Time')plt.ylabel('Amplitude')plt.legendplt.grid(True)plt.tight_layoutreconstructed_signal_path = "reconstructed_signal.png"plt.savefig(reconstructed_signal_path)plt.show# Print file paths for saved plotsprint(f"Original Signal Plot saved to: {original_signal_path}")print(f"Decomposition Coefficients Plot saved to: {decomposition_path}")print(f"Reconstructed Signal Plot saved to: {reconstructed_signal_path}")Original Signal Plot saved to: original_signal.pngDecomposition Coefficients Plot saved to: decomposition_coefficients.pngReconstructed Signal Plot saved to: reconstructed_signal.pngimport pywtimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt# Step 1: Simulate financial time seriesnp.random.seed(42)time = np.linspace(0, 1, 500)financial_data = np.sin(50 * np.pi * time) + np.random.normal(0, 0.5, len(time))# Plot the original noisy signalplt.figure(figsize=(12, 6))plt.plot(time, financial_data, label='Noisy Financial Data', color='blue', alpha=0.8)plt.title('Original Noisy Financial Time Series')plt.xlabel('Time')plt.ylabel('Amplitude')plt.legendplt.grid(True)plt.tight_layoutplt.show# Step 2: Perform wavelet decompositionwavelet = 'db4' # Daubechies waveletcoeffs = pywt.wavedec(financial_data, wavelet, level=3)# Reconstruct the signal using approximation coefficients (denoised signal)denoised_signal = pywt.waverec(coeffs[:1] + [None] * (len(coeffs) - 1), wavelet)# Convert denoised signal to Pandas Seriesdenoised_signal_series = pd.Series(denoised_signal[:len(time)])# Generate high, low, and close data for the denoised signaldenoised_high = denoised_signal_series + 0.5 * np.random.rand(len(denoised_signal_series))denoised_low = denoised_signal_series - 0.5 * np.random.rand(len(denoised_signal_series))denoised_close = denoised_signal_series# Step 3: Supertrend Calculationdef true_range(high, low, close):return pd.DataFrame({'H-L': high - low,'H-PC': abs(high - close.shift(1)),'L-PC': abs(low - close.shift(1))}).max(axis=1)def average_true_range(high, low, close, period=14):tr = true_range(high, low, close)return tr.rolling(window=period).meandef supertrend(high, low, close, atr_multiplier=3, period=14):atr = average_true_range(high, low, close, period)hl2 = (high + low) / 2 # Median priceupper_band = hl2 + (atr_multiplier * atr)lower_band = hl2 - (atr_multiplier * atr)# Initialize supertrendsupertrend = [True] * len(close) # True = Bullish, False = Bearishfor i in range(1, len(close)):if close[i] > upper_band[i - 1]:supertrend[i] = Trueelif close[i]

知乎学术咨询:

https://www.zhihu.com/consult/people/792359672131756032?isMe=1

担任《Mechanical System and Signal Processing》《中国电机工程学报》等期刊审稿专家,擅长领域:信号滤波/降噪,机器学习/深度学习,时间序列预分析/预测,设备故障诊断/缺陷检测/异常检测。

分割线分割线分割线

基于小波分析的时间序列降噪(Python,ipynb文件)

完整代码:

时间序列的最大重叠离散小波分解(Python)

完整代码:

基于连续小波变换的信号滤波方法(Python,ipynb文件)

不同小波族的优缺点

来源:莉姿教育

相关推荐