P
n
n
S M A_{t}=\frac{P_{1}+P_{2}+\ldots+P_{n}}{n}
SMAt=nP1+P2+…+Pn
比如若依次得到测定值
x
1
、
x
2
、
x
3
、
x
4
、
x
5
、
x
6
、
x
7
.
.
.
x_1、x_2、x_3、x_4、x_5、x_6、x_7…
x1、x2、x3、x4、x5、x6、x7…,按顺序取一定个数所做的全部算术平均值就是移动平均值,如
y
1
=
(
x
1
x
2
x
3
)
/
3
、
y
2
=
(
x
2
x
3
x
4
)
/
3…
y_1=(x_1+x_2+x_3)/3、y_2=(x_2+x_3+x_4)/3…
y1=(x1+x2+x3)/3、y2=(x2+x3+x4)/3…,
而panda提供了rolling函数可以用来计算移动平均,使用简单,速度较快:
DataFrame.rolling(window, min_periods=None, freq=None, center=False, win_type=None, on=None, axis=0, closed=None)
参数 | 用法 |
---|---|
window | 表示时间窗的大小,注意有两种形式(int or offset)。如果使用int,则数值表示计算统计量的观测值的数量即向前几个数据。如果是offset类型,表示时间窗的大小。 |
min_periods | 最少需要有值的观测点的数量,对于int类型,默认与window相等。对于offset类型,默认为1。 |
freq | 不用管,从0.18版本中已经被舍弃。 |
win_type | 窗口类型,不用管,默认为None一般不特殊指定 |
on | 对于DataFrame如果不使用index(索引)作为rolling的列,那么用on来指定使用哪列。 |
closed | 定义区间的开闭,不用管,新版本中已经被舍弃 |
axis | 方向(轴),一般都是0。 |
center | 是否使用window的中间值作为label,默认为false。只能在window是int时使用。 |
那么我们使用的简单移动平均直接使用:data['ma5'] = data['Adj Close'].rolling(5).mean()
,其表示窗口大小为5的移动平均。计算后,使用matplotlib.pyplot进行画图,横轴为时间,竖轴为预测价格,将其在pyplot 图中打印:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(16,9))
ax1 = fig.add_subplot(111, ylabel='Price')
data.ma5.plot(ax=ax1, color='plum', lw=2., legend=True)
效果如下:
我们以同样方法画出多个均线并且和原数据real对比:
data['real'] = data['Adj Close'].rolling(1).mean()
data['ma5'] = data['Adj Close'].rolling(5).mean()
data['ma10'] = data['Adj Close'].rolling(10).mean()
data['ma20'] = data['Adj Close'].rolling(20).mean()
data['ma30'] = data['Adj Close'].rolling(30).mean()
data['ma50'] = data['Adj Close'].rolling(50).mean()
data['ma100'] = data['Adj Close'].rolling(100).mean()
data['ma200'] = data['Adj Close'].rolling(200).mean()
data['ma250'] = data['Adj Close'].rolling(250).mean()
data.tail()
fig = plt.figure(figsize=(16,9))
ax1 = fig.add_subplot(111, ylabel='Price')
data.real.plot(ax=ax1, color='black', lw=2., legend=True)
data.ma5.plot(ax=ax1, color='plum', lw=2., legend=True)
data.ma10.plot(ax=ax1, color='grey', lw=2., legend=True)
data.ma20.plot(ax=ax1, color='salmon', lw=2., legend=True)
data.ma30.plot(ax=ax1, color='goldenrod', lw=2., legend=True)
data.ma50.plot(ax=ax1, color='hotpink', lw=2., legend=True)
data.ma100.plot(ax=ax1, color='khaki', lw=2., legend=True)
data.ma200.plot(ax=ax1, color='bisque', lw=2., legend=True)
data.ma250.plot(ax=ax1, color='skyblue', lw=2., legend=True)
plt.grid()
plt.show()
可以发现,移动平均存在一定的滞后性,移动平均以滞后性的代价换来了平滑性,滞后性说明由简单移动平均计算得到的低频趋势对近期的最新数据不够敏感。没有未来数据便是滞后的根本原因。当股价不是随着趋势的变化方向,发生突发的方向趋势,移动平均线行动往往过于迟缓,改变方向速度落后于大趋势。这是一个极大弱点
在股价原有趋势发生反转时,由于MA的追踪趋势的特性,MA的行动往往过于迟缓,掉头速度落后于大趋势。这是MA的一个极大的弱点。等MA发出反转信号时,股价调头的深度已经很大了。
附录DOW在不同MA值下的滑动平均值:
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
-PG706t3A-1714736152349)]
[外链图片转存中…(img-enkBtrkP-1714736152350)]
[外链图片转存中…(img-tf2QGAqt-1714736152350)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新