網站首頁 編程語言 正文
二次移動平均法邏輯
二次移動平均法是一種重要的數學工具,用于處理時間序列數據,它的主要目的是通過平滑序列中的噪音數據來更好地捕捉趨勢。
具體實現:
- 計算第一個二次移動平均數,這通常是簡單移動平均數(SMA)。
- 使用以下公式計算每個時間步的二次移動平均數:
EMAt?=α×yt?+(1?α)×EMAt?1?
其中EMAt表示時間步t的二次移動平均數,yt表示時間步t的數據點,α表示權重系數,它一般設置為2/(n+1),其中n表示窗口長度。
Python代碼實現
下面是一個用 python 實現的二次移動平均法的代碼示例:
def ema(data, window):
alpha = 2 / (window + 1)
ema = [data[0]]
for i in range(1, len(data)):
ema.append(alpha * data[i] + (1 - alpha) * ema[-1])
return ema
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
window = 5
ema_data = ema(data, window)
print(ema_data)
運行代碼,得到如下輸出。
第二種實現二次移動平均法的方式
另一種寫法是直接使用 NumPy 的函數 numpy.convolve() 實現二次移動平均法。具體如下:
import numpy as np
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
window = 5
def double_moving_average(data, window=2):
return np.convolve(data, np.ones(window) / window, 'valid')
ema_data = double_moving_average(data, window)
print(ema_data)
這里的 data 變量表示輸入的數據, window 變量表示窗口大小,這個代碼實現了二次移動平均法的功能,可以得到移動平均值數組。
第三種卷積實現二次移動平均法
第三種方法是使用卷積,在 Python 中可以使用 Numpy 實現:
import numpy as np
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
window = 5
def moving_average_2(data, window=3):
cumsum_vec = np.cumsum(np.insert(data, 0, 0))
ma = (cumsum_vec[window:] - cumsum_vec[:-window]) / window
return np.concatenate((np.zeros(window - 1), ma))
ema_data = moving_average_2(data, window)
print(ema_data)
這種方法將二次移動平均法轉化為卷積的形式,使用 cumsum() 函數計算前綴和,然后通過切片的方式計算窗口內的平均值。
二次移動平均法的應用場景
數據平滑:可以通過二次移動平均法對時間序列數據進行平滑處理,去除其中的噪音和瞬時干擾。
趨勢分析:可以通過對數據進行二次移動平均法處理,得到數據的趨勢信息,用于趨勢分析和預測。
市場分析:在股市分析中,二次移動平均法常被用于分析股票價格的趨勢,判斷買賣信號。
去除季節性:二次移動平均法可以用于去除季節性對數據的影響。
原文鏈接:https://blog.csdn.net/hihell/article/details/128834635
相關推薦
- 2022-05-02 C/C++的文件IO函數你知道嗎_C 語言
- 2021-12-06 ASP.NET?Core使用固定窗口限流_實用技巧
- 2022-10-13 Windows命令批處理的用法詳解_DOS/BAT
- 2023-07-07 @Autowired 注解有什么用?@Qualifier 注解有什么用? @RequestMappi
- 2022-10-01 使用301永久重定向和302臨時重定向作用區別詳解_相關技巧
- 2022-06-08 FreeRTOS任務控制API函數的功能分析_操作系統
- 2022-11-29 Redis五大常用數據結構-string、list、set、hash、zset(筆記)
- 2021-12-06 Ubuntu編譯內核模塊,內容體現系統日志中_Linux
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支