Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

    Pandas: Calculate and plot the Bollinger Bands for a Stock

    What is the Bollinger Bands?

    A Bollinger Band® is a technical analysis tool defined by a set of trendlines plotted two standard deviations (positively and negatively) away from a simple moving average (SMA) of a security’s price, but which can be adjusted to user preferences.

    https://www.investopedia.com/terms/b/bollingerbands.asp

    The Bollinger Bands are used to discover if a stock is oversold or overbought. It is called a mean reversion indicator, which measures how far a price swing will stretch before a counter impulse triggers a retracement.

    It is a lagging indicator, which is looking at historical background of the current price. Opposed to a leading indicator, which tries to where the price is heading.

    Step 1: Get some time series data on a stock

    In this tutorial we will use the Apple stock as example, which has ticker AAPL. You can change to any other stock of your interest by changing the ticker below. To find the ticker of your favorite company/stock you can use Yahoo! Finance ticker lookup.

    To get some time series of stock data we will use the Pandas-datareader library to collect it from Yahoo! Finance.

    import pandas_datareader as pdr
    import datetime as dt
    
    ticker = pdr.get_data_yahoo("AAPL", dt.datetime(2020, 1, 1), dt.datetime.now())[['Close', 'High', 'Low']]
    print(ticker)
    

    We will use the Close, High and Low columns to do the further calculations.

                     Close        High         Low
    Date                                          
    2020-01-02  300.350006  300.600006  295.190002
    2020-01-03  297.429993  300.579987  296.500000
    2020-01-06  299.799988  299.959991  292.750000
    2020-01-07  298.390015  300.899994  297.480011
    2020-01-08  303.190002  304.440002  297.160004
    ...                ...         ...         ...
    2020-08-06  455.609985  457.649994  439.190002
    2020-08-07  444.450012  454.700012  441.170013
    2020-08-10  450.910004  455.100006  440.000000
    2020-08-11  437.500000  449.929993  436.429993
    2020-08-12  452.040009  453.100006  441.190002
    

    Step 2: How are the Bollinger Bands calculated

    Luckily, we can refer to Investopedia.org to get the answer, which states that the Bollinger Bands are calculated as follows.

    BOLU=MA(TP,n)+mσ[TP,n]

    BOLD=MA(TP,n)−mσ[TP,n]

    Where BOLU is the Upper Bollinger Band and BOLD is Lower Bollinger Band. The MA is the Moving Average. The TP and σ are calculated as follows.

    TP (typical price)=(High+Low+Close)÷3

    σ[TP,n] = Standard Deviation over last n periods of TP​

    Where n is the number of days in smoothing period (typically 20), and m is the number of standard deviations (typically 2).

    Step 3: Calculate the Bollinger Bands

    This is straight forward. We start by calculating the typical price TP and then the standard deviation over the last 20 days (the typical value). Then we calculate the simple moving average of rolling over the last 20 days (the typical value). Then we have the values to calculate the upper and lower values of the Bolling Bands (BOLU and BOLD).

    ticker['TP'] = (ticker['Close'] + ticker['Low'] + ticker['High'])/3
    ticker['std'] = ticker['TP'].rolling(20).std(ddof=0)
    ticker['MA-TP'] = ticker['TP'].rolling(20).mean()
    ticker['BOLU'] = ticker['MA-TP'] + 2*ticker['std']
    ticker['BOLD'] = ticker['MA-TP'] - 2*ticker['std']
    print(ticker)
    

    Resulting in the following output.

    Date                                          
                     Close        High  ...        BOLU        BOLD
    Date                                ...                        
    2020-01-02  300.350006  300.600006  ...         NaN         NaN
    2020-01-03  297.429993  300.579987  ...         NaN         NaN
    2020-01-06  299.799988  299.959991  ...         NaN         NaN
    2020-01-07  298.390015  300.899994  ...         NaN         NaN
    2020-01-08  303.190002  304.440002  ...         NaN         NaN
    ...                ...         ...  ...         ...         ...
    2020-08-06  455.609985  457.649994  ...  445.784036  346.919631
    2020-08-07  444.450012  454.700012  ...  453.154374  346.012626
    2020-08-10  450.910004  455.100006  ...  459.958160  345.317173
    2020-08-11  437.500000  449.929993  ...  464.516981  346.461685
    2020-08-12  452.040009  453.100006  ...  469.891271  346.836730
    

    Note, that if you compare you results with Yahoo! Finance for Apple, there will be some small difference. The reason is, that they by default use TP to be closing price and not the average of the Close, Low and High. If you change TP to equal Close only, you will get the same figures as they do.

    Step 4: Plotting it on a graph

    Plotting the three lines is straight forward by using plot() on the DataFrame. Making an filled area with color between BOLU and BOLD can be achieved by using fill_between().

    This results in the full program to be.

    import pandas_datareader as pdr
    import datetime as dt
    import matplotlib.pyplot as plt
    
    ticker = pdr.get_data_yahoo("AAPL", dt.datetime(2020, 1, 1), dt.datetime.now())[['Close', 'High', 'Low']]
    # Boillinger band calculations
    ticker['TP'] = (ticker['Close'] + ticker['Low'] + ticker['High'])/3
    ticker['std'] = ticker['TP'].rolling(20).std(ddof=0)
    ticker['MA-TP'] = ticker['TP'].rolling(20).mean()
    ticker['BOLU'] = ticker['MA-TP'] + 2*ticker['std']
    ticker['BOLD'] = ticker['MA-TP'] - 2*ticker['std']
    ticker = ticker.dropna()
    print(ticker)
    # Plotting it all together
    ax = ticker[['Close', 'BOLU', 'BOLD']].plot(color=['blue', 'orange', 'yellow'])
    ax.fill_between(ticker.index, ticker['BOLD'], ticker['BOLU'], facecolor='orange', alpha=0.1)
    plt.show()
    

    Giving the following graph.

    Apple Stock Closing price with Bollinger Band indicators

    Step 5: How to use the Bollinger Band Indicator?

    If the stock price are continuously touching the upper Bollinger Band (BOLU) the market is thought to be overbought. While if the price continuously touches the lower Bollinger Band (BOLD) the market is thought to be oversold.

    The more volatile the market is, the wider the upper and lower band will be. Hence, it also indicates how volatile the market is at a given period.

    The volatility measured by the Bollinger Band is referred to as a squeeze when the upper and lower band are close. This is considered to be a sign that there will be more volatility in the coming future, which opens up for possible trading opportunities.

    A common misconception of the bands are that when the price outbreaks the the bounds of the upper and lower band, it is a trading signal. This is not the case.

    As with all trading indicators, it should not be used alone to make trading decisions.

    12% Investment Solution

    Would you like to get 12% in return of your investments?

    D. A. Carter promises and shows how his simple investment strategy will deliver that in the book The 12% Solution. The book shows how to test this statement by using backtesting.

    Did Carter find a strategy that will consistently beat the market?

    Actually, it is not that hard to use Python to validate his calculations. But we can do better than that. If you want to work smarter than traditional investors then continue to read here.

    Python for Finance: Unlock Financial Freedom and Build Your Dream Life

    Discover the key to financial freedom and secure your dream life with Python for Finance!

    Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.

    Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.

    Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.

    Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!

    Python for Finance a 21 hours course that teaches investing with Python.

    Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.

    “Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.

    Leave a Comment