Detailed explanation of K-line chart drawing with vue+Echarts (1) ---- Basic daily K-line chart drawing

1 Introducing Echarts

1.1 Installation

Use the following command to install ECharts through npm

npm install echarts --save

Note: The version of Echarts installed in this article is: "echarts": "5.2.1"

1.2 Introduction

After the installation is complete, you can echartsimport them all, so that we can use echartsall components on this page; the import code is as follows:

import * as echarts from "echarts";

1.3 Basic use

For basic usage of vue+Echarts, please see: Introducing ECharts into the Vue project

2 Basic K-line chart

2.1 Basic K-line chart

Ecahrts comes with a K-line chart, seriesjust typeset it to candlestick;

The horizontal axis of the basic K-line chart is the trading day, and the vertical axis is the price per share. The second is the daily situation of the K-line chart, including the current price, the closing price of the previous day, the opening price, the highest price of the day, and the lowest price of the day. We only need to add the corresponding The data is passed into the corresponding parameters to get the K-line chart we want.

The picture shows an example of a basic K-line chart:
Insert image description here

The code for the above picture is as follows:

<template>
  <div class="echart" id="mychart" style="width:100%; height: 400px;"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
    
    
  data() {
    
    
    return {
    
    };
  },
  mounted() {
    
    
    this.initEcharts();
  },
  methods: {
    
    
    initEcharts() {
    
    
      const option = {
    
    
        title: {
    
    
          text: "K线入门示例"
        },
        tooltip: {
    
    },
        legend: {
    
    },
        xAxis: {
    
    
          data: ["2017-10-24", "2017-10-25", "2017-10-26", "2017-10-27"]
        },
        yAxis: {
    
    },
        series: [
          {
    
    
            type: "candlestick",
            data: [
              [20, 34, 10, 38], //今开、当前价格、最低价格、最高价
              [40, 35, 30, 50],
              [31, 38, 33, 44],
              [38, 15, 5, 42]
            ]
          }
        ]
      };
      const myChart = echarts.init(document.getElementById("mychart"));
      myChart.setOption(option);
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
    
    
        myChart.resize();
      });
    }
  }
};
</script>

2.2 Basic daily K chart

The K-line chart data of financial securities institutions is relatively comprehensive. The K-line chart includes daily K chart, weekly K chart, daily K chart, and annual K chart. In China, red represents an increase and green represents a decrease. The stock market has been green in the past two months. The reason is that The global economy is in decline and the country is being harvested by a major country.

Today we mainly introduce the daily K chart, from which we can deduce the weekly K chart and monthly K chart, but the incoming data is different.

In addition to the red and green histograms, the daily K chart also contains moving averages. The moving average data of the same industry can be directly calculated from the daily K data. However, as a front-end engineer, it is recommended that the moving average data be obtained directly from the background. There will be some calculation errors in the front-end calculation.

In addition, the daily K chart has other attributes that can be adjusted, such as the guard dart to prevent the corresponding data from appearing in the position, the color and width of the K line histogram, etc. After mastering the basic daily K chart configuration, other K line charts will never change without it. .

Let’s go directly to the picture and code example:
Insert image description here

The code for the above picture is as follows:

<template>
  <div class="echart" id="mychart" style="width:100%; height: 400px;"></div>
</template>

<script>
import * as echarts from "echarts";
import SZlineData from "./data/klineDate.ts";
// console.log(SZlineData);

export default {
    
    
  data() {
    
    
    return {
    
    
      upcolor: "#FF0000", //增长颜色
      upBorderColor: "#8A0000",
      downColor: "#008000", // 下跌颜色
      downBorderColor: "#008F28",
      klineData: [] //k线图数据
    };
  },
  mounted() {
    
    
    this.initData();
    this.initEcharts();
  },
  methods: {
    
    
    initData() {
    
    
      this.klineData = this.splitData(SZlineData);
    },
    initEcharts() {
    
    
      const option = {
    
    
        title: {
    
    
          text: "上证指数",
          left: 0
        },
        tooltip: {
    
    
          trigger: "axis",
          axisPointer: {
    
    
            type: "cross"
          }
        },
        legend: {
    
    
          data: ["日K", "MA5", "MA10", "MA20", "MA30"]
        },
        grid: {
    
    
          left: "10%",
          right: "10%",
          bottom: "15%"
        },
        xAxis: {
    
    
          type: "category",
          data: this.klineData.categoryData,
          boundaryGap: false,
          axisLine: {
    
     onZero: false },
          splitLine: {
    
     show: false },
          min: "dataMin",
          max: "dataMax"
        },
        yAxis: {
    
    
          scale: true,
          splitArea: {
    
    
            show: true
          }
        },
        dataZoom: [
          {
    
    
            type: "inside",
            start: 50,
            end: 100
          },
          {
    
    
            show: true,
            type: "slider",
            top: "90%",
            start: 50,
            end: 100
          }
        ],
        series: [
          {
    
    
            name: "日K",
            type: "candlestick",
            data: this.klineData.values,
            itemStyle: {
    
    
              color: this.upColor,
              color0: this.downColor,
              borderColor: this.upBorderColor,
              borderColor0: this.downBorderColor
            },
            markPoint: {
    
    
              label: {
    
    
                formatter: function(param) {
    
    
                  return param != null ? Math.round(param.value) + "" : "";
                }
              },
              data: [
                {
    
    
                  name: "Mark",
                  coord: ["2013/5/31", 2300],
                  value: 2300,
                  itemStyle: {
    
    
                    color: "rgb(41,60,85)"
                  }
                },
                {
    
    
                  name: "highest value",
                  type: "max",
                  valueDim: "highest"
                },
                {
    
    
                  name: "lowest value",
                  type: "min",
                  valueDim: "lowest"
                },
                {
    
    
                  name: "average value on close",
                  type: "average",
                  valueDim: "close"
                }
              ],
              tooltip: {
    
    
                formatter: function(param) {
    
    
                  return param.name + "<br>" + (param.data.coord || "");
                }
              }
            },
            markLine: {
    
    
              symbol: ["none", "none"],
              data: [
                [
                  {
    
    
                    name: "from lowest to highest",
                    type: "min",
                    valueDim: "lowest",
                    symbol: "circle",
                    symbolSize: 10,
                    label: {
    
    
                      show: false
                    },
                    emphasis: {
    
    
                      label: {
    
    
                        show: false
                      }
                    }
                  },
                  {
    
    
                    type: "max",
                    valueDim: "highest",
                    symbol: "circle",
                    symbolSize: 10,
                    label: {
    
    
                      show: false
                    },
                    emphasis: {
    
    
                      label: {
    
    
                        show: false
                      }
                    }
                  }
                ],
                {
    
    
                  name: "min line on close",
                  type: "min",
                  valueDim: "close"
                },
                {
    
    
                  name: "max line on close",
                  type: "max",
                  valueDim: "close"
                }
              ]
            }
          },
          {
    
    
            name: "MA5",
            type: "line",
            data: this.calculateMA(5),
            smooth: true,
            showSymbol: false,
            lineStyle: {
    
    
              width: 1,
              opacity: 0.8
            }
          },
          {
    
    
            name: "MA10",
            type: "line",
            data: this.calculateMA(10),
            smooth: true,
            showSymbol: false,
            lineStyle: {
    
    
              width: 1,
              opacity: 0.8
            }
          },
          {
    
    
            name: "MA20",
            type: "line",
            data: this.calculateMA(20),
            smooth: true,
            showSymbol: false,
            lineStyle: {
    
    
              width: 1,
              opacity: 0.8
            }
          },
          {
    
    
            name: "MA30",
            type: "line",
            data: this.calculateMA(30),
            smooth: true,
            showSymbol: false,
            lineStyle: {
    
    
              width: 1,
              opacity: 0.8
            }
          }
        ]
      };
      const myChart = echarts.init(document.getElementById("mychart"));
      myChart.setOption(option);
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
    
    
        myChart.resize();
      });
    },
    // 数据计算以及拆分
    splitData(rawData) {
    
    
      const categoryData = [];
      const values = [];
      for (let i = 0; i < rawData.length; i++) {
    
    
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
      }
      return {
    
    
        categoryData: categoryData,
        values: values
      };
    },
    // 均值计算
    calculateMA(dayCount) {
    
    
      const result = [];
      for (let i = 0, len = this.klineData.values.length; i < len; i++) {
    
    
        if (i < dayCount) {
    
    
          result.push("-");
          continue;
        }
        let sum = 0;
        for (let j = 0; j < dayCount; j++) {
    
    
          sum += +this.klineData.values[i - j][1];
        }
        // 保留两位小数
        result.push((sum / dayCount).toFixed(2));
      }
      return result;
    }
  }
};
</script>

Note: Some Echarts-related properties have been introduced in previous chapters and will not be repeated here. The above code can realize the basic graphics of daily K-line.

3 Summary

The K-line chart is mainly about understanding the meaning of each data of various graph types. It is mainly composed of a line chart and a daily K chart. Here we introduce the basic daily K chart. In the next issue, we will introduce a more comprehensive daily K chart. Convert to and from time-sharing charts to implement basic applications.

Guess you like

Origin blog.csdn.net/m0_46309087/article/details/127201213