matplotlib绘制K线图
matplotlib绘制K线图
Claroja 发表于9个月前
matplotlib绘制K线图
• 发表于 9个月前
• 阅读 13
• 收藏 0
• 评论 0

Date Open High Low Close
2016/1/4 102.610001 105.370003 102 105.349998
2016/1/5 105.75 105.849998 102.410004 102.709999
2016/1/6 100.559998 102.370003 99.870003 100.699997
2016/1/7 98.68 100.129997 96.43 96.449997
2016/1/8 98.550003 99.110001 96.760002 96.959999

``````import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator,DayLocator, MONDAY
import pandas as pd
import matplotlib.dates as mdates
from matplotlib.finance import candlestick_ohlc
#1.数据预处理
#读取数据
#将时间数据转换为pandas的时间格式
data["Date"]=pd.to_datetime(data["Date"])
#将时间数据转换为matplotlib的时间格式
data['Date'] = data['Date'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
#将数据框转换为元组
tuples = [tuple(x) for x in data[['Date','Open','High','Low','Close']].values]

#2.图像设置
#获得fig和ax对象
fig, ax = plt.subplots()
#调节横坐标距离底部的长度
#设置横坐标标签的显示时间间隔(显示每周的周一)
mondays = WeekdayLocator(MONDAY)
ax.xaxis.set_major_locator(mondays)
#设置横坐标刻度的显示间隔(每个刻度代表一天)
alldays = DayLocator()
ax.xaxis.set_minor_locator(alldays)
#设置横坐标标签的显示样式，为“月、日”，Jan 12
weekFormatter = DateFormatter('%b %d')
ax.xaxis.set_major_formatter(weekFormatter)
#显示每个刻度的标签
#dayFormatter = DateFormatter('%d')
# ax.xaxis.set_minor_formatter(dayFormatter)

#3.绘图
#烛台图绘制
candlestick_ohlc(ax, tuples, width=0.6,colorup='r',colordown="g")
#调整图像设置横坐标标签的显示样式，获得当前坐标轴plt.gca、获得x轴刻度标签get_xticklabels、转换角度rotation、旋转角度hori...ent
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
plt.show()``````

×