Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Quantitative Stock K-Line Charts

Python Quantitative Stock K-Line Charts

The K-line chart is the most classic chart in finance; a single K-line condenses one period's open, close, high and low prices.

We can use Python pyecharts Moduleto draw interactive stock K-line charts.

pyecharts is a Python data visualization library based on ECharts; its charts support interactions such as zooming, dragging and data zoom, making it especially suited to displaying market data.


Basic Usage of K-Line Charts

First make sure pyecharts and the data retrieval library yfinance are installed:


pip install pyecharts yfinance

Import the relevant modules:


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

The data for a Kline chart is a 2D array, with each K-line corresponding to a four-element sub-array:

Example

from

pyecharts

import

options

as

opts

from

pyecharts.

charts

import

Kline

The data format of each K-line is fixed as [open, close, low, high]

data

=

[

   

[

2320.26

,

2320.26

,

2287.3

,

2362.94

]

,

   

[

2300.0

,

2291.3

,

2288.26

,

2308.38

]

,

   

[

2295.35

,

2346.5

,

2295.35

,

2345.92

]

,

   

[

2347.22

,

2358.98

,

2337.35

,

2363.8

]

,

]

Configure the Kline Chart

kline

=

(

    Kline

(

)

    .

add_xaxis

(

xaxis_data

=

[

"2017-10-24"

,

"2017-10-25"

,

"2017-10-26"

,

"2017-10-27"

]

)

    .

add_yaxis

(

series_name

=

"Kline"

,

y_axis

=

data

)

    .

set_global_opts

(

        xaxis_opts

=

opts.

AxisOpts

(

is_scale

=

True

)

,

        yaxis_opts

=

opts.

AxisOpts

(

is_scale

=

True

)

,

        title_opts

=

opts.

TitleOpts

(

title

=

"Kline Example"

)

,

   

)

)

Render the chart to an HTML file

kline.

render

(

"kline_chart.html"

)

The chained-call structure is intuitive: add_xaxis sets the x-axis (dates), add_yaxis adds the K-line data series, and set_global_opts sets global options such as the title and axes.

A kline_chart.html file is generated in the current directory; open it in a browser and the chart looks like this:

Common pitfall: the Kline data order is fixed as [open, close, low, high] - note the order of low and high, which is what beginners most often get wrong; if the order is wrong, all K-line shapes will be distorted.


Example: Kweichow Moutai K-Line Chart

In real use, data comes from a market data API. The example below uses yfinance to fetch Kweichow Moutai stock data and generate a K-line chart:

Example

import

yfinance

as

yf

from

pyecharts

import

options

as

opts

from

pyecharts.

charts

import

Kline

Fetch Kweichow Moutai's stock data for the past three years

600519.SS is Kweichow Moutai's ticker on Yahoo Finance; .SS denotes the Shanghai Stock Exchange

symbol

=

"600519.SS"

start_date

=

"2021-01-01"

end_date

=

"2023-12-31"

multi_level_index=False: a single stock returns single-level column names

stock_data

=

yf.

download

(

symbol

,

start

=

start_date

,

end

=

end_date

,

                         progress

=

False

,

multi_level_index

=

False

)

Extract the four columns at once and convert to a list, with each row ordered as [open, close, low, high]

kline_data

=

stock_data

[

[

"Open"

,

"Close"

,

"Low"

,

"High"

]

]

.

values

.

tolist

(

)

Configure the Kline Chart

kline

=

(

    Kline

(

)

    .

add_xaxis

(

xaxis_data

=

stock_data.

index

.

strftime

(

"%Y-%m-%d"

)

.

tolist

(

)

)

    .

add_yaxis

(

series_name

=

"Kline"

,

y_axis

=

kline_data

)

    .

set_global_opts

(

        xaxis_opts

=

opts.

AxisOpts

(

is_scale

=

True

)

,

        yaxis_opts

=

opts.

AxisOpts

(

is_scale

=

True

)

,

        title_opts

=

opts.

TitleOpts

(

title

=

"Kweichow Moutai Kline Chart Example"

)

,

        datazoom_opts

=

[

opts.

DataZoomOpts

(

)

]

,

        toolbox_opts

=

opts.

ToolboxOpts

(

            feature

=

{

               

"dataZoom"

:

{

"yAxisIndex"

:

"none"

}

,

               

"restore"

:

{

}

,

               

"saveAsImage"

:

{

}

,

           

}

       

)

,

   

)

)

Render the chart

kline.

render

(

"maotai_kline_chart.html"

)

Two details in the code are worth noting:

First, multi_level_index=False: newer yfinance returns multi-level column names by default when downloading a single stock, which causes type errors when accessing values row by row; adding this parameter directly yields single-level columns.

Second, using stock_data[["Open", "Close", "Low", "High"]].values.tolist() to extract by column name and convert to a list in one step both avoids the inefficiency of row-by-row traversal and naturally guarantees the column order required by K-lines.

A maotai_kline_chart.html file is generated in the current directory; open it and the chart looks like this:

In the configuration, DataZoomOpts provides a bottom zoom slider to drag and view K-lines over any time window; ToolboxOpts provides box-select zoom, restore and export-image buttons.


Drawing a Stock Price Line Chart

Besides K-line charts, pyecharts can also draw ordinary line charts. Take Moutai (600519.SS) as an example to plot the closing price trend:

Example

import

yfinance

as

yf

from

pyecharts

import

options

as

opts

from

pyecharts.

charts

import

Line

from

datetime

import

datetime

,

timedelta

Set the Moutai stock ticker

stock_code

=

"600519.SS"

Data range: the past three years

end_date

=

datetime

.

now

(

)

.

strftime

(

"%Y-%m-%d"

)

start_date

=

(

datetime

.

now

(

)

(

days

=

3

365

)

)

.

strftime

(

"%Y-%m-%d"

)

Use yfinance to fetch stock data

df

=

yf.

download

(

stock_code

,

start

=

start_date

,

end

=

end_date

,

                 progress

=

False

,

multi_level_index

=

False

)

Extract the dates and closing prices from the data

dates

=

df.

index

.

strftime

(

"%Y-%m-%d"

)

.

tolist

(

)

closing_prices

=

df

[

"Close"

]

.

tolist

(

)

Create a Line chart and add an average-value marker line

line_chart

=

Line

(

)

line_chart.

add_xaxis

(

xaxis_data

=

dates

)

line_chart.

add_yaxis

(

    series_name

=

"Moutai Stock Price Trend"

,

    y_axis

=

closing_prices

,

    markline_opts

=

opts.

MarkLineOpts

(

        data

=

[

opts.

MarkLineItem

(

type_

=

"average"

,

name

=

"Average"

)

]

   

)

,

)

line_chart.

set_global_opts

(

    title_opts

=

opts.

TitleOpts

(

title

=

"Moutai Stock Price Trend (Past Three Years)"

)

,

    xaxis_opts

=

opts.

AxisOpts

(

type_

=

"category"

)

,

    yaxis_opts

=

opts.

AxisOpts

(

is_scale

=

True

)

,

    datazoom_opts

=

[

opts.

DataZoomOpts

(

pos_bottom

=

"-2%"

)

]

,

)

Render the chart

line_chart.

render

(

"maotai_stock_trend_chart.html"

)

A maotai_stock_trend_chart.html file is generated in the current directory; open it and the chart looks like this:


Adding Interactive Experience

On this basis you can stack more interactive tools, such as combining inside zoom (mouse-wheel zoom) with slider zoom:

Example

import

yfinance

as

yf

from

pyecharts

import

options

as

opts

from

pyecharts.

charts

import

Line

from

datetime

import

datetime

,

timedelta

stock_code

=

"600519.SS"

end_date

=

datetime

.

now

(

)

.

strftime

(

"%Y-%m-%d"

)

start_date

=

(

datetime

.

now

(

)

(

days

=

3

365

)

)

.

strftime

(

"%Y-%m-%d"

)

df

=

yf.

download

(

stock_code

,

start

=

start_date

,

end

=

end_date

,

                 progress

=

False

,

multi_level_index

=

False

)

dates

=

df.

index

.

strftime

(

"%Y-%m-%d"

)

.

tolist

(

)

closing_prices

=

df

[

"Close"

]

.

tolist

(

)

line_chart

=

Line

(

)

line_chart.

add_xaxis

(

xaxis_data

=

dates

)

line_chart.

add_yaxis

(

    series_name

=

"Moutai Stock Price Trend"

,

    y_axis

=

closing_prices

,

    markline_opts

=

opts.

MarkLineOpts

(

        data

=

[

opts.

MarkLineItem

(

type_

=

"average"

,

name

=

"Average"

)

]

   

)

,

)

line_chart.

set_global_opts

(

    title_opts

=

opts.

TitleOpts

(

title

=

"Moutai Stock Price Trend (Past Three Years)"

)

,

    xaxis_opts

=

opts.

AxisOpts

(

type_

=

"category"

)

,

    yaxis_opts

=

opts.

AxisOpts

(

is_scale

=

True

)

,

   

inside: mouse-wheel zoom; slider: bottom slider zoom, both enabled together

    datazoom_opts

=

[

        opts.

DataZoomOpts

(

type_

=

"inside"

,

pos_bottom

=

"-2%"

)

,

        opts.

DataZoomOpts

(

type_

=

"slider"

,

pos_bottom

=

"-2%"

)

,

   

]

,

    toolbox_opts

=

opts.

ToolboxOpts

(

        feature

=

{

           

"dataZoom"

:

{

"yAxisIndex"

:

"none"

}

,

           

"restore"

:

{

}

,

           

"saveAsImage"

:

{

}

,

       

}

   

)

,

)

Render the chart

line_chart.

render

(

"maotai_stock_trend_chart2.html"

)

A maotai_stock_trend_chart2.html file is generated in the current directory; open it and the chart looks like this:

Interactive charts are not just good-looking: when studying the market you can quickly zoom to any range and inspect how strategy signals behave in the details, far more efficient than static charts.