[Quantitative Analysis] Python Bollinger Concept

1. Description

        Bollinger Bands (BOLL) uses statistical principles to find the standard deviation of the stock price and its confidence interval, thereby determining the fluctuation range and future trend of the stock price. It uses the wave bands to show the safe high and low price of the stock price, so it is also called Bollinger Bands.

2. Basic concepts of Bollinger Bands

        Bollinger Bands (BOLL) uses statistical principles to find the standard deviation of the stock price and its confidence interval, thereby determining the fluctuation range and future trend of the stock price. It uses the wave bands to show the safe high and low price of the stock price, so it is also called Bollinger Bands.

        Bollinger Bands are a statistical chart that characterizes the price and volatility of an asset over time.

  1. The middle band is the N-period simple moving average (SMA( N ))
  2.  The upper trajectory at K is multiplied by the standard deviation of the NN period above the middle band . SMA( N )+( K ×Standard Deviation (N ))
  3.  The lower trajectory at K is multiplied by the standard deviation of the NN period below the middle band . SMA( N )−( K ×standard deviation( N ))
Diagram of Bollinger Bands

 

        The width of the band indicates the volatility of the asset. Narrow bands indicate low volatility, while wide bands indicate high volatility.

volatility indicator

 

        Touch the upper track:

  • This may indicate that the asset is overbought.
  • However, simply hitting or exceeding the cap is not a sell signal in and of itself. Some traders believe that a close outside the range is more important.
  • In a strong uptrend, price can track and remain overbought for an extended period of time.

        Touch the lower rail:

  • This may indicate that the asset is oversold.
  • As with the upper band, hitting or breaking below the lower band is not always a buy signal. Prices can go down in a strong downtrend.
  • A more reliable buy signal might be for the price to move back inside the Bollinger Bands after a brief move below.

        Bollinger Bands Squeeze:

  • Squeezes indicate periods of low volatility, which traders consider to be a potential indicator of increased volatility and possible trading opportunities in the future.
  • The end of a squeeze, marked by a further separation of the bands, may signal the beginning of a new trend. The direction of the band expansion can often be the direction of the upcoming trend.

        Bollinger rebound:

  • Price is trending back towards the middle of the Bollinger Bands. This can be used as a mean reversion strategy.
  • When the price rebounds from the lower band and moves towards the middle band, it can be interpreted as a potential buy signal.
  • On the contrary, when it falls from the upper band to the middle band, it can be regarded as a potential sell signal.

        Double bottom and double top:

  • A double bottom is a bullish reversal pattern in which price forms two lows roughly at the same level. If the second low breaks below the Bollinger Bands but then closes inside, it could signal a potential bullish reversal.
  • In contrast, a double top is a bearish reversal pattern. If price forms two peaks at roughly the same level, and the second peak is above the upper Bollinger Band, but then moves back inside, it could be a potential bearish reversal signal.

 

 

        Crucially, while Bollinger Bands can give these underlying signals, no single tool should be used in isolation . Combining Bollinger Bands with other technical analysis tools such as the RSI (relative strength index), MACD, or support and resistance levels can provide a stronger signal.

3. python code

Let's use .yfinance

import ta
import talib
import yfinance as yf
import mplfinance as mpf
import matplotlib.pyplot as plt
from datetime import datetime, timedelta

ticker = "TSLA"

end_date = datetime.today().strftime('%Y-%m-%d')
start_date = (datetime.today() - timedelta(days=700)).strftime('%Y-%m-%d')

data = yf.download(ticker, start=start_date, end=end_date, interval='1h')

mpf.plot(data, type='candle', volume=True, style='yahoo')

Candlesticks. Image by the author.

Let’s use library to calculate the Bollinger Bands.ta

indicator_bb = ta.volatility.BollingerBands(close=data["Close"], 
                                            window=20, window_dev=2)
data['bb_bbm'] = indicator_bb.bollinger_mavg()   # Middle Band
data['bb_bbh'] = indicator_bb.bollinger_hband()  # Upper Band
data['bb_bbl'] = indicator_bb.bollinger_lband()  # Lower Band
data.tail()

The following are the parameters of this class:BollingerBands

  • close (pd.Series)is a series of closing prices for an asset.
  • window (int, default=20)Is the number of periods taken into account for simple moving average (SMA) and standard deviation calculations. This corresponds to N in the Bollinger Bands formula  . The default value is 20, which is a common period for Bollinger Bands.
  • window_dev (int, default=2)is the number of periods considered in the standard deviation calculation.
plt.figure(figsize=(14,7))
plt.plot(data["Close"], label='Tesla Prices', color='blue')
plt.plot(data['bb_bbh'], label='Upper Band', color='red')
plt.plot(data['bb_bbm'], label='Middle Band (SMA)', color='green')
plt.plot(data['bb_bbl'], label='Lower Band', color='red')
plt.title('Bollinger Bands for Tesla Prices')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.show()

Bollinger Bands for Tesla price. Image provided by the author.

4. The trajectory of Bollinger Bands

Bollinger Bands consists of three lines, each line has three trajectories: upper, middle and lower, which can form thousands of changes in actual trading.

1. When the Bollinger Bands move upward at the same time, it indicates that the stock price is strong, and it is suitable to hold stocks and wait for the increase; when the Bollinger Bands move downward at the same time, it means that the stock price is weak, and it is suitable to sell on highs; when the Bollinger Bands remain flat at the same time, it is a consolidation range, and it is necessary to follow the trend of the moving average. , make judgments based on transaction volume.

The weak downward touch plate concept and the strong upward limit concept

2. The stock price rises and after opening the consolidation range, the upper rail begins to move downward, while the middle rail and the lower rail remain upward, indicating that the stock price has entered the consolidation stage.

The upper track of the Northeast Concept Sector is downward, the middle track and the lower track are upward, and it has entered the stock price consolidation stage.

3. When the upper rail goes up and the lower rail goes down, you need to make a judgment based on the direction of the middle rail. The upper rail is upward, the middle rail and the lower rail are downward at the same time, and the short-term stock price will experience a round of decline; the upper rail and the middle rail are upward, and the lower rail is downward, and the short-term stock price will experience a round of rise. The range of rise and fall can be calculated by laughing.

For the 5G concept sector, the upper and middle rails are currently upward, while the lower rail is downward, and it is beginning to strengthen.

Bollinger Bands opening

According to experience, judgment can usually be made directly based on the opening of Bollinger Bands. There are three types of openings of Bollinger Bands: open horn, tight horn and closed horn.

1. Open speakers are caused by the divergence of the upper rail and lower rail trajectories. They usually occur after a long period of consolidation at the bottom, and the channel interval is extremely small. As the trading volume is released, the stock price soars. The upper track rises with the stock price, and the lower track drops sharply after subtracting the standard deviation.

The occurrence of open horns is usually accompanied by a long bottom plate and a surge in trading volume. At the same time, the open trumpet also needs the K line to break through the upper rail line and the stock price to stand above the medium and long-term moving average to assist judgment.

In the Huawei concept sector, trading volume was released on June 11, the K-line broke through the upper track, and the stock price stood above the moving average.

2. The closing horn occurs when the stock price changes downward after the stock price rises. The relative trend between the Bollinger Band and the lower track indicates that the stock price will fall significantly. The key to establishing the closing horn is when the upper track is downward and the stock price falls below the short-term moving average.

The Shanghai Composite 180 Index began to rise at the beginning of the year. On April 22, the upper track began to move downward. On April 23, the stock price fell below the moving average.

3. After falling, as risks are released, the standard deviation decreases, and the upper and lower rails gradually move closer to the middle rail, indicating that the stock price will be in a long-term consolidation. As the opening narrows, the probability of a shortfall increases, and the stock price will choose one side to make a breakthrough.

Limit width indicator (WIDTH), WIDTH = (Bollinger upper limit - Bollinger lower limit) / Bollinger stock price average, used to calculate the tight limit. When WIDTH is less than 0.1, the probability of a short-term trading is extremely high.

The Chinese prefix concept sector consolidated after falling. The current limit width indicator (WIDTH) is equal to 0.05, and the market may change at any time.

5. Bollinger Bands and K-Line

1. If the K line breaks through the middle track, it indicates that the stock price will rise; if it breaks through the upper track, it indicates that the stock price will rise sharply. The K-line breaks through the upper rail and continues upward, and the upper rail, middle rail, and lower rail move upward at the same time, indicating the strong characteristics of the stock price, and holders can hold shares to wait for the rise.

Huayang International's strong rise, the K line broke through the middle track and the upper track and continued to run in the direction of the upper track. Investors need to pay attention to the support of the upper and middle rails.

2. If the K line runs downward above the upper rail and breaks through the upper rail, it means that the strong market is about to end; if the K line breaks through the upper rail, and at the same time the upper rail, middle rail, and lower rail run downward at the same time, the short-term trend of the stock price is not optimistic; K line When the K line breaks through the middle track from top to bottom, it means that the strong market has ended and the stock price has formed a downward trend; when the K line breaks through the lower track and continues downward, the stock price is in an extremely weak position; when the stock price stabilizes at the lower track, it means that it has stabilized and stopped falling in the short term. The K line breaks through the upper rail from below the lower rail, indicating that the market is picking up;

3. When the K line moves above the middle rail, it indicates that the stock price is rising strongly; when the K line moves below the middle rail, it indicates that the stock price is weakly falling.

6. Summary

        The function of the Bollinger Bands indicator is to predict the stock price trend and serve as a reference for stock selection. It has strong guidance for band operations. However, it will lose its effect or produce deviations when the stock price consolidates.

References

Notes on stocks

Okan Jernigan

·

 

Guess you like

Origin blog.csdn.net/gongdiwudu/article/details/130978088