布林带

布林带

布林带由三条线组成:

中轨:移动平均线

上轨:中轨+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 *= 2
lowers = medios - stds
uppers = medios + stds

mp.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 np
import matplotlib.pyplot as mp
import datetime as dt
import matplotlib.dates as md


def 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 s


dates, 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.datetiem
dates = 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))
#卷积核中所有元素之和=1
kernel/=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*stds
lower = ema53 - 2*stds
mp.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()

 

posted @ 2019-09-04 17:33  maplethefox  阅读(374)  评论(0编辑  收藏  举报