# Draw professional K-line diagram with Python [including source code] Using Python to draw a professional K-line diagram is a necessary course for quantitative investment and financial data analysis.

Next, I will realize the drawing of professional K-line chart step by step from the aspects of K-line chart introduction, data acquisition, K-line chart drawing and trading volume drawing, combined with the source code.

### Introduction to K-line diagram

The K-line chart is also called "candle chart" and "Yin-Yang line". It can clearly highlight the market long and short situation in terms of visual effect. The K-line chart has become an indispensable part for everyone to view market data and various quantitative analysis. The common time spans in the K-line chart are minutes, days, weeks and months.

The K line is drawn by four prices: high opening and low closing. It is divided into positive line and negative line. When the closing price is higher than the opening price, it is the positive line, and when the closing price is lower than the opening price, it is the negative line; The schematic diagram of K-line diagram is as follows: The K-line consists of a rectangular entity and two shadow lines. The shadow line above the entity becomes the upper shadow line and the shadow line below becomes the lower shadow line. The entity is relatively long and short with the Yin line, which can form a variety of forms.

1. Stock data

We from Constant number Financial data community to obtain historical market data of the stock market. We obtained the daily market data of Hang Seng Electronics (600570.SH) from June 1, 2021 to August 1, 2021. The code and execution results are as follows.

```# Load the function package required for data retrieval and drawing
import pandas as pd
import datetime
from hs_udata import set_token,stock_quote_daily
from mpl_finance import candlestick_ohlc
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
mpl.rcParams['font.sans-serif'] = ['SimHei'] # Specifies the default font
mpl.rcParams['axes.unicode_minus'] = False  # Solve the problem that the negative sign '-' is displayed as a square in the saved image

def GetData(stock_code,start,end):
#stock_code: the stock code for obtaining stock data
#     Start: start date
#       End: end date
date_start=datetime.datetime.strptime(start,'%Y-%m-%d')
date_end  =datetime.datetime.strptime(end,'%Y-%m-%d')
data = pd.DataFrame([])
while date_start<date_end:
# Obtain daily market data. See for interface description https://udata.hs.net/datas/332/
# adjust_ The way enumeration values are: 0-no recovery weight, 1-pre recovery weight, 2-post recovery weight. The former recovery weight is taken here
data_i = stock_quote_daily(en_prod_code=stock_code
data=pd.concat([data,data_i],axis=0)      # Splice market data by line
date_start+=datetime.timedelta(days=1)    # Date variable auto increment
# Return market data
return data

#1. Get market data
stock_code = "600570.SH"     # Hang Seng Electronics Stock code is 600570.SH
start='2021-06-01'
end  ='2021-08-01'
set_token(token = 'xxxxxxxxxxxxxxxxxxxxxxxx')   # After registration, get and replace the token
data = GetData(stock_code,start,end)
data
``` #### 2. Data processing

Due to constant stock_ quote_ The daily interface returns many parameters, including data on non trading days and suspension dates. Using candlestick_ When drawing the K-line diagram of OHLC package, you need to convert the date to a value. The program code and execution results are as follows:

```#2. Data processing
data = data.loc[data.turnover_status=='transaction']             # Excluding non trading days
,'business_amount']]                  # Select date, high opening and low closing price and trading volume data
data_price = data_price.astype(float)                    # Convert price data type to floating point number
# Convert date format to candlestick_ohlc recognizable value
data_price['Date'] = list(map(lambda x:mdates.date2num(datetime.datetime.strptime(x,'%Y-%m-%d')),data_price.index.tolist()))
data_price
``` #### 3. Draw K-line

Using MPL_ Candlestick in the finance function package_ OHLC function for drawing, the program is as follows:

```#3. Draw K-line diagram
# Extract drawing data
ohlc = data_price[['Date','open_price','high_price','low_price','close_price']]
f1, ax = plt.subplots(figsize = (12,6))                        # create picture
candlestick_ohlc(ax, ohlc.values.tolist(), width=.7
, colorup='red', colordown='green')           # Using candlestick_ohlc drawing
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # Format horizontal date
plt.xticks(rotation=30)                                        # Rotation angle of date display
plt.title(stock_code,fontsize = 14)                            # Set picture title
plt.xlabel('Date',fontsize = 14)                              # Set horizontal axis title
plt.ylabel('Price (yuan)',fontsize = 14)                        # Set vertical axis title
plt.show()
``` ####4. Remove the non trading days in the figure

Because candlestick_ The K-line chart drawn by OHLC function by default does not exclude non trading days (weekends, holidays and suspension dates), resulting in a blank interval between k-lines. Next, we can eliminate the non trading day data in the graph by modifying the horizontal axis data and modifying the date marked on the horizontal axis.

```# 4. Remove non trading day intervals
ohlc = data_price[['Date','open_price','high_price','low_price','close_price']]
ohlc.loc[:,'Date'] = range(len(ohlc))     # Reassign the horizontal axis data so that the horizontal axis data is a continuous value
# mapping
f1, ax = plt.subplots(figsize = (12,6))
candlestick_ohlc(ax, ohlc.values.tolist(), width=.7, colorup='red', colordown='green')
plt.xticks(rotation=30)                                        # Rotation angle of date display
plt.title(stock_code,fontsize = 14)                            # Set picture title
plt.xlabel('Date',fontsize = 14)                               # Set horizontal axis title
plt.ylabel('Price (yuan)',fontsize = 14)                          # Set vertical axis title
# Modify horizontal axis dimension date
date_list = ohlc.index.tolist()           # Get date list
xticks_len = round(len(date_list)/(len(ax.get_xticks())-1))    # Gets the interval of the default horizontal axis dimension
xticks_num = range(0,len(date_list),xticks_len)                # Generate a list of horizontal axis dimension locations
xticks_str = list(map(lambda x:date_list[int(x)],xticks_num))  # Generating list of labeling dates
ax.set_xticks(xticks_num)                                      # Sets the horizontal axis dimension position
ax.set_xticklabels(xticks_str)                                 # Set horizontal axis dimension date
plt.show()
``` In the K-line diagram, in addition to the K-line data, the trading volume data is generally provided. Constant stock_ quote_ The data returned by the daily interface also includes trading volume data. The procedure of drawing K-line chart and trading volume on the same chart is as follows:

```#5. Draw trading volume
fig = plt.figure(figsize=(12,10))
grid = plt.GridSpec(12, 10, wspace=0.5, hspace=0.5)
#(1) Draw K-line diagram
# K-line data
ohlc = data_price[['Date','open_price','high_price','low_price','close_price']]
ohlc.loc[:,'Date'] = range(len(ohlc))     # Re assign the horizontal axis data and draw the K-line diagram without interval
# Draw K-line
ax1 = fig.add_subplot(grid[0:8,0:12])   # Set the dimensions of the K-line diagram
candlestick_ohlc(ax1, ohlc.values.tolist(), width=.7
, colorup='red', colordown='green')
plt.title(stock_code,fontsize = 14)     # Set picture title
plt.ylabel('Price (yuan)',fontsize = 14)   # Set vertical axis title
ax1.set_xticks([])                      # The date is marked in the trading volume, so the x-axis scale here is cleared
ax1.set_xticklabels([])                 # The date is marked in the trading volume, so the x-axis here is cleared
# Volume data
data_volume['color'] = data_volume.apply(lambda row: 1 if row['close_price'] >= row['open_price'] else 0, axis=1)        # Calculate the color corresponding to the trading volume histogram to make it consistent with the color of K line
data_volume.Date = ohlc.Date
ax2 = fig.add_subplot(grid[8:10,0:12])  # Set the volume graph size
ax2.bar(data_volume.query('color==1')['Date']
, color='r')                    # Draw red histogram
ax2.bar(data_volume.query('color==0')['Date']
, color='g')                    # Draw a green histogram
plt.xticks(rotation=30)
plt.xlabel('Date',fontsize = 14)                               # Set horizontal axis title
# Modify horizontal axis date dimension
date_list = ohlc.index.tolist()           # Get date list
xticks_len = round(len(date_list)/(len(ax2.get_xticks())-1))      # Gets the interval of the default horizontal axis dimension
xticks_num = range(0,len(date_list),xticks_len)                   # Generate a list of horizontal axis dimension locations
xticks_str = list(map(lambda x:date_list[int(x)],xticks_num))     # Generating list of labeling dates
ax2.set_xticks(xticks_num)                                        # Sets the horizontal axis dimension position
ax2.set_xticklabels(xticks_str)                                   # Set horizontal axis dimension date
plt.show()
``` So far, a professional K-line map has been drawn.

In the next article, we will add the moving average and common technical index trend chart to the chart. Please look forward to it.

Tags: Python

Posted on Tue, 28 Sep 2021 21:30:23 -0400 by Option