Python uses RSI, MACD and 20 moving average charts to analyze the short-term price trend of a company's stock

This article selects the closing price of Hengrui Pharmaceutical (stock code: 'sh.600276') from 2023-05-01 to 2023-07-01, using RSI (relative strength index), MACD (moving average convergence/ Divergence indicator) and the 20-day moving average chart to analyze the short-term trend of a company's stock closing price. These technical indicators can provide important information about market price movements and momentum, helping investors better understand stock price fluctuations.

(To obtain the source code ipynb file, you can follow gzh'finance melatonin' to reply to the corresponding keywords. More empirical cases and models can also be obtained)

Crawl Hengrui Pharmaceutical’s stock price data

At the beginning, we need to crawl the closing price of Hengrui Pharmaceutical from 2023-05-01 to 2023-07-01. The Python code is as follows:

# 获取股票数据代码
import baostock as bs
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, date

# 登陆系统
lg = bs.login()
code = 'sh.600276' 
start = '2022-07-01'
end = '2023-07-01'

# 获取指数基金指数历史数据

hs300_price = bs.query_history_k_data_plus(code, "date,code,open,high,low,close,preclose,pctChg",
              start_date=start, end_date=end, frequency="d")
# 整合为DataFrame格式
data_list = []
while (hs300_price.error_code == '0') & hs300_price.next():
    data_list.append(hs300_price.get_row_data())
hs300 = pd.DataFrame(data_list, columns=hs300_price.fields)
hs300.to_csv('600276.csv')

View the generated data by calling df = pd.read_csv('600276.csv'):

1. Relative Strength Index (RSI)

1.1 Introduction to RSI

RSI is a technical indicator of flat price momentum that typically ranges from 0 to 100. It is used to determine whether a stock or other asset is overbought or oversold.

Overbought: A market is considered overbought when market prices rise too quickly or too much, causing the price of a stock or other asset to be higher than its reasonable value. In this case, market participants generally believe that the asset is priced on the high side and may be at risk of a correction or decline. Being overbought doesn't mean a stock price is bound to drop immediately, but it can be a potential signal of a price reversal.

Oversold: When market prices fall too fast or too much, causing the price of a stock or other asset to be lower than its reasonable value, the market is considered to be oversold. In this case, market participants generally believe that the asset is underpriced and may face opportunities for a rebound or rise. Being oversold does not mean that the stock price is bound to rise immediately, but it can be a potential signal of a price reversal.

An RSI value of 70 may indicate overbought, meaning the price may pull back. RSI values ​​below 30 may indicate oversold conditions, suggesting that prices may rebound.

1.2 Specific calculation formula of RSI

(1) Calculate the average gain (AG): Take the sum of the gains within N days, and then divide it by N, where N is the calculation period of RSI (usually 14).

AG = (gain1 + gain2 + ... + gainN) / N

Calculate the average loss (AL): take the sum of the declines within N days, and then divide it by N, where N is the calculation period of RSI (usually 14).

AL = (loss1 + loss2 + ... + lossN) / N

(2) Calculate the value of RS (Relative Strength): RS = AG / AL

(3)RSI = 100 - (100 / (1 + RS))

In RSI calculation, N days are the trading day data before the selected day. Specifically, the calculation period of RSI is N days, and the RSI value of each day is calculated based on the price change data within these N days.

Suppose we have stock price data for a period of time, and we want to calculate the RSI value for 14 days. Then the RSI value for the 15th day is calculated based on the price change data of the previous 14 days (day 2 to day 15). . The RSI value on day 16 is calculated based on the price change data of the previous 15 days (day 3 to day 16), and so on.

The calculation period of RSI is a fixed value. Commonly used calculation periods are 14 days, 9 days or other different days, depending on personal preferences and analysis needs. You can choose the appropriate RSI calculation period according to your own needs.

1.3 Hengrui Pharmaceutical’s RSI within one year

According to the above calculation formula, the RSI of Hengrui Pharmaceutical from 2022-7-1 to 2023-7-1 is (only part of the data is shown due to space limitations)

This series of data are all RSI values ​​of the disk. The length of the disk is the same as the length of the input price data, and the value at each position is the RSI value for the period. When the RSI value exceeds 70, it may mean that the market is overbought, and when the RSI value is below 30, it may mean that the market is oversold. These signals can guide decisions to buy or sell.

price = df["close"]

def calculate_rsi(prices, period=14):
    deltas = np.diff(prices)
    seed = deltas[:period + 1]
    up = seed[seed >= 0].sum() / period
    down = -seed[seed < 0].sum() / period
    rs = up / down
    rsi = np.zeros_like(prices)
    rsi[:period] = 100. - 100. / (1. + rs)

    for i in range(period, len(prices)):
        delta = deltas[i - 1]  # since the diff is 1 shorter
        if delta > 0:
            upval = delta
            downval = 0.
        else:
            upval = 0.
            downval = -delta

        up = (up * (period - 1) + upval) / period
        down = (down * (period - 1) + downval) / period
        rs = up / down
        rsi[i] = 100. - 100. / (1. + rs)

    return rsi

# 示例用法
import numpy as np

# 假设这是你的价格数据,这里使用一个随机生成的示例数据
prices = np.array(price)

rsi_values = calculate_rsi(prices)
print(rsi_values)

 Make a column chart of rsi_values, and the parts exceeding 70 are marked in red, and the parts less than 30 are marked in green:

plt.figure(figsize=(12, 6))
plt.bar(range(len(rsi_values)), rsi_values)

# 设置柱形颜色
for i in range(len(rsi_values)):
    if rsi_values[i] > 70:
        plt.gca().get_children()[i].set_facecolor('red')
    elif rsi_values[i] < 30:
        plt.gca().get_children()[i].set_facecolor('green')

plt.xlabel('Days')
plt.ylabel('RSI Values')
plt.title('RSI Values with Red Bars > 70 and Green Bars < 30')
plt.show()

2. Moving Average Convergence/Divergence Indicator (MACD)

2.1 Introduction to MACD

MACD is a trend following indicator calculated by calculating the variance between two moving averages (usually the 12-day and 26-day exponential moving averages). Also includes a signal line (usually the 9-day moving average). Positive MACD values ​​represent the short-term moving average versus the long-term moving average and may indicate that a stock is in an uptrend. Conversely, negative values ​​may indicate a downtrend.

2.2 Calculation steps of MACD

(1) Calculate the fast (short-term) moving average (EMA12) and the slow (long-term) moving average (EMA26). EMA is an exponential moving average.

The initial value of EMA is the simple moving average (SMA) of the price data within the first calculation period (12 or 26). A simple moving average takes the sum of all prices during the period and divides it by the number of days in the calculation period.

Next, the value of each subsequent EMA is calculated based on the previous period's EMA value and current price data. Calculated as follows:

Current EMA value = (current price - previous EMA value) * smoothing coefficient + previous EMA value

Among them, smoothing coefficient = 2 / (calculation period + 1)

(2) Calculate the DIF line, which is the difference between fast EMA and slow EMA: DIF = EMA12 - EMA26.

(3) Calculate the signal line (DEA), usually the 9-day (or other period) EMA of DIF.

(4) Calculate the MACD Histogram, that is, the difference between the DIF line and the signal line: MACD Histogram = DIF - DEA.

2.3 Hengrui Medicine’s MACD chart and analysis

MACD indicator charts usually include price curves, DIF lines, signal lines and MACD histograms.

DIF line (red line): the difference between fast EMA and slow EMA. When the DIF line is above the zero axis, it means that the short-term moving average is stronger than the long-term moving average and may move the price. On the contrary, when the DIF line is below the zero axis, it means that the short-term moving average is relatively unfavorable to the long-term moving average, and the price may fall.

Signal line (green line): Usually the 9-day EMA of the DIF line. The signal line is a smoothed version of the DIF line and helps filter out short-term price fluctuations. When the DIF line breaks through the signal line from below, it may be a buy signal. On the contrary, when the DIF line breaks through the signal line from above, it may be a sell signal.

MACD histogram (orange histogram): the difference between the DIF line and the signal line. When the MACD histogram is above the zero axis, it means that the fast moving average is stronger than the slow moving average, and the market may show an upward trend. On the contrary, when the MACD histogram is below the zero axis, it means that the fast moving average is weaker than the slow moving average, and the market may be in a downward trend.

There are several parts of the picture that need attention:

(1) Crossing of DIF line and signal line: When the DIF line breaks through the signal line from below, it may be a buy signal. On the other hand, when the DIF line breaks above the signal line from above, it may be a sell signal.

(2) The shape of the MACD histogram: Observe the height of the MACD histogram. When the MACD histogram gradually increases, it means that the fast moving average is stronger than the slow moving average, and the market may be on an upward trend. On the contrary, when the MACD histogram gradually shrinks, it means that the fast moving average is weaker than the slow moving average, and the market may be in a downward trend.

import numpy as np

def calculate_ema(data, window):
    # 计算指数移动平均线
    weights = np.exp(np.linspace(-1., 0., window))
    weights /= weights.sum()
    ema = np.convolve(data, weights, mode='full')[:len(data)]
    ema[:window] = ema[window]
    return ema

def calculate_macd(prices, short_window=12, long_window=26, signal_window=9):
    # 计算MACD指标
    short_ema = calculate_ema(prices, short_window)
    long_ema = calculate_ema(prices, long_window)

    dif = short_ema - long_ema
    signal_line = calculate_ema(dif, signal_window)

    macd_histogram = dif - signal_line

    return dif, signal_line, macd_histogram

# 示例用法
import matplotlib.pyplot as plt

# 假设这是你的价格数据,这里使用一个随机生成的示例数据
prices = price

dif, signal_line, macd_histogram = calculate_macd(prices)

plt.figure(figsize=(12, 6))
plt.plot(prices, label='Prices', color='blue')
plt.legend()
plt.show()

plt.figure(figsize=(12, 6))
plt.plot(dif, label='DIF', color='red')
plt.plot(signal_line, label='Signal Line', color='green')
plt.bar(range(len(prices)), macd_histogram, label='MACD Histogram', color='orange')
plt.legend()
plt.show()

3.20-day simple moving average (20 moving average)

The 20-day simple moving average refers to the matching of closing prices over the past 20 trading days. It is used to smooth price data and often initiate support and braking levels. When the price is rising and above the 20-day moving average, it may indicate that the stock is trending upward. Conversely, when the price falls and is below the 20-day moving average, it may indicate that the stock is trending downward.

The value of the 20-day moving average was calculated using the calculate_moving_average function. Then use the Matplotlib library to plot different price curves and 20-day moving average curves. The price curve above is shown in blue, with the 20-day moving average in red.

Price curve (blue line): represents the trend of market prices. The fluctuations and changes in the price curve reflect the price trend of the asset, and the rising and falling trends of the price can be seen.

The 20-day EMA (red line) represents the 20-day moving average price. The function of the moving average is to smooth out price fluctuations and reflect longer-term price trends. When the price is above the 20-day moving average, it may indicate that the market is in an upward trend; when the price is below the 20-day moving average, it may indicate that the market is in a downward trend.

When the price curve crosses the 20-day moving average, it may indicate a change in the price trend. When the price curve crosses the 20-day moving average from below, it may be a buy signal, indicating that the market may rise; conversely, when the price ellipse crosses the 20-day moving average from above, it may be a sell signal, indicating that the market may rise. fell.

import numpy as np
import matplotlib.pyplot as plt

def calculate_moving_average(prices, window=20):
    # 计算移动平均线
    return np.convolve(prices, np.ones(window)/window, mode='same')

# 示例用法
# 假设这是你的价格数据,这里使用一个随机生成的示例数据
prices = price

# 计算20日均线
ma_20 = calculate_moving_average(prices, window=20)

# 绘制价格曲线和20日均线曲线
plt.figure(figsize=(12, 6))
plt.plot(prices, label='Prices', color='blue')
plt.plot(ma_20, label='20-day Moving Average', color='red')
plt.legend()
plt.show()

(To obtain the source code ipynb file, you can follow gzh'finance melatonin' to reply to the corresponding keywords. More empirical cases and models can also be obtained)

Guess you like

Origin blog.csdn.net/celiaweiwei/article/details/132078888