绘制K线图
绘制K线图
案例:使用matplotlib绘制K线图
绘制dates与收盘价的折线图:
import numpy as np import datetime as dt import matplotlib.pyplot as mp import matplotlib.dates as md # 绘制k线图,x为日期 mp.figure('APPL K', facecolor='lightgray') mp.title('APPL K') mp.xlabel('Day', fontsize=12) mp.ylabel('Price', fontsize=12) #拿到坐标轴 ax = mp.gca() #设置主刻度定位器为周定位器(每周一显示主刻度文本) ax.xaxis.set_major_locator( md.WeekdayLocator(byweekday=md.MO) ) ax.xaxis.set_major_formatter(md.DateFormatter('%d %b %Y')) #设置次刻度定位器为日定位器 ax.xaxis.set_minor_locator(md.DayLocator()) mp.tick_params(labelsize=8) dates = dates.astype(md.datetime.datetime) mp.plot(dates, opening_prices, color='dodgerblue', linestyle='-') mp.gcf().autofmt_xdate() mp.show()
绘制每一天的蜡烛图:
#绘制每一天的蜡烛图 #填充色:涨为白色,跌为绿色 rise = closeing_prices >= opening_prices color = np.array([('white' if x else 'limegreen') for x in rise]) #边框色:涨为红色,跌为绿色 edgecolor = np.array([('red' if x else 'limegreen') for x in rise]) #绘制线条 mp.bar(dates, highest_prices - lowest_prices, 0.1, lowest_prices, color=edgecolor) #绘制方块 mp.bar(dates, closeing_prices - opening_prices, 0.8, opening_prices, color=color, edgecolor=edgecolor)
# 绘制K线图 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')
#整理颜色 rise = closing_prices>opening_prices ecolor = np.array(['red' if x else 'green' for x in rise]) color = np.array(['white' if x else 'green' for x in rise]) #绘制实体 mp.bar(dates,opening_prices-closing_prices,0.8,opening_prices, edgecolor=ecolor,color=color,zorder=3) #绘制影线 mp.vlines(dates,lowest_prices,highest_prices,color=ecolor) mp.legend() mp.gcf().autofmt_xdate() mp.show()