使用matplotlib绘制股票K线图

"""
    文件加载--绘制股票K线图
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dts
import time


def dmy2ymd(dmy):
    """
        与numpy.loadtxt中converters转换器配合使用
        变换日期格式:字符串-->解析为日期-->格式化为字符串
    :param dmy: 
    :return: 新的时间字符串
    """
    time1 = time.strptime(dmy.decode(), '%d-%m-%Y')
    t = time.strftime('%Y-%m-%d', time1)
    return t
    pass


# 加载文件
date, opening_price, highest_price, lowest_price, closing_price = \
    np.loadtxt(r'E:\Python达内\数据分析学习素材\da_data\aapl.csv',
               dtype='M8[D],f8,f8,f8,f8', # 转为数组后,元素类型
               delimiter=',',            # 分隔符
               usecols=(1, 3, 4, 5, 6),  # 读取文件的列,0开始
               unpack=True,              #是否拆包
               converters={
    
    1: dmy2ymd})  # 转换器,将日期改为M8[D]可转换格式
# 构建窗口
plt.figure('K line Chart', facecolor='lightgray')
# 网格线
plt.grid(linestyle='-.')
# 刻度参数
plt.tick_params(labelsize='10')
# 标题
plt.title('APPL', fontdict={
    
    'fontsize': 18, 'color': 'black'})
# 坐标轴文本
plt.xlabel('Date', fontdict={
    
    'fontsize': 15})
plt.ylabel('Price', fontdict={
    
    'fontsize': 15})
# 刻度设置
ax = plt.gca()
ax.xaxis.set_major_locator(dts.WeekdayLocator(byweekday=dts.MO))
ax.xaxis.set_major_formatter(dts.DateFormatter('%d %m %Y'))
ax.xaxis.set_minor_locator(dts.DayLocator())
# 绘制折线图
plt.plot(date, opening_price, color='yellow', label='opening price', alpha=0.3)
# plt.plot(date, highest_price, color='red', label='highest_price', alpha=0.3)
# plt.plot(date, lowest_price, color='green', label='lowest_price', alpha=0.3)
plt.plot(date, closing_price, color='blue', label='closing_price', alpha=0.3)
# 绘制蜡烛图
# 整理颜色(使用bool掩码,建立颜色列表)
rise = opening_price > closing_price
# color1 = ['red' if x else 'green' for x in rise]
color_arr1 = np.array(['green' for i in range(1, 31)], dtype='U5')
# 掩码 将rise为True的部分变为'white'
color_arr1[rise] = 'white'
color_arr2 = np.array(['green' for j in range(1, 31)], dtype='U5')
color_arr2[rise] = 'r'
# 绘制实体
plt.bar(date, closing_price - opening_price, 0.8,
        bottom=opening_price, color=color_arr1,
        edgecolor=color_arr2, zorder=3)
# 绘制影线
plt.vlines(date, lowest_price, highest_price, colors='black')
plt.legend()
# 自动化日期,避免文本过长,覆盖
plt.gcf().autofmt_xdate()
plt.show()

猜你喜欢

转载自blog.csdn.net/m0_51489557/article/details/130018039