Generally speaking, we will obtain K-line charts from major brokerage platforms, but the K-line charts obtained in this case are often not flexible enough to meet the complex and changeable production needs. Therefore, it is necessary for us to learn how to draw K-line diagram in Python.
It should be noted that mpl_finance is the original matplotlib.finance, and now it is independent (and it seems that no one maintains the update), and we will use the method it provides to draw the K-line diagram; Tushare is a library for obtaining stock data online; There is a FuncFormatter () method in matplotlib.ticker that can help us adjust the coordinate axis; Matplotlib.pylab.date2num can help us convert date data.
Let's take the Shanghai Composite Index since September 65438+2008 as an example.
Draw it with mpl_finance first to see if everything is all right.
As you can see, all holidays, including weekends, will be displayed as blank here, which is very unfriendly to the continuity of our graphics, so we must remove them.
As you can see, the blank problem has been solved perfectly. Let me explain it here. Because matplotlib will understand the date data as continuous data, and the interval between continuous data is meaningful, even if there is no data on the non-trading day, it will still be reflected on the coordinate axis. How many consecutive non-trading days correspond to how many small squares on the coordinate axis, but there is no corresponding candle chart above these small squares.
Knowing its principle, we can prescribe the right medicine. We can pass the continuous and fixed interval data into the abscissa (date) to ensure that the drawing of the K-line chart is continuous first; Then generate a list with the correct date data. Then we can get the correct date according to the data on the coordinate axis and replace it with the label on the coordinate axis.
The format_date function above is for this purpose. Since we have generated continuous data starting from 0 for the date column, we can directly use it as an index to get the corresponding data from the actual date list. Here we will use the matplotlib.ticker.funcformatter () method, which allows us to specify a function to format axis labels. In this function, we need to accept the value and position of the coordinate axis and return the custom label.
Have you learned?
Of course, a complete K-line chart does not end here. Later, we will consider adding elements such as moving average and trading volume. Welcome interested students to pay attention!