布林带
中轨:移动平均线
上轨:中轨+2x5日收盘价标准差 (顶部的压力)
下轨:中轨-2x5日收盘价标准差 (底部的支撑力)
布林带收窄代表稳定的趋势,布林带张开代表有较大的波动空间的趋势。
绘制5日均线的布林带
weights = np.exp(np.linspace(-1, 0, 5))weights /= weights.sum()em5 = np.convolve(closing_prices, weights[::-1], 'valid')stds = np.zeros(em5.size)for i in range(stds.size): stds[i] = closing_prices[i:i + 5].std()stds *= 2lowers = medios - stdsuppers = medios + stdsmp.plot(dates, closing_prices, c='lightgray', label='Closing Price')mp.plot(dates[4:], medios, c='dodgerblue', label='Medio')mp.plot(dates[4:], lowers, c='limegreen', label='Lower')mp.plot(dates[4:], uppers, c='orangered', label='Upper')
# 绘制布林带import numpy as npimport matplotlib.pyplot as mpimport datetime as dtimport matplotlib.dates as mddef dmy2ymd(dmy): """ 把日月年转年月日 :param day: :return: """ dmy = str(dmy, encoding='utf-8') t = dt.datetime.strptime(dmy, '%d-%m-%Y') s = t.date().strftime('%Y-%m-%d') return sdates, opening_prices, \highest_prices, lowest_prices, \closing_prices = \ np.loadtxt('aapl.csv', delimiter=',', usecols=(1, 3, 4, 5, 6), unpack=True, dtype='M8[D],f8,f8,f8,f8', converters={1: dmy2ymd}) # 日月年转年月日print(dates)# 绘制收盘价的折现图mp.figure('APPL', facecolor='lightgray')mp.title('APPL', fontsize=18)mp.xlabel('Date', fontsize=14)mp.ylabel('Price', fontsize=14)mp.grid(linestyle=":")# 设置刻度定位器# 每周一一个主刻度,一天一个次刻度ax = mp.gca()ma_loc = md.WeekdayLocator(byweekday=md.MO)ax.xaxis.set_major_locator(ma_loc)ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d'))ax.xaxis.set_minor_locator(md.DayLocator())# 修改dates的dtype为md.datetime.datetiemdates = dates.astype(md.datetime.datetime)mp.plot(dates, closing_prices, color='dodgerblue', linewidth=2, linestyle='--', alpha=0.8, label='APPL Closing Price')#基础卷积实现5日加权平均线#寻找一组卷积核kernel = np.exp(np.linspace(-1,0,5))#卷积核中所有元素之和=1kernel/=kernel.sum()print(kernel)ema53 = np.convolve(closing_prices,kernel[::-1],'valid')mp.plot(dates[4:],ema53,color='red', label='EMA-53')#最近5日标准差数组stds = np.zeros(ema53.size)for i in range(stds.size): stds[i] = closing_prices[i:i+5].std()#计算上轨和下轨upper = ema53 + 2*stdslower = ema53 - 2*stdsmp.plot(dates[4:],upper,color='orangered',label='Upper')mp.plot(dates[4:],lower,color='orangered',label='Lower')#填充mp.fill_between(dates[4:],upper,lower,upper>lower, color='orangered',alpha=0.1)mp.legend()mp.gcf().autofmt_xdate()mp.show()