• numpy之股价布林带绘制


    import numpy as np
    import matplotlib.pyplot as mp
    import datetime as dt
    import matplotlib.dates as md
    
    '''
        绘制5日均线布林带
    '''
    
    
    # 日期转化函数
    def dmy2ymd(dmy):
        # 把dmy格式的字符串转化成ymd格式的字符串
        dmy = str(dmy, encoding='utf-8')
        d = dt.datetime.strptime(dmy, '%d-%m-%Y')
        d = d.date()
        ymd = d.strftime('%Y-%m-%d')
        return ymd
    
    
    dates, opening_prices, highest_prices, lowest_prices, closing_prices = 
        np.loadtxt('./da_data/aapl.csv', delimiter=',', usecols=(1, 3, 4, 5, 6), unpack=True,
                   dtype='M8[D], f8, f8, f8, f8', converters={1: dmy2ymd})  # converters为转换器,运行时先执行,其中1表示时间所在的列索引号
    
    # 绘制收盘价折线图
    mp.figure('AAPL', facecolor='lightgray')
    mp.title('AAPL', fontsize=18)
    mp.xlabel('date', fontsize=12)
    mp.ylabel('closing_pricing', fontsize=12)
    mp.tick_params(labelsize=10)
    mp.grid(linestyle=':')
    # 设置x轴的刻度定位器,使之更适合显示日期数据
    ax = mp.gca()
    # 以周一作为主刻度
    ma_loc = md.WeekdayLocator(byweekday=md.MO)
    # 次刻度,除周一外的日期
    mi_loc = md.DayLocator()
    ax.xaxis.set_major_locator(ma_loc)
    ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d'))
    ax.xaxis.set_minor_locator(mi_loc)
    # 日期数据类型转换,更适合绘图
    dates = dates.astype(md.datetime.datetime)
    mp.plot(dates, closing_prices, linewidth=2, linestyle='--', color='dodgerblue', label='AAPL', alpha=0.5)
    
    # 基于加权卷积实现5日加权均线
    weights = np.exp(np.linspace(-1, 0, 5))
    weights = weights[::-1] / weights.sum()
    print(weights.sum())
    sma = np.convolve(closing_prices, weights, 'valid')
    mp.plot(dates[4:], sma, linewidth=2, color='r', label='SMA51', alpha=0.8)
    # 绘制布林带的上轨和下轨
    stds = np.zeros(sma.size)
    for i in range(stds.size):
        stds[i] = closing_prices[i:i + 5].std()
    lower = sma - 2 * stds
    upper = sma + 2 * stds
    mp.plot(dates[4:], upper, linewidth=2, color='orangered', label='UPPER', alpha=0.3)
    mp.plot(dates[4:], lower, linewidth=2, color='orangered', label='LOWER', alpha=0.3)
    # 填充布林带
    mp.fill_between(dates[4:], lower, upper, upper > lower, color='orangered', alpha=0.2)
    
    mp.tight_layout()
    mp.legend()
    # 自动格式化x轴日期的显示格式(以最合适的方式显示)
    mp.gcf().autofmt_xdate()
    mp.show()

      

  • 相关阅读:
    Spring--IOC--AOP
    SpringMVC
    elasticsearch为什么检索快?
    linux下无法启动webdriver问题
    python 日志组件
    纯js脚本操作excel
    箭头函数
    Vue与React对比
    Vue Router 路由懒加载
    Vue Router 路由守卫:完整的导航解析流程
  • 原文地址:https://www.cnblogs.com/yuxiangyang/p/11162927.html
Copyright © 2020-2023  润新知