Python draws stock candlestick chart

Table of contents

1 Knowledge of stock K-line charts

2 Use Python to draw stock K-line charts

2.1 Install the mpl_finance library for drawing candlestick charts

2.2 Import related libraries

2.3 Obtain stock basic data with Tushare library

2.4 Date format adjustment and table conversion

2.5 Draw candlestick chart

2.6 Add moving average chart

2.7 Add daily trading volume column chart


1 Knowledge of stock K-line charts

The following figure shows the K-line chart of the Kweichow Moutai stock at the daily level:

The column in the K-line chart is usually called "K-line" . Because it looks like a candle, it is also called a candle chart.

The K-line is drawn based on the 4 prices of the stock:

        Opening price (the price when trading starts at 9:30 am on the same day),

        Closing price (the price at the end of trading at 3:00 p.m. of the day),

        The highest price (the highest price in the stock price fluctuation of the day),

        The lowest price (the lowest price in the stock price fluctuation of the day).

These four prices are referred to as "high", "open", "low" and "close" respectively .

There are two types of K-lines:

        If the closing price of the day is higher than the opening price, that is, the price of the day rises, which is called a Yang line, usually drawn in red;

        If the closing price of the day is lower than the opening price, that is, the price of the day falls, it is called a negative line, usually drawn in green;

        I would like to add that in the US stock market, instead, red represents a fall and green represents an increase.

The broken line in the K-line chart is called the "moving average" .

The moving average is divided into 5-day moving average (MA5), 10-day moving average (MA10), 20-day moving average (MA20), etc. The drawing principle is to average the closing prices of stocks within a certain period of time.

For example, to draw a 5-day moving average, it is necessary to calculate the average of the closing prices of the last 5 consecutive trading days. The specific calculation formula is as follows, where Close1 is the closing price of the current day, Close2 is the closing price of the previous day, and so on.

According to the above formula, a 5-day average price can be calculated for each trading day, and then the 5-day average prices of multiple trading days can be connected into a smooth curve, which is the 5-day moving average. The 10-day moving average and the 20-day moving average are also drawn using a similar principle.

2 Use Python to draw stock K-line charts

2.1 Install the mpl_finance library for drawing candlestick charts

Command line window or Jupyter Notebook:

pip install https://github.com/matplotlib/mpl_finance/archive/master.zip

2.2 Import related libraries

import tushare as ts
import matplotlib.pyplot as plt
import mpl_finance as mpf
import seaborn as sns

2.3 Obtain stock basic data with Tushare library

Obtain the stock price data of the stock "Vanke A" with the stock code "000002" from 2019-06-01 to 2019-09-30 through the Tushare library, the code is as follows.

df = ts.get_k_data('000002','2019-06-01','2019-09-30')

A screenshot of the obtained data part is as follows.

2.4 Date format adjustment and table conversion

Because the candlestick_ochl() function for drawing candlestick charts can only read data in array format, and the date data in it must be in a specific digital format, so it is necessary to adjust the basic stock data obtained earlier, the code is as follows.

# 导入调整日期格式涉及的两个库
from matplotlib.pylab import date2num
import datetime

# 将Tushare库中获取到的日期数据转换成candlestick_ochl()函数可读取的格式
def date_to_num(dates):
    num_time = []
    for date in dates:
        date_time = datetime.datetime.strptime(date,'%Y-%m-%d')
        num_date = date2num(date_time)
        num_time.append(num_date)
    return num_time

# 将DataFrame转换为二维数组,并利用date_to_num()函数转换日期格式
df_arr = df.values  #将DataFrame格式的数据转换为二维数组
# df_arr
df_arr[:,0] = date_to_num(df_arr[:,0])  #将二维数组中的日期转换成数字格式

Check out some of the adjusted data:

You can see that the two-dimensional table in DataFrame format has changed to a two-dimensional array, and the content of the date column has changed from a date in text format to a date in number format.

2.5 Draw candlestick chart

fig,ax = plt.subplots(figsize=(15,6))
mpf.candlestick_ochl(ax,df_arr,width=0.6,colorup='r',colordown='g',alpha=1.0)
plt.grid() #显示网格
ax.xaxis_date()  #设置x轴的刻度格式为常规日期格式

2.6 Add moving average chart

Taking adding the 5-day moving average and the 10-day moving average as an example, first construct the data of the 5-day moving average and the 10-day moving average through the following code.

df['MA5'] = df['close'].rolling(5).mean()
df['MA10'] = df['close'].rolling(10).mean()

The moving average data can be directly calculated through the rolling() function and the mean() function. To calculate the data of the 20-day or 30-day moving average, just replace the parameters in the rolling() function with 20 or 30 .

View the data at this time:

It can be seen that the first 4 rows of the MA5 column representing the 5-day moving average data are empty. Calculated, so it is a null value; similarly, the first 9 rows of column MA10 are also null, and there is no data until the 10th row.

After obtaining the data of the 5-day moving average and the 10-day moving average, it can be drawn into a chart. The code is as follows.

plt.rcParams['font.sans-serif'] = ['SimHei']  #设置正常显示中文
fig,ax = plt.subplots(figsize=(15,6))
mpf.candlestick_ochl(ax,df_arr,width=0.6,colorup='r',colordown='g',alpha=1.0)
plt.plot(df_arr[:,0],df['MA5'])
plt.plot(df_arr[:,0],df['MA10'])

plt.grid()
ax.xaxis_date()

plt.title('万科A')
plt.xlabel('日期')
plt.ylabel('价格')

2.7 Add daily trading volume column chart

In actual commercial combat, there are often daily trading volume column charts that appear together with stock K-line charts and moving average charts. Next, use the knowledge points of drawing multi-graphs to draw two sub-graphs in one canvas. The first sub-graph contains the K-line chart and the moving average chart, and the second sub-graph is the daily trading volume column chart. The code is as follows.

fig,axes = plt.subplots(2,1,sharex=True,figsize=(15,8))
ax1,ax2 = axes.flatten()

# 绘制K线图和均线图
mpf.candlestick_ochl(ax1,df_arr,width=0.6,colorup='r',colordown='g',alpha=1.0)
ax1.plot(df_arr[:,0],df['MA5'])
ax1.plot(df_arr[:,0],df['MA10'])

ax1.grid()
ax1.xaxis_date()
ax1.set_title('万科A',fontsize=16)
ax1.set_ylabel('价格',fontsize=16)

# 绘制每日成交量图
ax2.bar(df_arr[:,0],df_arr[:,5])
ax2.set_xlabel('日期',fontsize=16)
ax2.set_ylabel('成交量',fontsize=16)
ax1.grid()
ax1.xaxis_date()

 

 

Guess you like

Origin blog.csdn.net/qq_42433311/article/details/124060394