移动平均线是最常见的技术指标,它能够去除时间序列的短期波动,使得数据变得平滑,从而可以方便看出序列的趋势特征。常见的移动平均线有简单移动平均线,加权移动平均线,指数移动平均线。
一. 简单移动平均(SMA)
简单移动平均线(Simple Moving Average),很好理解,就是将过去n个窗口内的价格进行算术平均
S
M
A
t
(
n
)
=
1
n
(
X
t
−
n
+
1
+
X
t
−
n
+
2
+
.
.
.
+
X
t
)
SMA_t(n) = \frac{1}{n}(X_{t-n+1} + X_{t-n+2} + ... + X_t)
SMAt(n)=n1(Xt−n+1+Xt−n+2+...+Xt)
以下是贵州茅台从 2018.6.1 2018.6.1 2018.6.1到 2019.12.31 2019.12.31 2019.12.31收盘价的简单移动平均线。
import pandas as pd
import baostock as bs
import matplotlib.pyplot as plt
def get_data(code, start_date, end_date):
lg = bs.login()
rs = bs.query_history_k_data_plus(code,
"date,code,open,high,low,close,volume",
start_date=start_date, end_date=end_date,
frequency="d", adjustflag="3")
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
result = pd.DataFrame(data_list, columns=rs.fields)
bs.logout()
result['date'] = pd.to_datetime(result['date'])
result['open'] = result['open'].astype(float)
result['high'] = result['high'].astype(float)
result['low'] = result['low'].astype(float)
result['close'] = result['close'].astype(float)
result['volume'] = result['volume'].astype(float)
result.set_index(result['date'], inplace=True)
return result
if __name__ == '__main__':
data = get_data('sh.600519', '2018-06-01', '2019-12-31')
data['SMA10'] = data['close'].rolling(10).mean()
data['SMA20'] = data['close'].rolling(20).mean()
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot()
ax.plot(data.index, data['close'], linestyle='--', label='close')
ax.plot(data.index, data['SMA10'], label='SMA10')
ax.plot(data.index, data['SMA20'], label='SMA20')
ax.legend()
plt.show()
二. 加权移动平均(WMA)
加权移动平均(Weighted Moving Average)在计算平均值时,对最近的数据赋予的权重比历史数据的权重要大。
W
M
A
(
n
)
t
=
n
X
t
+
(
n
−
1
)
X
t
−
1
+
.
.
.
+
2
X
t
−
n
+
2
+
X
t
−
n
+
1
n
+
(
n
−
1
)
+
.
.
.
+
2
+
1
WMA(n)_t = \frac{nX_t + (n-1)X_{t-1} + ... + 2X_{t-n+2} + X_{t-n+1}}{n + (n - 1) + ...+ 2 + 1}
WMA(n)t=n+(n−1)+...+2+1nXt+(n−1)Xt−1+...+2Xt−n+2+Xt−n+1
以下是贵州茅台从 2018.6.1 2018.6.1 2018.6.1到 2019.12.31 2019.12.31 2019.12.31收盘价的加权移动平均线。
import numpy as np
import pandas as pd
import baostock as bs
import matplotlib.pyplot as plt
def get_data(code, start_date, end_date):
lg = bs.login()
rs = bs.query_history_k_data_plus(code,
"date,code,open,high,low,close,volume",
start_date=start_date, end_date=end_date,
frequency="d", adjustflag="3")
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
result = pd.DataFrame(data_list, columns=rs.fields)
bs.logout()
result['date'] = pd.to_datetime(result['date'])
result['open'] = result['open'].astype(float)
result['high'] = result['high'].astype(float)
result['low'] = result['low'].astype(float)
result['close'] = result['close'].astype(float)
result['volume'] = result['volume'].astype(float)
result.set_index(result['date'], inplace=True)
return result
if __name__ == '__main__':
data = get_data('sh.600519', '2018-06-01', '2019-12-31')
n = 10
weights = np.array(range(1, n + 1))
weights_sum = np.sum(weights)
data['WMA10'] = data['close'].rolling(window=n, min_periods=n).apply(lambda x: np.sum(x * weights) / weights_sum)
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot()
ax.plot(data.index, data['close'], linestyle='--', label='close')
ax.plot(data.index, data['WMA10'], label='WMA10')
ax.legend()
plt.show()
三. 指数移动平均(EMA)
指数移动平均(Exponential Moving Average)跟加权移动平均类似,只是它对最近的数据赋予了更高的权重。
E
M
A
t
=
α
X
t
+
(
1
−
α
)
E
M
A
t
−
1
EMA_t = {\alpha}X_t + (1-\alpha)EMA_{t-1}
EMAt=αXt+(1−α)EMAt−1
α
\alpha
α一般取
2
/
(
n
+
1
)
2/(n + 1)
2/(n+1),
n
n
n为数据序列长度,pandas中计算EMA一般可以使用ewm方法。
以下是贵州茅台从 2018.6.1 2018.6.1 2018.6.1到 2019.12.31 2019.12.31 2019.12.31收盘价的指数移动平均线。
import numpy as np
import pandas as pd
import baostock as bs
import matplotlib.pyplot as plt
def get_data(code, start_date, end_date):
lg = bs.login()
rs = bs.query_history_k_data_plus(code,
"date,code,open,high,low,close,volume",
start_date=start_date, end_date=end_date,
frequency="d", adjustflag="3")
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
result = pd.DataFrame(data_list, columns=rs.fields)
bs.logout()
result['date'] = pd.to_datetime(result['date'])
result['open'] = result['open'].astype(float)
result['high'] = result['high'].astype(float)
result['low'] = result['low'].astype(float)
result['close'] = result['close'].astype(float)
result['volume'] = result['volume'].astype(float)
result.set_index(result['date'], inplace=True)
return result
if __name__ == '__main__':
data = get_data('sh.600519', '2018-06-01', '2019-12-31')[['date', 'close']]
data['EMA10'] = data['close'].ewm(span=10, adjust=True).mean()
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot()
ax.plot(data.index, data['close'], linestyle='--', label='close')
ax.plot(data.index, data['EMA10'], label='EMA10')
ax.legend()
plt.show()
四. 对比三种均线
1. 三种均线的权重对比
从权重思维来看,三种方法都可以认为是加权平均。
- SMA:权重系数一致
- WMA:权重系数随时间间隔线性递减
- EMA:权重系数随时间间隔指数递减
下面通过程序展示三种均线的权重系数的递减情况
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
if __name__ == '__main__':
n = 30
# 简单移动平均权重
weight_sma = np.ones(n)
# 加权移动平均
weights_wma = range(1, n + 1)
weights_wma /= np.sum(weights_wma)
weights_wma = weights_wma[::-1]
# 指数移动平均
alpha = 2 / (n + 1)
t = np.array(range(0, n))
weights_ema = alpha * (1 - alpha) ** t
df = pd.DataFrame({"SMA30-Weights": weight_sma, "WMA30-Weights": weights_wma, "EMA30-Weights": weights_ema})
ax = df.plot.bar(subplots=True, figsize=(16, 6), title=['', '', ''])
plt.show()
从上图中的权重系数随时间间隔衰减情况可以看出,指数移动平均系数衰减较快,也因此一般也能更快的发现趋势的变化。
2. 三种均线可视化
下面展示贵州茅台从2018.6.1到2019.12.31收盘价的三种移动均线。
import numpy as np
import pandas as pd
import baostock as bs
import matplotlib.pyplot as plt
def get_data(code, start_date, end_date):
lg = bs.login()
rs = bs.query_history_k_data_plus(code,
"date,code,open,high,low,close,volume",
start_date=start_date, end_date=end_date,
frequency="d", adjustflag="3")
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
result = pd.DataFrame(data_list, columns=rs.fields)
bs.logout()
result['date'] = pd.to_datetime(result['date'])
result['open'] = result['open'].astype(float)
result['high'] = result['high'].astype(float)
result['low'] = result['low'].astype(float)
result['close'] = result['close'].astype(float)
result['volume'] = result['volume'].astype(float)
result.set_index(result['date'], inplace=True)
return result
# 简单移动平均
def sma_demo(data, n):
data['SMA20'] = data['close'].rolling(window=n, min_periods=n).mean()
return data
# 加权移动平均
def wma_demo(data, n):
weights = np.array(range(1, n + 1))
weights_sum = np.sum(weights)
data['WMA20'] = data['close'].rolling(window = n, min_periods=n).apply(lambda x: np.sum(x * weights) / weights_sum)
return data
# 指数平均
def ema_demo(data, n):
data['EMA20'] = data['close'].ewm(span=n, min_periods=n, adjust=True).mean()
return data
if __name__ == '__main__':
data = get_data('sh.600519', '2018-06-01', '2019-12-31')[['close']]
data = sma_demo(data, 20)
data = wma_demo(data, 20)
data = ema_demo(data, 20)
fig = plt.figure(figsize=(30, 20))
ax = fig.add_subplot()
ax.plot(data.index, data['close'], linestyle='--', label='close')
ax.plot(data.index, data['SMA20'], label='SMA20')
ax.plot(data.index, data['WMA20'], label='WMA20')
ax.plot(data.index, data['EMA20'], label='EMA20')
ax.legend()
plt.show()
运行结果: