Python Stock Line Chart
We can use the (#) to draw stock K-line charts.
pyecharts is a Python data visualization library based on ECharts, which allows users to use the Python language to generate various types of interactive charts and data visualizations.
View the content of the Python pyecharts module: (#).
In pyecharts, you can use the K-line chart (Kline) to display stock trends. K-line charts are mainly used to display financial data, such as a stock's opening price, closing price, highest price, lowest price, and other information.
First, make sure you have installed pyecharts:
pip install pyecharts
We use data from Yahoo Finance to obtain stock data from the past year. We can use the yfinance library:
pip install yfinance
### Using K-line Charts
Import the relevant modules:
from pyecharts import options as opts from pyecharts.charts import Kline
Prepare the data:
Kline chart data is usually a two-dimensional array containing the opening price, closing price, highest price, and lowest price, for example:
data = [ [2320.26, 2320.26, 2287.3, 2362.94], [2300, 2291.3, 2288.26, 2308.38], # ...]
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"), ))
Here, `add_xaxis` is used to set the x-axis data, `add_yaxis` is used to add the Kline data series, and `set_global_opts` is used to set global configurations, including the title.
Render the chart:
kline.render("kline_chart.html")
Render the Kline chart to an HTML file.
## Example
from pyecharts import options as opts
from pyecharts.charts import Kline
# Prepare data
data =[
[2320.26,2320.26,2287.3,2362.94],
[2300,2291.3,2288.26,2308.38],
[2295.35,2346.5,2295.35,2345.92],
[2347.22,2358.98,2337.35,2363.8],
# ... more data
]
# Configure 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 chart
kline.render("kline_chart.html")
**Explanation:**
* We have a dataset named `data`, which contains daily financial data, including the opening price, closing price, highest price, and lowest price.
* We created a `Kline` instance, used `add_xaxis` to set the x-axis data (in this case, dates), and used `add_yaxis` to add the Kline data series.
* Used `set_global_opts` to set global options, such as scaling for the x-axis and y-axis, and the chart title.
* Finally, we used `render` to render the chart to an HTML file.
A file named kline_chart.html will be generated in the current directory. Opening this file displays the chart as follows:
!(#)
Below is an example code demonstrating how to fetch stock data for Kweichow Moutai and generate a K-line chart:
## Example
import yfinance as yf
from pyecharts import options as opts
from pyecharts.charts import Kline
# Get Kweichow Moutai stock data for the past three years
symbol='600519.SS'# 600519.SS is the stock code for Kweichow Moutai
start_date ='2020-01-01'
end_date ='2022-12-31'
stock_data = yf.download(symbol, start=start_date, end=end_date)
# Extract the data format required for the K-line chart
kline_data =[]
for index, row in stock_data.iterrows():
kline_data.append([row['Open'], row['Close'], row['Low'], row['High']])
# Configure 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 chart
kline.render("maotai_kline_chart.html")
A file named maotai_kline_chart.html will be generated in the current directory. Opening this file displays the chart as follows:
!(#)
### Drawing Line Charts
We can also use pyecharts to draw simple line charts for stocks, using Moutai (600519.SH) as an example:
## Example
import yfinance as yf
from pyecharts import options as opts
from pyecharts.charts import Line
from datetime import datetime, timedelta
# Set Moutai stock code
stock_code ="600519.SS"
# Get current date
end_date =datetime.now().strftime('%Y-%m-%d')
# Calculate the date three years ago
start_date =(datetime.now() - timedelta(days=3 * 365)).strftime('%Y-%m-%d')
# Use yfinance to get stock data
df = yf.download(stock_code, start=start_date, end=end_date)
# Extract dates and closing prices from the data
dates = df.index.strftime('%Y-%m-%d').tolist()
closing_prices = df['Close'].tolist()
# Create Line chart
line_chart = Line()
line_chart.addpolar axis(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")]
)
)
linepolar chart.set_global_opts(
title_opts=opts.TitleOpts(title="Moutai Stock Price Trend Chart (Past Three Years)"),
xaxis_opts=opts.AxisOpts(type_="category"),
yaxis_opts=opts.AxisOpts(is_scale=True),
datazoom_opts=[opts.DataZoompolar Opts(pos_bottom="-2%")],
)
# Render chart
line_chart.render("maotai_stock_trend_chart.html")
A file named maotai_stock_trend_chart.html will be generated in the current directory. Opening this file displays the chart as follows:
!(#)
Consider adding some chart tools, such as data zoom, data view, etc., to enhance the user's interactive experience.
Below is the optimized code with added data zoom and data view functionality:
## Example
import yfinance as yf
from pyecharts import options as opts
from pyecharts.chartspolar as Line
from pyecharts.commons.utils import JsCode
from datetime import datetime, timedelta
# Set Moutai stock code
stock_code ="600519.SS"
# Get current date
end_date =datetime.now().strftime('%Y-%m-%d')
# Calculate the date three years ago
start_date =(datetime.now() - timedelta(days=3 * 365)).strftime('%Y-%m-%polar d')
# Use yfinance to get stock data
df = yf.download(stock_code, start=start_date, end=end_date)
# Extract dates and closing prices from the data
dates = df.index.strftime('%Y-%m-%d').tolist()
closing_prices = df['Close'].tolist()
# Create Line chart
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 Chart (Past Three Years)"),
xaxis_opts=opts.AxisOpts(type_="category"),
yaxis_opts=opts.AxisOpts(is_scale=True),
datazoom_opts=[
opts.DataZoomOpts(
pos_bottom="-2%",
range_start=0,
range_end=100,
type_="inside"
),
opts.DataZoomOpts(
pos_bottom="-2%",
range_start=0,
range_end=100,
type_="slider",
),
],
toolbox_opts=opts.ToolboxOpts(
feature={
"dataZoom": {"yAxisIndex": "none"},
"restore": {},
"saveAsImage": {},
}
),
)
# Render chart
line_chart.render("maotai_stock_trend_chart2.html")
A file named maotai_stock_trend_chart2.html will be generated in the current directory. Opening this file displays the chart as follows:
!(#)
YouTip