想通过 Python 和 akshare 绘制 K线图,网上找了很多代码,放在 Pycharm 中都是无法正常运行绘制的,于是自己整理了下并调试成功。
环境:
python3.9(miniconda3)、Pycharm、Win10
需要用的模块或者工具库:
akshare(1.11.91)、pandas(2.1.1)、numpy(1.26.2)、matplotlib(3.8.2)、mplfinance(0.12.10b0)
绘制K线图流程如下:
-
获取中国平安数据
def getStoneData(): pingan = ak.stock_zh_a_daily(symbol="sh601318", adjust="qfq") df3 = pingan.reset_index().iloc[-30:, :6] # 取过去30天数据 df3 = df3.dropna(how='any').reset_index(drop=True) # 去除空值且从零开始编号索引 df3 = df3.sort_values(by='date', ascending=True) print(df3.info()) # 均线数据 df3['5'] = df3.close.rolling(5).mean() df3['10'] = df3.close.rolling(10).mean() print(df3.tail()) return df3
通过 akshare 获取数据如下:
************<class 'pandas.core.frame.DataFrame'> RangeIndex: 30 entries, 0 to 29 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 index 30 non-null int64 1 date 30 non-null object 2 open 30 non-null float64 3 high 30 non-null float64 4 low 30 non-null float64 5 close 30 non-null float64 dtypes: float64(4), int64(1), object(1) memory usage: 1.5+ KB None index date open high low close 5 10 25 4011 2023-12-04 40.85 41.27 40.31 40.38 40.924 41.801 26 4012 2023-12-05 40.12 40.17 39.51 39.53 40.496 41.447 27 4013 2023-12-06 39.50 39.75 39.29 39.53 40.252 41.127 28 4014 2023-12-07 39.36 39.72 38.88 39.34 39.960 40.756 29 4015 2023-12-08 39.25 39.63 39.19 39.19 39.594 40.406
-
绘制K线图
def drawKLine(df3): plt.style.use("ggplot") fig, ax = plt.subplots(1, 1, figsize=(8, 3), dpi=200) # 绘制 K线 candlestick2_ohlc(ax, opens=df3['open'].values, highs=df3['high'].values, lows=df3['low'].values, closes=df3['close'].values, width=0.75, colorup="r", colordown="g") # 显示最高点和最低点 ax.text(df3.high.idxmax(), df3.high.max(), s=df3.high.max(), fontsize=8) ax.text(df3.high.idxmin(), df3.high.min() - 2, s=df3.high.min(), fontsize=8) # 显示中文 plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] ax.set_facecolor("white") ax.set_title("中国平安") # 画均线 plt.plot(df3['5'].values, alpha=0.5, label='MA5') plt.plot(df3['10'].values, alpha=0.5, label='MA10') ax.legend(facecolor='white', edgecolor='white', fontsize=6) # date 为 object 数据类型,通过 pd.to_datetime将该列数据转换为时间类型,即datetime df3.date = pd.to_datetime(df3.date, format='%Y-%m-%d') # 修改x轴坐标 plt.xticks(ticks=np.arange(0, len(df3)), labels=df3.date.dt.strftime('%Y-%m-%d').to_numpy()) plt.xticks(rotation=90, size=8) # 修改y轴坐标 ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) # x轴坐标显示不全,整理 plt.subplots_adjust(bottom=0.25) plt.show()
股票中国平安的 K线绘制如下: