计算布林带
import numpy as np
from matplotlib import pyplot as plt
import sys
series = np.random.rand(100) * 10 + 10
ser_len = len(series)
win_sz = 5 if len(sys.argv) < 2 else sys.argv[1]
print u'窗口大小: ', win_sz
sma_weight = np.ones(win_sz).astype(float) / win_sz
ema_weight = np.exp(np.linspace(-1, 0, win_sz))
ema_weight /= ema_weight.sum()
sma = []
ema = []
mstd = []
for i in xrange(win_sz - 1, ser_len):
ser_range = series[i - (win_sz - 1): i + 1]
avg = (ser_range * sma_weight).sum()
sma.append(avg)
avg = (ser_range * ema_weight).sum()
ema.append(avg)
std = ser_range.std()
mstd.append(std)
sma = np.asarray(sma)
mstd = np.asarray(mstd)
upper = sma + 2 * mstd
lower = sma - 2 * mstd
ser_slice = series[win_sz - 1:]
x = np.arange(win_sz - 1, ser_len)
print 'x: ', x[:5]
plt.plot(x, ser_slice, 'b', label='series')
print u'序列: ', ser_slice[:5]
plt.plot(x, sma, 'g', label='sma')
print u'简单滑动均值: ', sma[:5]
plt.plot(x, ema, 'r', label='ema')
print u'指数滑动均值: ', ema[:5]
plt.plot(x, upper, 'grey', label='upper bolling')
plt.plot(x, lower, 'grey', label='lower bolling')
plt.legend()
plt.show()