之前在一篇文章中提到Matplotlib可视化,甚至可以用来画股票K线图,许多同学也在问代码,这次来发个文回应下。
Python用matplotlib绘制K线图,需要配合talib、numpy、mpl_finance等第三方库来使用,具体展示如下:
股市及期货市场中的K线图的画法包含四个数据,即开盘价、最高价、最低价、收盘价。
所有的k线都是围绕这四个数据展开,反映大势的状况和价格信息。
如果把每日的K线图放在一张纸上,就能得到日K线图,同样也可画出周K线图、月K线图。
第一步:导入相关库
import talib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime
import mpl_finance as mpf
import warnings
import akshare as ak
warnings.filterwarnings('ignore')
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
第二步:获取股票数据
这里从akshare库接口自动获取数据
def getdata(stock_symbol):
global data_all
# 所有股票实时数据
data_all = ak.stock_zh_a_spot()
# 单个股票历史行情数据
global data
data = ak.stock_zh_a_daily(symbol=stock_symbol, adjust="hfq")
# 生成股票code和name
global stock_code
stock_code = data_all[data_all['symbol'] == stock_symbol].values[0, 1]
global stock_name
stock_name = data_all[data_all['symbol'] == stock_symbol].values[0, 2]
print("数据加载完成")
getdata('sh600006')
第三步:绘制k线图
def kline(start_time,end_time):
# 处理数据
global data
data = data[start_time:end_time]
# 10天均线
sma_10 = talib.SMA(np.array(data['close']), 10)
# 30天均线
sma_30 = talib.SMA(np.array(data['close']), 30)
# 添加图表
global fig
fig = plt.figure(figsize=(8, 4),dpi=200)
ax = fig.add_axes([0,0.2,1,0.5])
ax2 = fig.add_axes([0,0,1,0.2])
# 绘制K线图
mpf.candlestick2_ochl(ax, data['open'], data['close'], data['high'], data['low'],
width=0.5, colorup='r', colordown='g', alpha=0.6)
ax.set_xticks(range(0, len(data.index), 10))
ax.plot(sma_10, label='10 日均线')
ax.plot(sma_30, label='30 日均线')
global stock_name
ax.set_title("{0}K线图".format(stock_name))
ax.legend(loc='upper left')
ax.grid(True)
# 绘制成交量柱状图
mpf.volume_overlay(ax2, data['open'], data['close'], data['volume'], colorup='r', colordown='g', width=0.5, alpha=0.8)
ax2.set_xticks(range(0, len(data.index), 10))
ax2.set_xticklabels(data.index[::10].strftime('%Y-%m-%d'), rotation=30)
plt.show()
start_time = '2021-06-01'
end_time = '2021-09-30'
kline(start_time,end_time)