TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码

Python计算移动平均值的完整指南:rolling函数详解

2025-07-30
/
0 评论
/
2 阅读
/
正在检测是否收录...
07/30


移动平均值是时间序列分析中最常用的技术指标之一,在股票分析、传感器数据处理、商业趋势预测等领域广泛应用。本文将全面介绍如何使用Python的pandas库中的rolling函数实现各种移动平均计算。

一、移动平均的核心概念

移动平均(Moving Average)通过不断向前移动的窗口计算平均值,能有效消除数据中的随机波动。假设我们有以下股价数据:

python import pandas as pd data = [25.6, 26.8, 25.9, 27.2, 26.5, 28.1, 27.9] dates = pd.date_range('2023-01-01', periods=7) ts = pd.Series(data, index=dates)

二、基础滚动计算

1. 简单移动平均(SMA)

python

计算3日简单移动平均

sma_3 = ts.rolling(window=3).mean()
"""
2023-01-01 NaN
2023-01-02 NaN
2023-01-03 26.10 # (25.6+26.8+25.9)/3
2023-01-04 26.63
...
"""

2. 关键参数解析

  • window:窗口大小,决定计算范围
  • min_periods:最小计算数据量(默认为window值)
  • center:是否居中计算(默认False)
  • win_type:窗口类型(如'boxcar', 'triang'等)

三、高级应用技巧

3. 加权移动平均

python

使用线性衰减权重

weights = [0.1, 0.3, 0.6]
wma = ts.rolling(window=3).apply(lambda x: (x*weights).sum())

4. 指数移动平均(EMA)

python ema = ts.ewm(span=3, adjust=False).mean()

5. 多列数据滚动计算

python df = pd.DataFrame({ 'price': [25.6, 26.8, 25.9, 27.2, 26.5], 'volume': [1200, 1500, 1100, 1800, 1300] }) df.rolling(2).agg({'price':'mean', 'volume':'sum'})

四、实战注意事项

  1. 边界处理问题:可以通过min_periods=1避免初始NaN值
    python ts.rolling(3, min_periods=1).mean()

  2. 性能优化:大数据集建议先df = df.sort_index()

  3. 异常值处理:结合clip()方法限制极端值影响

五、完整案例:股票分析

python

获取雅虎财经数据

import yfinance as yf
aapl = yf.download('AAPL', start='2022-01-01')

计算双均线系统

aapl['MA20'] = aapl['Close'].rolling(20).mean()
aapl['MA60'] = aapl['Close'].rolling(60).mean()

六、常见问题解答

Q:如何计算非等间隔时间序列?
A:使用pd.rolling('2D')这样的时间偏移量

Q:滚动计算比普通循环快多少?
测试显示:10万数据点下,rolling比for循环快约200倍

Q:怎样实现前向滚动?
使用shift()方法:
python ts.shift(1).rolling(3).mean() # 使用未来数据

扩展学习
- 尝试实现Hull移动平均(HMA)
- 学习与卷积运算的结合应用(np.convolve
- 了解如何在PySpark中实现分布式滚动计算

数据处理Python移动平均pandas rolling时间序列平滑金融分析
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/34349/(转载时请注明本文出处及文章链接)

评论 (0)

人生倒计时

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月

最新回复

  1. 强强强
    2025-04-07
  2. jesse
    2025-01-16
  3. sowxkkxwwk
    2024-11-20
  4. zpzscldkea
    2024-11-20
  5. bruvoaaiju
    2024-11-14

标签云