matplotlib draws a candlestick chart using its own data

 The candlestick charts in other tutorials use ready-made libraries such as tushare to obtain data and directly use matplotlib.finance.candlestick_ochl to draw graphics, but there is no detailed description of the use of their own data.

The following is a summary of the key points from my code. The first part is the import of the package. If matplotlib.pyplot.show() cannot display graphics, before importing matplotlib.pyplot, execute matplotlib.use('TkAgg' after importing matplotlib ) , TkAgg is a graphical interface using tkinter

import datetime
from tkinter import *
import pandas as pd
import numpy as np
import matplotlib

matplotlib.use('TkAgg')  # 处理图形不显示的问题,要在导入 matplotlib.pyplot 之前

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.finance as mpf  

 The following function converts data of type datetime to the type required for drawing graphics.

datetime2matplotlib_np_array(data_datetime) # data_datetime是numpy.array类型,
datetime2matplotlib(data_datetime) # data_datetime是list类型

def datetime2matplotlib(data_list):
    """
    把 data_list 中的 datetime 类型的数据转换为 matplotlib 的轴所需的格式
    :param data_list: list,只有一个 datetime 类型元素
    :return: list
    """
    for index, i in enumerate(data_list):
        data_list[index] = mpf.date2num(datetime.datetime.strptime(i, "%Y-%m-%d %H:%M:%S"))
    return data_list


def datetime2matplotlib_np_array(np_array):
    """
    把 numpy 中的datetime 类型的数据转换为 matplotlib 的轴能使用的类型
    :param np_array: numpy.array,只有一个 datetime 类型元素
    :return:
    """
    for line_no, line in enumerate(np_array):
        # 把日期整理成所需的类型
        datetime_field = line[0]
        datetime_field = datetime.datetime.strptime(datetime_field, "%Y-%m-%d %H:%M:%S")
        np_array[line_no][0] = mpf.date2num(datetime_field)
    return np_array

Use candlestick_ochl to plot the kline_data.

If you want the data corresponding to the price such as the moving average near the k-line, you need to use ax_kline.twiny() to share the y-axis, so that only the moving distance between the moving average and the k-line is the same, the y-axis can share the coordinates normally. A normal candlestick chart.

# 绘制k线
mpf.candlestick_ochl(ax_kline, kline_data, width=0.6, colorup='red', colordown='green', alpha=1.0)
# ax_kline.xaxis.set_major_locator(mdates.DayLocator(bymonthday=range(1, 32), interval=15))  # 设置x轴间隔
ax_kline.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))  # 格式化X轴的时间
for label in ax_kline.xaxis.get_ticklabels():
    label.set_rotation(45)  # 旋转x轴

# k线上附加绘制均线
ax_ma5 = ax_kline.twiny()  # 共享y轴
ax_ma5.plot(data_datetime, data_ma5, linewidth=1, linestyle="-", color="blue")
ax_ma10 = ax_kline.twiny()  # 共享y轴
ax_ma10.plot(data_datetime, data_ma10, linewidth=1, linestyle="-", color="#00ff00")

plt.grid(True)  # 显示网格
plt.show()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324414013&siteId=291194637