当前位置:网站首页>Common skills for quantitative investment - indicators Chapter 3: detailed explanation of RSI indicators, their code implementation and drawing

Common skills for quantitative investment - indicators Chapter 3: detailed explanation of RSI indicators, their code implementation and drawing

2022-06-13 00:55:00 Your name is Yu yuezheng

Quantitative investment common skills List of articles

We have introduced three articles on quantitative investment mapping and two articles on the derivation and introduction of indicator classes , If you are interested, you can learn something about



Preface

Because this part is mainly to introduce the mathematical formula and calculation method of indicators , Learn more about them , There are many mathematical formulas and theoretical derivation process , I try to be as neat as possible , It's convenient for you to read . If you just want to see the code implementation, you can skip to the bottom “ Code implementation ” part

RSI In fact, the realization of indicators is also very easy to start , The calculation method is the same as before BOLL Indicators are similar , The core computing parts are easy , You can easily understand and use it after a little reading



You can pay attention to my GitHub:ExileSaber

Quantitative investment will be uploaded after the whole package is completed and debugged , Although there is no high level yet , But we can learn and improve together



One 、RSI Index Introduction

This part mainly refers to Baidu Encyclopedia Introduction to

Relative strength index , namely RSI indicators

The general principle of investment is , Investors' buying and selling behavior is the reflection of the comprehensive results of various factors , The change of the market ultimately depends on the relationship between supply and demand , and RSI The index is based on the principle of supply and demand balance , By measuring the percentage of the total increase of the stock price in the average of the total change of the stock price in a certain period , To assess the strength of the air force , Then prompt the specific operation .

The specific strategy introduction will be put in “ Quantitative investment common skills —— Decision making ” in



Two 、RSI The mathematical calculation process of indicators

RSI Indicators are simply calculation N Average daily closing increase and decrease

N Japan R S I = N Japan Inside closed disc rose picture all value N Japan Inside closed disc rose picture all value + N Japan Inside closed disc fall picture all value × 100 N Japan RSI = \frac{N Average daily closing gains }{N Average daily closing gains +N Average daily closing loss } \times100 N Japan RSI=N Japan Inside closed disc rose picture all value +N Japan Inside closed disc fall picture all value N Japan Inside closed disc rose picture all value ×100

By formula we can find , This indicator reflects N The average daily closing increase accounts for N The proportion of the average daily closing range . When stock prices continue to rise , When the upward force is large , The calculated value of this indicator is large and shows an upward trend ; When stock prices continue to fall , When the downward force is large , The calculated value of this indicator is small and shows a downward trend



3、 ... and 、RSI Code implementation and drawing of indicators

There are two parts to explain , One is the code of the main calculation part , While learning, you can also flexibly use it in other places . The other is the overall drawing part , Including candlelight chart and RSI indicators


The calculation method of the main calculation part

  • Up and down range calculation
    Series Object can be used p c t pct pct_ c h a n g e ( ) change() change() Function to quickly and concisely complete the calculation of rise and fall , Since the first data can not calculate the range of rise and fall , So this position is N A N NAN NAN value , have access to Series Object's d r o p n a ( ) dropna() dropna() Function to get rid of N A N NAN NAN value , And then convert it to ndarray Object to facilitate subsequent processing

The code implementation is as follows

rate = np.array(close.pct_change().dropna())  #  Calculate the range of rise and fall 
  • RSI Index calculation
    When calculating indicators, it is necessary to judge whether they are rising or falling , It also requires the moving average of the amplitude , So we write it as a normal cycle for easy reading
# window Is the moving average window size 
for i in range(len(rate) - window + 1):
    the_rate = rate[i:i+window]  #  Extract the data of each window 
    up_rate = the_rate[np.where(the_rate > 0)].mean()  #  Use np.where Function to determine whether it is up or down 
    down_rate = the_rate[np.where(the_rate < 0)].mean()
    rsi.append(100 * up_rate / (up_rate - down_rate))

Complete drawing code

For the sake of comprehensive drawing , We will “ Quantitative investment common skills —— Drawing 1: Draw the closing price curve of the stock and ochl Candlelight ” The function of drawing candle graph in p l o t plot plot_ o c h l ochl ochl Paste into this part of the code , We can complete the drawing of multiple graphs . In addition, in terms of data , We use another way to get data ( This method may not be effective every time , You need to find your own solution ). The complete code is as follows :

The missing library is directly pip install Can be installed

import numpy as np
import matplotlib.pyplot as plt
import pandas_datareader.data as web
import datetime
from matplotlib.dates import date2num
import mpl_finance as mpf

# ———————————————————— #
# ————  Default parameter settings  ———— #
# ———————————————————— #
__colorup__ = "red"
__colordown__ = "green"

window = 14

start = datetime.datetime(2017, 1, 1)
end = datetime.date.today()
stock = web.DataReader("600519.SS", "yahoo", start, end)  #  Select the data of Maotai stock 

# ———————————————————— #


def plot_ochl(data_df, axs=None, show=False):
    '''  Draw a candle  :param data_df:  Input data , The input data type currently only supports DataFrame type  :param axs:  Whether to draw on the subgraph  :param show:  Whether to display the image  :return: '''

    if axs is None:
        fig, ax = plt.subplots(figsize=(14, 7))
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        drawer = ax

    else:
        drawer = axs

    qutotes = []

    #  This part is modified according to the actual table situation 
    for index, (d, o, c, h, l) in enumerate(zip(data_df.index, data_df.Open, data_df.Close, data_df.High, data_df.Low)):
        d = date2num(d)  #  The date of the candle chart should be used matplotlib.finance.date2num To a unique numeric value 
        val = (d, o, c, h, l)  #  date , The opening quotation , The close , The highest , The lowest composition tuple object val
        qutotes.append(val)  #  Add val Join in qutotes

    #  Use mpf.candlestick_ochl Drawing candles ,ochl representative :open,close,high,low
    mpf.candlestick_ochl(drawer, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__)
    drawer.autoscale_view()
    drawer.xaxis_date()

    if show:
        plt.show()


def rsi(stock_df, window, axs=None, show=False):
    '''  Calculation RSI Index and plot  :param stock_df:  Input data , The input data type currently only supports DataFrame type  :param window:  Calculation RSI The window size of  :param axs:  Whether to draw on the subgraph  :param show:  Whether to display the image  :return: '''
    drawer = plt if axs is None else axs

    close = stock_df['Close']

    rate = np.array(close.pct_change().dropna())  #  Calculate the range of rise and fall 

    rsi = []

    for i in range(len(rate) - window + 1):
        the_rate = rate[i:i+window]  #  Extract the data of each window 
        up_rate = the_rate[np.where(the_rate > 0)].mean()  #  Use np.where Function to determine whether it is up or down 
        down_rate = the_rate[np.where(the_rate < 0)].mean()
        rsi.append(100 * up_rate / (up_rate - down_rate))

    drawer.plot(stock.index, 30 * np.ones(len(stock.index)), 'g--', label='30', alpha=0.6)
    drawer.plot(stock.index, 50 * np.ones(len(stock.index)), 'y-.', label='50', alpha=0.5)
    drawer.plot(stock.index, 70 * np.ones(len(stock.index)), 'g--', label='70', alpha=0.6)
    drawer.plot(stock.index[window:], rsi, label='RSI', alpha=0.8)

    drawer.legend()

    if show:
        plt.show()


fig, ax = plt.subplots(2, 1, figsize=(14, 7))
plot_ochl(data_df=stock, axs=ax[0])

rsi(stock, window, axs=ax[1], show=True)

The final effect is as follows :
 Insert picture description here



Four 、RSI General research and judgment criteria for indicators

This part mainly introduces several common research criteria , The actual situation is not necessarily in line with the research criteria

Mainly referring to the introduction of Baidu Encyclopedia , Put in the last for you to learn the code, you can also learn some RSI The standard of index research and judgment

Single RSI Basic application of indicators

It is easy to know from the formula , 0 ⪕ R S I ⪕ 100 0 \eqslantless RSI \eqslantless 100 0RSI100, R S I = 50 RSI=50 RSI=50 It is the dividing point between the strong market and the weak market

  1. generally speaking ,RSI A U-turn down signals a sell ,RSI A U-turn up is a buy signal . However, the application should start from the judgment of the overall situation
  2. RSI Of M Shape trend is a common top shape in overbought areas ;W Shape trend is a common bottoming pattern in oversold areas . At this time , Often visible RSI The trend deviates from the price trend . therefore , Deviation is also a sign of buying and selling
  3. RSI Go from bottom to top , A trough higher than a trough constitutes the rising support line ;RSI Go from top to bottom , A wave top lower than a wave top forms a downward pressure line . Falling below the support line is a selling signal , Crossing the pressure line is a buying signal
  4. RSI Put on 50 The dividing line is the buy signal , Lower broken 50 The dividing line is the sell signal
  5. N Japan RSI Of N Values are often taken as 5~14 Japan .N The higher the value, the stronger the sense of trend , But there is a tendency of delayed response , It is called slow line ;N Smaller values are more sensitive to changes , But it's easy to feel erratic , It's called a fast line . therefore , Compare the slow line with the fast line , If the two lines go up together , The upward trend is strong ; If the two lines go down together , The decline is strong ; If the fast line crosses the slow line, it is a buy signal ; If the fast line crosses the slow line, it is a sell signal
  6. because RSI Design reasons ,RSI After entering the overbought area or oversold area , Even if the market trend fluctuates greatly , and RSI The rate of change gradually slows down , The wave amplitude is getting smaller and smaller , That is, the so-called passivation problem occurs . Especially when it continues to rise or fall sharply , Easy to buy or sell “ act with undue haste ” Regret of . The solution to this problem , Just RSI The indicator itself is the defining indicator to adjust the overbought area or oversold area , Such as 90 above 、10 following ; The second is to increase N The value of

length RSI General research, judgment and marking of indicators

short-term RSI It refers to those with relatively small parameters RSI, long-term RSI It refers to those with relatively long parameters RSI. such as ,6 Japan RSI and 12 Japan RSI in ,6 Japan RSI Short term RSI,12 Japan RSI Long term RSI. Long term and short term RSI The intersection of lines can be used as a method for us to study and judge the market

  1. When short RSI> long-term RSI when , The market is a long market
  2. When short RSI< long-term RSI when , The market is short
  3. When short RSI The line breaks through the long-term in the low position RSI Line , Is the buying signal of the market
  4. When short RSI The line breaks through the long term at a high level RSI Line , It is the selling signal of the market

Indicator defect

  1. RSI The time parameters of indicators are different , The result will be different
    In theory , Shorter period RSI Although the indicators are sensitive , But there are more rapid shocks , Poor reliability ; Longer period RSI Although the signal is reliable , But the sensitivity of the index is not enough , Slow response , Therefore, there is often the phenomenon of missing good trading opportunities
    because RSI It's calculated by the closing price , If the market fluctuates greatly that day , When the upper and lower hatches are long ,RSI It is impossible to accurately reflect the changes of the market at this time
  2. Overbought 、 The indicator passivation caused by oversold is easy to send wrong operation signals
    stay " bull market " and " bear market " In the middle of the process ,RSI The value rises to 90 Above or below 10 The following situations happen from time to time , At this time, fuzzy and misleading information will appear after the index is passivated , If you operate according to this indicator, you may make mistakes , Miss profit opportunities or enter the market earlier and get stuck
  3. RSI Index and stock price " deviation " The trend often lags behind
    One side , The market has reversed , But the index is " deviation " The signal may be delayed ; On the other hand , Under the influence of various random factors , Sometimes " deviation " After the phenomenon appeared several times, the market really began to reverse , At the same time, we are studying and judging the indicators " deviation " Phenomenon , True reversal corresponds to " deviation " The number of occurrences is inconclusive , once 、 Two or three deviations have the possibility of trend change , In practice, it is difficult to confirm
  4. When RSI Values in 50 This index often loses reference value when it fluctuates nearby
    generally speaking ,RSI Values in 40 To 60 The role of research and judgment is not big . according to RSI Application principle of , When RSI from 50 Breakthrough upward below 50 The dividing line means that the stock price has strengthened ;RSI from 50 Above and below 50 The dividing line means that the share price has weakened

In practice, if Reduce this shortcoming , When the price changes greatly and changes frequently , take RSI Lower the parameter setting ; When the price change range is small and the rise and fall changes are not frequent , take RSI Set the parameter larger

原网站

版权声明
本文为[Your name is Yu yuezheng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280557382924.html