-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempCodeRunnerFile.python
More file actions
59 lines (49 loc) · 1.61 KB
/
tempCodeRunnerFile.python
File metadata and controls
59 lines (49 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import numpy as np
import matplotlib.pyplot as plt
# 假设我们有某只股票的日线收盘价数据
# 这里用随机数据模拟
np.random.seed(1)
N = 250 # 一年的数据
initial_price = 10 # 初始价格
price_changes = np.random.randn(N) # 每日价格变化
stock_prices = initial_price + np.cumsum(price_changes) # 模拟股票价格
stock_prices = np.maximum(stock_prices, 0) # 确保价格不为负
# 绘制原始时序图
plt.figure(figsize=(10, 6))
plt.subplot(3, 1, 1)
plt.plot(stock_prices)
plt.title('Stock Prices Time Series')
plt.xlabel('Day')
plt.ylabel('Price')
plt.grid()
# 进行FFT
fft_result = np.fft.fft(stock_prices)
fft_freqs = np.fft.fftfreq(N, 1) # 采样间隔d=1天
# 计算幅度谱
amplitude_spectrum = np.abs(fft_result) / N
# 绘制频谱图
plt.subplot(3, 1, 2)
plt.plot(fft_freqs, amplitude_spectrum)
plt.title('Frequency Spectrum of Stock Prices')
plt.xlabel('Frequency (cycles per day)')
plt.ylabel('Amplitude')
plt.grid()
# 提取周期为30天的频率分量
period = 30
frequency = 1 / period
index = np.argmin(np.abs(fft_freqs - frequency))
# 创建一个新的FFT结果,只保留周期为30天的频率分量
filtered_fft_result = np.zeros_like(fft_result)
filtered_fft_result[index] = fft_result[index]
filtered_fft_result[-index] = fft_result[-index] # 对称频率分量
# 进行逆FFT得到时域曲线
filtered_stock_prices = np.fft.ifft(filtered_fft_result).real
# 绘制提取的时域曲线
plt.subplot(3, 1, 3)
plt.plot(filtered_stock_prices)
plt.title('Extracted 30-Day Period Time Series')
plt.xlabel('Day')
plt.ylabel('Price')
plt.grid()
plt.tight_layout()
plt.show()