Python stock quantitative trading (9) --- Use TA-Lib library to achieve a comparison chart of stock price trends

Every sky will send out the people of Sri Lanka, without the blessings, the wisdom will be first; when this wisdom is sent, the floating will be self-reliant, and the arrogant will be self-contained; if the establishment is gentle and good, the apocalypse is complete.

Preface

In many market stock trading software, each interface does not only display one indicator chart. Often the stock trading software will place all the indicator charts side by side to achieve a comparative effect. The advantage of this is that you can see the various indicators more intuitively. Indicators, combined with various indicators for analysis. Just like the previous blog post, a single indicator is often wrong and has no reference value.

Therefore, this blog post will use the TA-Lib library to implement a summary chart of comparison indicators of K-line, moving average, volume, KDJ, and MACD.

Calculate various indicators

There is no doubt that if we need to draw these indicators, the first thing we need to do is to obtain the basic parameters for drawing these indicators. Below, we will calculate one by one through the TA-Lib library.

(1) First of all, we need to obtain the data of a stock for half a year. Take Goertek as an example:

import akshare as ak

df = ak.stock_zh_a_daily(symbol="sz002241", start_date="20200701", end_date="20210130",
                                 adjust="qfq")
df.to_excel("歌尔股份year.xlsx")

(2) Next, calculate various moving averages, such as the commonly used daily moving averages of 10, 30, and 60.

import pandas as pd
import talib
df = pd.read_excel("歌尔股份year.xlsx")
df["SMA10"]=talib.SMA(df['close'],timeperiod=10)
df["SMA30"]=talib.SMA(df['close'],timeperiod=30)
df["SMA60"]=talib.SMA(df['close'],timeperiod=60)
df['SMA10'].fillna(method="bfill",inplace=True)
df['SMA30'].fillna(method="bfill",inplace=True)
df['SMA60'].fillna(method="bfill",inplace=True)

(3) Calculate trading volume

red_pred = np.where(df["close"] > df["open"], df["volume"], 0)
blue_pred = np.where(df["close"] < df["open"], df["volume"], 0)

(4) Calculate KDJ

df['K'], df['D'] = talib.STOCH(df['high'].values, df['low'].values, df['close'].values, fastk_period=9, slowk_period=3,
                               slowk_matype=0, slowd_period=3, slowd_matype=0)
df['K'].fillna(0,inplace=True)
df['D'].fillna(0,inplace=True)
df['J']=3*df['K']-2*df['D']

(5) Calculate MACD

dif, dea, bar = talib.MACD(df['close'].values, fastperiod=12, slowperiod=26, signalperiod=9)
dif[np.isnan(dif)], dea[np.isnan(dea)], bar[np.isnan(bar)] = 0, 0, 0
red_bar = np.where(bar > 0, 2 * bar, 0)
blue_bar = np.where(bar < 0, 2 * bar, 0)

Drawing

Here the K-line chart and the moving average chart are the top one. The volume is below the K-line chart, the KDJ chart is below the volume, and the MACD chart is below the KDJ chart, so the entire chart is 4 rows and 1 column. First, we create a canvas for drawing graphics:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import mpl_finance as mpf
import talib
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
fig, axes = plt.subplots(4, 1, sharex=True, figsize=(15, 10))
ax1, ax2, ax3, ax4 = axes.flatten()

(1) Draw K-line chart and moving average chart

mpf.candlestick2_ochl(ax1, df["open"], df["close"], df["high"], df["low"], width=0.6, colorup='r',
                      colordown='green',
                      alpha=1.0)
ax1.plot(np.arange(0, len(df)), df['SMA10'])  # 绘制10日均线
ax1.plot(np.arange(0, len(df)), df['SMA30'])  # 绘制30日均线
ax1.plot(np.arange(0, len(df)), df['SMA60'])  # 绘制60日均线
ax1.set(ylabel=u"K线图")

(2) Draw volume

ax2.bar(np.arange(0, len(df)), red_pred, facecolor="red")
ax2.bar(np.arange(0, len(df)), blue_pred, facecolor="blue")
ax2.set(ylabel=u"成交量")

(3) Drawing KDJ

ax3.plot(df["date"], df["K"], label ="K")
ax3.plot(df["date"], df["D"], label ="D")
ax3.plot(df["date"], df["J"], label ="J")
ax3.legend()
ax3.set(ylabel=u"KDJ")

(4) Draw MACD

ax4.plot(np.arange(0, len(df)), dif)
ax4.plot(np.arange(0, len(df)), dea)
ax4.bar(np.arange(0, len(df)), red_bar, color="red")
ax4.bar(np.arange(0, len(df)), blue_bar, color="blue")
ax4.set(ylabel=u"MACD")
ax1.xaxis.set_major_locator(ticker.MaxNLocator(20))
def format_date(x, pos=None):
    if x < 0 or x > len(df['date']) - 1:
        return ''
    return df['date'][int(x)]


ax1.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
plt.show()

After running, the displayed effect chart is as shown in the figure below:
Summary chart
Special note: Some small partners may be very confused, why are other stock softwares one-to-one correspondence, and why there are vacancies in front of your KDJ and MACD? In fact, there are some vacancies in the front of the real KDJ and MACD diagrams, and other software because of the long time span, the average user will not look at the data 10 years ago, and even fill in the values ​​by themselves according to the previous direct calculation method, and let the data one by one. Corresponding, but even if the data of the previous few days is complete, it is meaningless. Remember that any parameter with a moving average in the curve will cause a missing or invalid value in the previous part, which is unavoidable.

Guess you like

Origin blog.csdn.net/liyuanjinglyj/article/details/113430285