Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python for Finance Cookbook – Second Edition

You're reading from   Python for Finance Cookbook – Second Edition Over 80 powerful recipes for effective financial data analysis

Arrow left icon
Product type Paperback
Published in Dec 2022
Publisher Packt
ISBN-13 9781803243191
Length 740 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Eryk Lewinson Eryk Lewinson
Author Profile Icon Eryk Lewinson
Eryk Lewinson
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. Acquiring Financial Data 2. Data Preprocessing FREE CHAPTER 3. Visualizing Financial Time Series 4. Exploring Financial Time Series Data 5. Technical Analysis and Building Interactive Dashboards 6. Time Series Analysis and Forecasting 7. Machine Learning-Based Approaches to Time Series Forecasting 8. Multi-Factor Models 9. Modeling Volatility with GARCH Class Models 10. Monte Carlo Simulations in Finance 11. Asset Allocation 12. Backtesting Trading Strategies 13. Applied Machine Learning: Identifying Credit Default 14. Advanced Concepts for Machine Learning Projects 15. Deep Learning in Finance 16. Other Books You May Enjoy
17. Index

Calculating the most popular technical indicators

There are hundreds of different technical indicators that traders use for making decisions on whether to enter or exit a position. In this recipe, we will learn how to easily calculate a few of those indicators using the TA-Lib library, which is the most popular library for such a task. We start with a brief introduction of a few of the selected indicators.

Bollinger bands are a statistical method, used for deriving information about the prices and volatility of a certain asset over time. To obtain the Bollinger bands, we need to calculate the moving average and standard deviation of the time series (prices), using a specified window (typically, 20 days). Then, we set the upper/lower bands at K times (typically, 2) the moving standard deviation above/below the moving average. The interpretation of the bands is quite simple: the bands widen with an increase in volatility and contract with a decrease in volatility.

The default setting of using 2 standard deviations for the bands is connected to the (empirically incorrect) assumption about the normality of returns. Under the Gaussian distribution, we would assume that when using 2 standard deviations, 95% of returns would fall within the bands.

The relative strength index (RSI) is an indicator that uses the closing prices of an asset to identify oversold/overbought conditions. Most commonly, the RSI is calculated using a 14-day period and is measured on a scale from 0 to 100 (it is an oscillator). Traders usually buy an asset when it is oversold (if the RSI is below 30) and sell when it is overbought (if the RSI is above 70). More extreme high/low levels, such as 80–20, are used less frequently and, at the same time, imply stronger momentum.

The last considered indicator is the moving average convergence divergence (MACD). It is a momentum indicator showing the relationship between two exponential moving averages (EMA) of a given asset’s price, most commonly 26- and 12-day ones. The MACD line is the difference between the fast (short period) and slow (long period) EMAs. Lastly, we calculate the MACD signal line as a 9-day EMA of the MACD line. Traders can use the crossover of the lines as a trading signal. For example, it can be considered a buy signal when the MACD line crosses the signal line from below.

Naturally, most of the indicators are not used in isolation and traders look at multiple signals before making a decision. Also, all of the indicators can be tuned further (by changing their parameters) depending on the specific goal. We will cover backtesting trading strategies based on technical indicators in another chapter.

How to do it…

Execute the following steps to calculate some of the most popular technical indicators using IBM’s stock prices from 2020:

  1. Import the libraries:
    import pandas as pd
    import yfinance as yf
    import talib
    

    TA-Lib is not like most Python libraries and it has a bit of a different installation process. For more information on how to do it, please refer to the GitHub repository provided in the See also section.

  1. Download IBM’s stock prices from 2020:
    df = yf.download("IBM",
                     start="2020-01-01",
                     end="2020-12-31",
                     progress=False,
                     auto_adjust=True)
    
  2. Calculate and plot the Simple Moving Average (SMA):
    df["sma_20"] = talib.SMA(df["Close"], timeperiod=20)
    (
        df[["Close", "sma_20"]]
        .plot(title="20-day Simple Moving Average (SMA)")
    )
    

    Running the snippet generates the following plot:

Figure 5.1: IBM’s close price and the 20-day SMA

  1. Calculate and plot the Bollinger bands:
    df["bb_up"], df["bb_mid"], df["bb_low"] = talib.BBANDS(df["Close"])
     
    fig, ax = plt.subplots()
     
    (
        df.loc[:, ["Close", "bb_up", "bb_mid", "bb_low"]]
        .plot(ax=ax, title="Bollinger Bands")
    )
     
    ax.fill_between(df.index, df["bb_low"], df["bb_up"], 
                    color="gray", 
                    alpha=.4)
    

    Running the snippet generates the following plot:

    Figure 5.2: IBM’s close price and the Bollinger bands

  1. Calculate and plot the RSI:
    df["rsi"] = talib.RSI(df["Close"])
    fig, ax = plt.subplots()
    df["rsi"].plot(ax=ax,
                   title="Relative Strength Index (RSI)")
    ax.hlines(y=30,
              xmin=df.index.min(),
              xmax=df.index.max(),
              color="red")
    ax.hlines(y=70,
              xmin=df.index.min(),
              xmax=df.index.max(),
              color="red")
    plt.show()
    

    Running the snippet generates the following plot:

Figure 5.3: The RSI calculated using IBM’s close prices

  1. Calculate and plot the MACD:
    df["macd"], df["macdsignal"], df["macdhist"] = talib.MACD(
        df["Close"], fastperiod=12, slowperiod=26, signalperiod=9
    )
    fig, ax = plt.subplots(2, 1, sharex=True)
    (
        df[["macd", "macdsignal"]].
        plot(ax=ax[0],
             title="Moving Average Convergence Divergence (MACD)")
    )
    ax[1].bar(df.index, df["macdhist"].values, label="macd_hist")
    ax[1].legend()
    

    Running the snippet generates the following plot:

Figure 5.4: The MACD calculated using IBM’s close prices

So far, we have calculated the technical indicators and plotted them. In the next chapters, we will spend more time on their implications and building trading strategies on their basis.

How it works…

After importing the libraries, we downloaded IBM’s stock prices from 2020.

In Step 3, we calculated the 20-day simple moving average using the SMA function. Naturally, we could have calculated the same indicator using the rolling method of a pandas DataFrame.

In Step 4, we calculated the Bollinger bands. The BBANDS function returns three objects (the upper and lower thresholds and the moving average), which we assigned to different columns of our DataFrame.

In the next step, we calculated the RSI using the default settings. We plotted the indicator, together with two horizontal lines (created using ax.hlines) indicating the popular decision-making thresholds.

In the last step, we calculated the MACD, also using the default number of periods for the EMAs. The MACD function also returned three objects, the MACD, the signal line, and the MACD histogram, which is effectively the difference between the first two elements. We plotted them on separate plots, as is most commonly done on trading platforms.

There’s more…

TA-Lib is a great library and the gold standard when it comes to calculating technical indicators. However, there are also alternative libraries out there, which are gaining traction. One of them is called ta. Compared to TA-Lib, which is a wrapper around a C++ library, ta is written using pandas, which makes exploring the code base much easier.

While it does not offer as extensive functionalities as TA-Lib, one of its unique features is that it can calculate all of the available 30+ indicators in a single line of code. That can definitely be useful in situations in which we want to calculate a lot of potential features for a machine learning model.

Execute the following steps to calculate 30+ technical indicators with a single line of code:

  1. Import the libraries:
    from ta import add_all_ta_features
    
  2. Discard the previously calculated indicators and keep only the required columns:
    df = df[["Open", "High", "Low", "Close", "Volume"]].copy()
    
  3. Calculate all the technical indicators available in the ta library:
    df = add_all_ta_features(df, open="Open", high="High",
                             low="Low", close="Close",
                             volume="Volume")
    

The resulting DataFrame contains 88 columns, out of which 83 were added by the single function call.

See also

Please find below links to repositories of TA-Lib, ta, and other interesting libraries useful for technical analysis:

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image