Software Testing | Python Data Visualization Artifact - pyecharts Tutorial (9)

Use pyecharts to draw the advanced version of K-line chart

Introduction

Kandlestick Chart, also known as candlestick chart, is a chart type used to visualize price trends and trading data in financial markets. It is one of the most commonly used technical analysis tools in financial markets such as stocks, foreign exchange, and futures, and can provide important information about price changes, trends, and market sentiment. K-line charts usually include four key price points: opening price, closing price, highest price, and lowest price. These price points form a rectangle (candle) or a vertical line segment, which is convenient for visually observing price trends.

As Python's data visualization tool, pyecharts can also help us draw K-line charts. This article will introduce to you how to use pyecharts to draw K-line charts.

Common configuration classes for K-line charts

  1. Kline: K-line chart class, used to create K-line chart objects.
  2. opts.AxisOpts: Axis configuration class, used to set the styles and properties of the abscissa and ordinate axes.
  3. opts.DataZoomOpts: Data zoom configuration class, used to set the style and properties of data zoom.
  4. opts.MarkLineOpts: Markline configuration class, used to set the style and attributes of the markline.
  5. opts.MarkLineItem: MarkLineItem class, used to set the type and value of the mark.
  6. opts.TooltipOpts: prompt box configuration class, used to set the style and attributes of the prompt box.

The above are some commonly used configuration classes, which we can configure to set the style and interactive effect of the K-line chart. According to specific needs, you can flexibly use these configuration classes to customize the K-line chart you want. Other configuration classes will not be introduced one by one here.

Draw basic K-line chart

First, let's draw a simple K-line chart. The sample code is as follows:

from pyecharts import options as opts
from pyecharts.charts import Kline

# 准备K线图的数据
x_data = ["2022-09-01", "2022-09-02", "2022-09-03", "2022-09-04", "2022-09-05"]
y_data = [
    [90, 120, 80, 110],  # 第一天的K线数据:开盘价、最高价、最低价、收盘价
    [110, 130, 100, 120],  # 第二天的K线数据
    [130, 140, 90, 110],  # 第三天的K线数据
    [110, 130, 100, 120],  # 第四天的K线数据
    [120, 140, 90, 110],  # 第五天的K线数据
]

# 创建K线图对象
kline = (
    Kline()
    .add_xaxis(xaxis_data=x_data)  # 设置x轴数据
    .add_yaxis(
        series_name="K线图",  # 设置数据系列的名称
        y_axis=y_data,  # 设置y轴数据
        itemstyle_opts=opts.ItemStyleOpts(color="blue", color0="green"),  # 设置K线图的颜色
    )
    .set_global_opts(
        xaxis_opts=opts.AxisOpts(is_scale=True),  # 设置x轴选项,使其自适应
        yaxis_opts=opts.AxisOpts(is_scale=True),  # 设置y轴选项,使其自适应
        title_opts=opts.TitleOpts(title="K线图示例"),  # 设置标题选项
    )
)

# 渲染图表
kline.render("kline.html")

Run the script and the K-line chart drawn is as follows:

Insert image description here

Of course, the candlestick charts we usually see are more complicated. There are other graphics and lines to help us look at the candlestick charts. pyecharts can also help us draw auxiliary lines. The code is as follows:

import random
from pyecharts import options as opts
from pyecharts.charts import Kline

# 随机数据
data = []
# 使用嵌套的循环结构生成双层随机嵌套列表
for _ in range(30):
    inner_list = []
    # 内层列表个数
    for _ in range(4):
        random_num = random.randint(3000, 3500)
        inner_list.append(random_num)
    data.append(inner_list)

# 创建K线图对象
c = (
    Kline()
    # 添加横坐标数据
    .add_xaxis(["2022/9/{}".format(i + 1) for i in range(30)])
    # 添加纵坐标数据
    .add_yaxis(
        "kline",
        data,
        # 设置标线配置项,标记最大值
        markline_opts=opts.MarkLineOpts(
            data=[opts.MarkLineItem(type_="max", value_dim="close")]
        ),
    )
    # 设置全局配置项
    .set_global_opts(
        xaxis_opts=opts.AxisOpts(is_scale=True),  # 设置横坐标��配置项,is_scale=True表示自适应刻度
        yaxis_opts=opts.AxisOpts(
            is_scale=True,  # 设置纵坐标轴配置项,is_scale=True表示自适应刻度
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True,  # 设置分割区域配置项,is_show=True表示显示分割区域
                areastyle_opts=opts.AreaStyleOpts(opacity=1)  # 设置分割区域样式配置项,opacity=1表示不透明
            ),
        ),
        title_opts=opts.TitleOpts(title="K线图示例2"),  # 设置标题配置项
    )
)


# 渲染为HTML文件
c.render("K线图示例2.html")

Run the script and the generated image is as follows:

Insert image description here

Many times, we want to see the short-term price trend. We can add the effect of mouse sliding and zooming on the basis of the above, so that we can view the short-term price. The code is as follows:

import random
from pyecharts import options as opts
from pyecharts.charts import Kline

# 随机数据
data = []
# 使用嵌套的循环结构生成双层随机嵌套列表
for _ in range(30):
    inner_list = []
    # 内层列表个数
    for _ in range(4):
        random_num = random.randint(3000, 3500)
        inner_list.append(random_num)
    data.append(inner_list)

# 创建K线图对象
c = (
    Kline()
    # 添加横坐标数据
    .add_xaxis(["2022/9/{}".format(i + 1) for i in range(30)])
    # 添加纵坐标数据
    .add_yaxis(
        "kline",
        data,
        # 设置图表元素样式
        itemstyle_opts=opts.ItemStyleOpts(
            color="#ec0000",
            color0="#00da3c",
            border_color="#8A0000",
            border_color0="#008F28",
        ),
    )
    # 设置全局配置项
    .set_global_opts(
        # 设置横坐标轴配置项,is_scale=True表示自适应刻度
        xaxis_opts=opts.AxisOpts(is_scale=True),
        # 设置纵坐标轴配置项,is_scale=True表示自适应刻度
        yaxis_opts=opts.AxisOpts(
            is_scale=True,
            # 设置分割区域配置项,is_show=True表示显示分割区域
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True,
                # 设置分割区域样式配置项,opacity=1表示不透明
                areastyle_opts=opts.AreaStyleOpts(opacity=1)
            ),
        ),
        # 设置数据缩放配置项,type_="inside"表示内置缩放
        datazoom_opts=[opts.DataZoomOpts(type_="inside")],
        # 设置标题配置项,title="K线图鼠标缩放"为标题内容
        title_opts=opts.TitleOpts(title="K线图示例3"),
    )
)

# 渲染为HTML文件
c.render("K线图示例3.html")

Run the script, as shown below, and we can slide the mouse on the generated image to display the price change information of certain days.

Insert image description here

If we need to view images with a longer period, mouse zooming may be troublesome. We can use the slider method to facilitate our viewing. The specific implementation code is as follows:

import random
from pyecharts import options as opts
from pyecharts.charts import Kline

# 随机数据
data = []
# 使用嵌套的循环结构生成双层随机嵌套列表
for _ in range(30):
    inner_list = []
    # 内层列表个数
    for _ in range(4):
        random_num = random.randint(3000, 3500)
        inner_list.append(random_num)
    data.append(inner_list)

# 创建K线图对象
c = (
    Kline()
    # 添加横坐标数据
    .add_xaxis(["2022/9/{}".format(i + 1) for i in range(30)])
    # 添加纵坐标数据
    .add_yaxis("kline", data)
    # 设置全局配置项
    .set_global_opts(
        xaxis_opts=opts.AxisOpts(is_scale=True),  # 设置横坐标轴配置项,is_scale=True表示自适应刻度
        yaxis_opts=opts.AxisOpts(
            is_scale=True,  # 设置纵坐标轴配置项,is_scale=True表示自适应刻度
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True,  # 设置分割区域配置项,is_show=True表示显示分割区域
                areastyle_opts=opts.AreaStyleOpts(opacity=1)  # 设置分割区域样式配置项,opacity=1表示不透明
            ),
        ),
        datazoom_opts=[opts.DataZoomOpts()],  # 设置数据缩放配置项位置在底部偏下
        title_opts=opts.TitleOpts(title="K线图示例4"),  # 设置标题配置项
    )
)

# 渲染为HTML文件
c.render("K线图示例4.html")

Run the script and the generated image is as follows:

Insert image description here

Guess you like

Origin blog.csdn.net/Tester_muller/article/details/132673864