Computing and Plotting Technical Indicators

Technical analysis is a discipline in trading that employs mathematical functions, called technical indicators, to predict and find profitable opportunities in stock markets. Technical indicators analyze data based on past and current prices and volumes of a financial instrument and give out statistical information. This helps in predicting where the future prices of a financial instrument may go (either up or down). With this knowledge, you as a trader can make informed decisions when trading and hence increase your odds of success. 

Technical indicators do not take into account any of the fundamental aspects of the business of the underlying financial instrument, such as revenue, earnings, profit, and so on. However, they do take past and current prices and volumes into account, which helps in predicting short-term price movements.

Most brokers provide technical indicator charts, superimposed on historical data plots, in real time. This helps in visually predicting trends in price movements. However, there are a few limitations to only doing visual analysis:

  • You can view and analyze only a handful of charts at a time, while there could potentially be thousands of charts you may want to analyze to help search for a profitable opportunity.
  • Analyzing multiple charts visually is tedious and subject to delay and human error. Delays and errors are not viable when we want to instantly and accurately grab a good trading opportunity. 

Hence, it is best to let a computer analyze historical data for a large number of financial instruments in real time. For this reason, it is important to learn to compute technical indicators for a given financial instrument using its historical data. This chapter has recipes that introduce code for computing various technical indicators using Python.

There may be scenarios where you would want to plot complex charts. However, it may not be possible to do so with the tools provided by most brokers. For example, you may want to plot a simple moving average (SMA) on the relative strength index (RSI) of the close of historical data (mathematically, this is SMA(RSI(close, timeperiod=10), timeperiod=5)) and analyze it over a period of, say, 3 months, to aid in the development of your trading strategy. On these occasions, it would help to know how to plot technical indicators for a given financial instrument. The recipes of this chapter also include code to plot technical indicators using Python.

Every technical indicator belongs to one of the following two mentioned categories:

  • Leading: This category of indicators gives trade signals when the trend is about to start or a reversal is about to happen. In other words, they lead the trend. So, these indicators are helpful in predicting the upcoming trend. (The trend can be bullish if the prices are going up, or bearish if they are going down.)
  • Lagging: This category of indicators gives trade signals after a trend has started or after a reversal has happened. So, these indicators are helpful in finding out the current trend. 

Technical indicators can also be broadly classified into four types, based on the insight they give:

  • Trend indicators or oscillators: These indicators indicate the trend in the market, if there is a trend. These indicators are also called oscillators as they often oscillate between high and low values with time, like an oscillating wave. Such indicators are usually lagging, but can sometimes be leading as well.
  • Momentum indicators: These indicators tell us how strong the current trend is and also if a reversal in the current trend is likely to occur. These indicators are usually leading indicators.
  • Volatility indicators: These indicators measure the rate of change of price movement, irrespective of the direction (that is, bearish or bullish). These indicators help us understand how fast or slow prices are changing. A very volatile market might not be good for your trading strategy, as by the time you query the market and place an order at a particular price, the price might have moved significantly away from the specified price. These indicators are usually lagging indicators.
  • Volume indicators: These are indicators that indicate how fast or slow the volume is changing with time. The higher the volume, the stronger the current trend would be, so these indicators help in finding the strength of the current trend. These indicators can be both leading and lagging.

This chapter discusses 10 technical indicators across all the previously mentioned categories and types. Each recipe does the following:

  1. Introduces a new technical indicator
  2. Shows how it can be computed on given historical data using Python
  3. Shows how it can be plotted on a Japanese candlestick pattern chart using Python
  4. Explains the insight provided by the indicator from the plot

In this chapter, we will cover the following recipes:

  • Trend indicators – simple moving average 
  • Trend indicators – exponential moving average 
  • Trend indicators – moving average convergence divergence 
  • Trend indicators – parabolic stop and reverse
  • Momentum indicators – relative strength index 
  • Momentum indicators – stochastic oscillator
  • Volatility indicators – Bollinger Bands 
  • Volatility indicators – average true range 
  • Volume indicators – on balance volume 
  • Volume indicators – volume-weighted average price 
The main focus of this chapter is to demonstrate how the most commonly used technical indicators can be computed and plotted. Although each technical indicator is introduced at the beginning of every recipe, understanding them in depth is beyond the scope of this book. If you are interested in this, please refer to the work of renowned personalities, such as Jack Schwager, Martin Pring, John Murphy, Steve Nison, and Thomas Bulkowski, to name a few. You can also use widely accepted web resources, such as https://www.investopedia.com/.

Technical requirements

You will need the following to successfully execute the recipes in this chapter:

  • Python 3.7+
  • The following Python packages:
  • pyalgotrading ($ pip install pyalgotrading)
  • TA-Lib ($ pip install TA-Lib)

If you face errors while installing TA-Lib, it will mostly be due to missing dependencies. You can follow these instructions to fix the issue:

  • For Mac OS X, use the following:
$ brew install ta-lib
  • For Windows, use the following instructions:

You can install the latest TA-Lib binary from https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib based on your Windows build (32 bit/64 bit) and Python version. So, for example, this link on the site TA_Lib‑0.4.18‑cp38‑cp38‑win_amd64.whl, is for TA-Lib version 0.4.18 (TA_Lib-0.4.18) and Python version 3.8 (cp38) and is Windows 64-bit-compatible (win_amd64).

  • For Linux, take the following steps:

Download the gzip file from http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz and run the following commands from your Linux Terminal:

  1. Extract the downloaded gzip file containing the source code for TA-Lib:
$ tar -xzf ta-lib-0.4.0-src.tar.gz
  1. Change your current working directory to the extracted folder:
$ cd ta-lib/
  1. Run the configure command to configure TA-Lib for your machine:
$ ./configure --prefix=/usr
  1. Run the make command to build TA-Lib from the downloaded source code:
$ make
  1. Run the install command to install built executables and libraries to specific directories on your machine:
$ sudo make install

If this doesn't help and you still get errors, please refer to the official TA-Lib GitHub page at https://github.com/mrjbq7/ta-lib#dependencies.

The latest Jupyter notebook for this chapter can be found on GitHub at https://github.com/PacktPublishing/Python-Algorithmic-Trading-Cookbook/tree/master/Chapter05.

It is recommended that you try out the recipes of this chapter in a Jupyter notebook. All of the recipes have a plot as an output. You can interact with those plots conveniently in Jupyter Notebook using its features such as select, pan, zoom, and so on.

The first thing needed for setting connectivity with the broker is getting the API keys. The broker will provide unique keys to each customer, typically as an api-key and api-secret key pair. These API keys are chargeable, usually on a monthly subscription basis. You need to get your copy of api-key and api-secret from the broker website before starting this. You can refer to Appendix I for more details.

The following steps will help you import the necessary modules, set up the broker connection with Zerodha, and fetch and keep some historical data handy, which will be used by all the recipes in this chapter. Please make sure you have followed these steps before trying out any of the recipes:

  1. Import the necessary modules:
>>> import pandas as pd
>>> import talib
>>> from pyalgotrading.broker.broker_connection_zerodha import BrokerConnectionZerodha
>>> from pyalgotrading.utils.func import plot_candlesticks_chart, PlotType

These modules will be needed throughout this chapter.

The plot_candlesticks_chart function is used in every recipe. It takes the following arguments:

  • data: The historical data to be plotted, which should be a pandas.DataFrame object with timestamp, open, high, low, and close columns.
  • plot_type: An instance of the pyalgotrading.plot_type enum class specifying the type of candlesticks pattern chart.
  • indicators (optional): A list of dictionaries, specifying the indicator that should also be plotted along with the candlesticks pattern chart. Each dict should have the following key-value pairs:
  • name: The name of the plot for the legend
  • data: The pandas.Series object representing the indicator data to be plotted
  • extra (optional): The dict of attributes, which will be passed to the plotly.graph_objects.Scatter constructor (more information on this class can be found at https://plot.ly/python-api-reference/generated/plotly.graph_objects.Scatter.html)
  • plot_indicators_separately (optional): If False, indicators will be plotted on the same plot as the historical data. If True, indicators will be plotted separately. The default value is False.
  • caption (optional): Add a string caption to the plot.
  1. Get the api_key and api_secret keys from the broker. These are unique to you and will be used by the broker to identify your Demat account:
>>> api_key = "<your-api-key>"
>>> api_secret = "<your-api-secret>"
>>> broker_connection = BrokerConnectionZerodha(api_key,
api_secret)

We get the following output:

Installing package kiteconnect via pip. This may take a while...
Please login to this link to generate your request token: https://kite.trade/connect/login?api_key=<your-api-key>&v=3

If you are running this for the first time and kiteconnect is not installed, pyalgotrading will automatically install it for you. The final output of step 2 will be a link. Click on the link and log in with your Zerodha credentials. If the authentication is successful, you will see a link in your browser's address bar similar to https://127.0.0.1/?request_token=<aplphanumeric-token>&action=login&status=success—for example, https://127.0.0.1/?request_token=H06I6Ydv95y23D2Dp7NbigFjKweGwRP7&action=login&status=success.

  1. Copy the alphanumeric token and paste it in request_token:
>>> request_token = "<your-request-token>"
>>> broker_connection.set_access_token(request_token)
  1. Fetch and print the historical data for an instrument and assign it to historical_data:
>>> instrument = broker_connection.get_instrument('NSE', 
'TATASTEEL')
>>> historical_data =
broker_connection.get_historical_data(
instrument=instrument,
candle_interval='minute',
start_date='2020-01-01 12:00:00',
end_date='2020-01-01 14:00:00')
>>> historical_data

We get the following output:

                    timestamp   open   high    low  close volume
0 2020-01-01 12:00:00+05:30 467.00 467.30 467.00 467.15 5694
1 2020-01-01 12:01:00+05:30 467.15 467.50 467.10 467.35 10852
2 2020-01-01 12:02:00+05:30 467.35 467.45 467.20 467.45 4171
3 2020-01-01 12:03:00+05:30 467.50 467.50 467.35 467.45 2897
... ... ... ... ... ... ...
117 2020-01-01 13:57:00+05:30 469.70 469.70 469.55 469.60 9442
118 2020-01-01 13:58:00+05:30 469.60 469.70 469.50 469.60 7609
119 2020-01-01 13:59:00+05:30 469.60 469.60 469.50 469.50 8155
120 2020-01-01 14:00:00+05:30 469.50 469.60 469.45 469.60 6973

This step uses the get_instrument() method of the BrokerConnectionZerodha class to fetch an instrument and assign it to a new attribute, instrument. This object is an instance of the Instrument class. The two parameters needed to call get_instrument are the exchange ('NSE') and the trading-symbol ('TATASTEEL'). Next, historical data is fetched and printed for instrument using the get_historical_data() method. This method takes four arguments, described as follows:

  • instrument (Instrument): The object returned by the get_instrument() method of broker_connection.
  • candle_interval (str): A valid string that denotes the duration of each candlestick in the historical data. Possible values can be 'minute', '3minute', '5minute', '10minute', '15minute', '30minute', '60minute', and 'day'. We pass 'minute' to this argument in step 4.
  • start_date (str): Historical data will be fetched starting from this timestamp. We pass '2020-01-01 12:00:00' to this argument in step 4.
  • end_date (str): Historical data will be fetched up to this timestamp. We pass '2020-01-01 14:00:00' to this argument in step 4.

The historical_data object will be needed throughout this chapter.

The pyalgotrading package supports multiple brokers and provides a connection object class per broker, with the same methods. It abstracts broker APIs behind a unified interface, so you need not worry about the underlying broker API calls and can use all the recipes in this chapter as it is. Only the procedure to set up the broker connection will vary from broker to broker. You can refer to the pyalgotrading documentation for information on setting up the broker connection if you are not using Zerodha as your broker. For Zerodha users, the steps mentioned in the preceding section will suffice.

Trend indicators – simple moving average

SMA is a lagging trend indicator. It is used to smooth the price data by eliminating noise and thus identifying trends.

SMA is the simplest form of a moving average. Each output value is the average of the previous n values of the historical data. You can define the value of n, which is also called the time period. In SMA, each value in the time period carries the same weight, and values outside the time period are not included. This makes it less responsive to recent changes compared to previous changes in the data, and is thus useful for smoothing out the prices' data. A consecutive rise in SMA indicates a clear bullish trend, while a consecutive fall indicates a bearish trend. Thus, it is a trend indicator. Also, since it indicates the trend after it has started, it is a lagging indicator.

SMA is widely used in technical analysis. It is also used for calculating other technical indicators, either in combination with itself or other indicators, with the same or different time periods.

The formula for calculating SMA is as follows:

(n >= 1), and here, n is the time period and has to be defined by the user.

Although it is a good idea to know the mathematics behind how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating SMA.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. plot_candlesticks_chart (function)
  3. PlotType (enum)
  4. historical_data (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects. 

How to do it…

We will execute the following steps for this recipe:

  1. Calculate the SMA on historical_data. Assign it to sma_9 and print it:
>>> sma_9 = talib.SMA(historical_data['close'], 
timeperiod=9)
>>> sma_9

We get the following output:

0             NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 467.927778
9 468.100000
10 468.211111
11 468.400000
...
117 469.738889
118 469.744444
119 469.716667
120 469.716667
  1. Plot sma_9 on historical_data:
>>> indicators = [
{
'name': 'SMA 9',
'data': sma_9,
'extra': {
'mode': 'lines',
'line': {
'color': 'gray'
}
}
}
]
>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
                           indicators=indicators, 
caption='Trend Indicator: '
'Simple Moving Average | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute')

We get the following output:

The plotly Python package (https://github.com/plotly/plotly.py) is required for plotting charts. The plot_candlesticks_chart function will install it for you if you don't have it installed already.

How it works...

The talib package provides a ready-to-use talib.SMA function. We use this in step 1 to compute SMA on historical_data and assign it to a new attribute, sma_9. Along with the close series of historical_data, this function takes timeperiod as a parameter, which should be an int value. We use 9 as the parameter here. The sma_9 object is a pandas.Series object. This is printed in step 1. We plot sma_9 on historical_data in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the SMA indicator values and chart:

  • The SMA plot is missing for the first eight timestamp values as the output values are NaN (the index starts from 0, so indices 0 to 7 are the first eight values). This is because the talib.SMA function requires at least a time period number of entries to compute the SMA, which is 9 in our case. From the ninth row onward, we can see the computed values of the Simple moving average (SMAand the corresponding timestamp of the historical_data object. 
  • The SMA increases as the prices go up and decreases as the prices go down, though not immediately in the next timestamp.
  • The rise or fall of the SMA plot follows the rise and fall in the corresponding prices. Hence, it's a lagging indicator. In other words, it doesn't predict the trend outcome in advance.
  • The SMA plot is smooth, without any sudden spikes, unlike the historical data plot. Hence, SMA is often used to smoothen out the prices.

Trend indicators – exponential moving average

EMA is a lagging trend indicator. It is used to smooth the price data by eliminating noise and thus identifying trends, with more weightage to recent values.

The EMA technical indicator calculation is cumulative and includes all the data with decreasing weights. Past values have a lower contribution to the average, while recent values have a greater contribution. The further away the value, the smaller the contribution. Thus, EMA is a moving average that is more responsive to recent changes in the data.

The EMA technical indicator is not like the SMA technical indicator, where each value in the time period carries equal weight and values outside of the time period are not included in the calculation.

EMA is widely used in technical analysis. It is also used for calculating other technical indicators, either in combination with itself or other indicators, with the same or different time periods.

A recursive formula for calculating EMA is as follows:

(n >= 1), and here, n is the time period and has to be defined by the user. K is sometimes called the smoothing or weighting factor.

Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating EMA.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. plot_candlesticks_chart (function)
  3. PlotType (enum)
  4. historical_data (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects.

How to do it…

We will execute the following steps for this recipe:

  1. Calculate the EMA on historical_data. Assign it to ema_9 and print it: 
>>> ema_9 = talib.EMA(historical_data['close'], 
timeperiod=9)
>>> ema_9

We get the following output:

0             NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 467.927778
9 468.082222
10 468.135778
11 468.338622
...
117 469.728790
118 469.703032
119 469.662426
120 469.649941
  1. Plot ema_9 on historical_data:
>>> indicators = [
{
'name': 'EMA 9',
'data': ema_9,
'extra': {
'mode': 'lines',
'line': {
'color': 'gray'
}
}
}
]
>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
caption='Trend Indicator: '
'Exponential Moving Average | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute')

We get the following output:

How it works…

The talib package provides a ready-to-use talib.EMA function. We use this in step 1 to compute the EMA on historical_data and assign it to a new attribute, ema_9. Along with the close series of historical_data, this function takes timeperiod as a parameter, which should be an int value. We use 9 as the parameter here. The ema_9 object is a pandas.Series object. This is printed in step 1. We plot ema_9 on historical_data in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the EMA indicator values and chart:

  • The EMA plot is missing for the first eight timestamp values as the output values are NaN (the index starts from 0, so indices 0 to 7 are first eight values). This is because the talib.EMA function requires at least a time period number of entries to compute EMA, which is 9 in our case. From the ninth row onward, we can see the EMA computed, each entry being the EMA for the corresponding timestamp of the historical_data object. 
  • The EMA increases as the prices go up and decreases as the prices go down, closely following the prices. Hence, it's a trend indicator.
  • The rise or fall of the EMA plot follows the rise and fall in the corresponding prices. Hence, it's a lagging indicator. In other words, it doesn't predict the trend outcome in advance.
  • The EMA plot is smooth, without any sudden spikes, unlike the historical data plot. Hence, EMA is used to smooth out the prices.
  • The EMA plot, when compared to the SMA plot from the Plotting trend indicator – simple moving average recipe, shows that the EMA plot follows the price trend more closely than the SMA plot. That is because EMA gives more weightage to recent values, unlike SMA, where each bit of data used for computation has equal weightage.
For more information on the usage of the plot_candlesticks_chart function, please refer to the How it works… section of the Plotting trend indicator – simple moving average recipe of this chapter.

Trend indicators – moving average convergence divergence

Moving average convergence divergence (MACD) is a lagging trend indicator. MACD has three components: the MACD line, MACD signal, and MACD histogram. The MACD line helps in identifying trend changes as it signals the start of a new trend direction. Large positive values of the MACD line indicate that the shorter EMA is much larger than the longer EMA. This suggests that there is an overbought condition in the market, which means prices will be going up. Similarly, large negative values of the MACD line indicate that the shorter EMA is much smaller than the longer EMA. This suggests that there is an oversold condition in the market, which means the prices will be going down. When the MACD line crosses above the MACD signal and is positive, a buy signal is generated; and the MACD line crosses below the MACD signal and becomes negative, a sell signal is generated.

The formulae for computing the three components of MACD are given as follows:

  • The MACD line is the difference between two different time period EMAs—the EMA of a shorter time period, m, and the EMA of a longer time period, n:

  • The MACD signal is the EMA of the MACD line, with time period p:

  • The MACD histogram is the difference between the MACD line and the MACD signal:

The time periods for the MACD line are often given as 12 (m) and 26 (n) and the time period for the MACD signal is often given as 9 (p).

Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating MACD.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. pd (module)
  3. plot_candlesticks_chart (function)
  4. PlotType (enum)
  5. historical_data (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects. 

How to do it…

We will execute the following steps for this recipe:

  1. Calculate MACD on historical_data. Assign it to macd_line, macd_signal, and macd_historgram. Also, print it:
>>> macd_line, macd_signal, macd_histogram = 
talib.MACD(historical_data['close'],
fastperiod=12,
slowperiod=26,
signalperiod=9)
>>> pd.DataFrame({
'Line': macd_line,
'Signal': macd_signal,
'Histogram': macd_histogram
})

We get the following output:

        Line   Signal Histogram
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN NaN NaN
... ... ... ...
116 0.075136 0.087038 -0.011901
117 0.057580 0.081146 -0.023566
118 0.043170 0.073551 -0.030381
119 0.023410 0.063523 -0.040113
120 0.015639 0.053946 -0.038307
  1. Plot macd_line, macd_signal, and macd_histogram, along with historical_data:
>>> indicators = [
{
'name': 'MACD Line',
'data': macd_line,
'extra': {
'mode': 'lines',
'line': {
'width': 1
}
}
},
{
'name': 'MACD Signal',
'data': macd_signal,
'extra': {
'mode': 'lines',
'line': {
'width': 1
}
}
},
{
'name': 'MACD Histogram',
'data': macd_histogram,
'extra': {
'mode': 'lines',
'line': {
'dash': 'dot',
'width': 2
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
plot_indicators_separately=True,
caption='Trend Indicator: Moving '
'Average Convergence/Divergence | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute',
plot_height=700)

We get the following output:

How it works…

The talib package provides a ready-to-use talib.MACD function. We use this in step 1 to compute MACD on historical_data. Along with the close series of historical_data, this function takes fastperiod, slowperiod, and signalperiod as parameters, all of which should be objects of the int type. We use 26, 12, and 9 as the respective parameters here. The talib.MACD function returns three pandas.Series objects, which we assign to new attributes: macd_line, macd_signal, and macd_histogram. These three objects are concatenated into a pandas.DataFrame object and printed in step 1. We plot macd_line, macd_signal, and macd_histogram along with historical_data in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the MACD indicator values and chart:

  • The MACD plot is missing for the first 34 timestamp values and starts appearing only at the 35th timestamp. This is because it takes 26 data points for the first long EMA data to come (the short EMA data comes in the first 12 data points), and 9 of these points for the MACD signal to appear. So, 26 + 9 make it 35 data points.
  • The MACD line is negative when the prices are going up and is positive when the prices are going down. Hence, it's a trend indicator.
  • The rise or fall of the MACD line plot follows the rise and fall in the corresponding prices. Hence, it's a lagging indicator. In other words, it doesn't predict the trend outcome in advance.
  • The MACD line plot is smooth, without any sudden spikes, unlike the historical data plot. The MACD signal is even smoother, as it is an EMA of the MACD line.
  • When the MACD histogram is positive, the trend is bullish, which means prices are going up. When the MACD histogram is negative, the trend is bearish, which means the prices are going down.
For usage of the plot_candlesticks_chart function, please refer to the How it works… section of the Plotting trend indicator – simple moving average recipe of this chapter.

Trend indicators – parabolic stop and reverse

Parabolic stop and reverse (SAR) is a leading trend indicator.

The parabolic SAR computes a trailing stop loss for every data point. As the data points are stop-loss points, they are away from the prices when there is a trend and cross the price line during a trend reversal. The parabolic SAR takes two parameters as input: the acceleration factor and the maximum point.

The formula for computing the parabolic SAR is not straightforward and is hence not mentioned here. If you are interested in the underlying math, please refer to the official documentation of TA-Lib on parabolic SAR at http://www.tadoc.org/indicator/SAR.htm. Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating the parabolic SAR.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. plot_candlesticks_chart (function)
  3. PlotType (enum)
  4. historical_data  (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects.

How to do it…

We will execute the following steps for this recipe:

  1. Calculate the parabolic SAR on historical_data. Assign it to psar and print it:
>>> psar = talib.SAR(historical_data['high'], 
historical_data['low'],
acceleration=0.02,
maximum=0.2)
>>> psar

We get the following output:

0             NaN
1 467.000000
2 467.010000
3 467.019800
4 467.029404
...
116 469.175426
117 469.208409
118 469.240073
119 469.270470
120 469.299651
  1. Plot psar on historical_data:
>>> indicators = [
{
'name': 'PSAR',
'data': psar,
'extra': {
'mode': 'lines',
'line': {
'dash': 'dot',
'width': 2,
'color': 'purple'
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
caption='Trend Indicator: '
'Parabolic Stop and Reverse | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute')

We get the following output:

How it works…

The talib package provides a ready-to-use talib.SAR function. We use this in step 1 to compute the parabolic SAR on historical_data and assign it to a new attribute, psar. Along with the high and low series of historical_data, this function takes acceleration and maximum as parameters, both of which should be objects of the float type. We use 0.02 and 0.2 as the respective parameters here. The psar object is a pandas.Series object. This is printed in step 1. We plot psar, along with historical_data, in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the parabolic SAR indicator values and chart:

  • The parabolic SAR is plotted as discrete points, as each point represents the stop loss. The stop loss point changes every time. So, it is a trailing stop loss.
  • When the parabolic SAR plot is below the OHLC plot, the trend is bullish, and when it is above the OHLC plot, the trend is bearish. Hence, it's a trend indicator.
For more information on the usage of the plot_candlesticks_chart function, please refer to the How it works… section of the Plotting trend indicator – simple moving average recipe of this chapter.

Momentum indicators – relative strength index

RSI is a leading momentum indicator. The RSI is a ratio of the recent upward price movement to the absolute price movement. The RSI is always between 0 and 100. It can be interpreted to indicate an overbought condition when the value is above 70 and an oversold condition when the value is below 30. The RSI indicates a reversal when the prices are making new highs or new lows. 

The formula for computing the RSI is not straightforward and is hence not mentioned here. If you are interested in the underlying math, please refer to the official documentation of TA-Lib on RSI at http://www.tadoc.org/indicator/RSI.htm. Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating the RSI.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. plot_candlesticks_chart (function)
  3. PlotType (enum)
  4. historical_data  (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects.

How to do it…

We will execute the following steps for this recipe:

  1. Calculate the RSI on historical_data. Assign it to rsi_14 and print it:
>>> rsi_14 = talib.RSI(historical_data['close'], 
timeperiod=14)
>>> rsi_14

We get the following output:

0            NaN
1 NaN
2 NaN
3 NaN
...
12 NaN
13 NaN
14 70.886076
15 69.932757
16 69.932757
17 64.873530
18 61.976413
...
116 48.449209
117 48.449209
118 48.449209
119 45.997672
120 48.788323
  1. Plot rsi_14 along with historical_data:
>>> indicators = [
{
'name': 'RSI (14)',
'data': rsi_14,
'extra': {
'mode': 'lines',
'line': {
'width': 2,
'color': 'purple'
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
plot_indicators_separately=True,
caption='Momentum Indicator: '
'Relative Strength Index | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute')

We get the following output:

How it works…

The talib package provides a ready-to-use talib.RSI function. We use this in step 1 to compute the RSI on historical_data and assign it to a new attribute, rsi_14. Along with the close series of historical_data, this function takes timeperiod as a parameter, which should be an int value. We use 14 as the parameter here. The rsi_14 object is a pandas.Series object. This is printed in step 1. We plot rsi_14 on historical_data in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the RSI indicator values and chart:

  • The first 13 values in the output are NaN (the index starts from 0, so indices 0 to 12 are the first 13 values) because the function requires at least a time period number of entries to compute the RSI, which is 14 in our case. From the 14th row onward, we can see the RSI computed, each entry being the RSI for the corresponding timestamp of the historical_data object.
  • The RSI is always between 0 and 100.
  • For the given plot, the price peaks suddenly between 12:45 P.M. to 1:00 P.M., and the RSI moves above 70. Thus, it correctly indicates an overbought condition. Also, since it indicates the strength of the price movement, it is a momentum indicator.
For more information on the usage of the plot_candlesticks_chart function, please refer to the How it works… section of the Plotting trend indicator – simple moving average recipe of this chapter.

Momentum indicators – stochastic oscillator

The stochastic oscillator is a leading momentum indicator. It is also called STOCH for short. STOCH compares the latest close with the recent trading range. Fast K is a ratio and has a value between 0 and 100. Fast K can have haphazard movement, and hence it is smoothed using a moving average, which is the slow K. Slow K is further smoothed using another moving average, which is the slow D. Values of slow K over 75 indicate an overbought condition, while values below 25 indicate an oversold condition. When slow K crosses above slow D, it is considered a buy signal. Similarly, when slow K crosses below slow D, it is considered a sell signal.

The formula for computing STOCH is as follows:

MA stands for moving average, and can be either SMA or EMA. For this recipe, we have used SMA. This formula needs three time periods: one of them is n and the other two are the time periods of the MAs. The range over which we analyze data is defined by n.

Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating STOCH.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. pd (module)
  3. plot_candlesticks_chart (function)
  4. PlotType (enum)
  5. historical_data  (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects.

How to do it…

We will execute the following steps for this recipe:

  1. Calculate the stochastic oscillator on historical_data. Assign it to slowk and slowd. Also, print it:
>>> slowk, slowd = talib.STOCH(historical_data['high'], 
historical_data['low'],
historical_data['close'],
fastk_period=5,
slowk_period=3,
slowk_matype=0,
slowd_period=3,
slowd_matype=0)
>>> pd.DataFrame({
'Slow K': slowk,
'Slow D': slowd
})

We get the following output:

       Slow K    Slow D
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN
4 NaN NaN
5 NaN NaN
6 NaN NaN
7 NaN NaN
8 70.514283 69.296302
9 71.113411 70.921500
10 61.606578 67.744757
11 67.613252 66.777747
12 52.662272 60.627367
... ... ...
116 63.626374 77.374847
117 44.102564 64.420024
118 20.000000 42.576313
119 13.333333 25.811966
120 15.757576 16.363636
  1. Plot slowk and slowd, along with historical_data:
>>> indicators = [
{
'name': 'Slow K',
'data': slowk,
'extra': {
'mode':'lines',
'line': {
'width': 2
}
}
},
{
'name': 'Slow D',
'data': slowd,
'extra': {
'mode': 'lines',
'line': {
'width': 2
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
plot_indicators_separately=True,
caption='Trend Indicator: '
'Stochastic Oscillator (Slow) | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute',
plot_height=700)

We get the following output:

How it works…

The talib package provides a ready-to-use talib.STOCH function. We use this in step 1 to compute the stochastic oscillator on historical_data. Along with the high, low, and close series of historical_data, this function takes the following parameters:

  • fastk_period (int): The range over which we analyze the data. Here, we took the value as 5.

  • slowk_period (int): The time period for calculating the moving average on fast K. Here, we took the value as 3.

  • slowk_matype (int): The moving average type. A value of 0 implies SMA and 1 implies EMA. Here, we took the value as 0.

  • slowd_period (int): The time period for calculating the moving average on slow K. Here, we took the value as 3.

  • slowd_matype (int): The moving average type. A value of 0 implies SMA and 1 implies EMA. Here, we took the value as 0.

The talib.STOCH function returns two pandas.Series objects, which we assign to new attributes: slowk and slowd. These two objects are concatenated into a pandas.DataFrame object and printed in step 1. We plot slowk and slowd, along with historical_data, in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the STOCH indicator values and chart:

  • The first eight values in the output are NaN (the index starts from 0, so indices 0 to 7 are the first 8 values). That's because it takes the first five values to get a fast K, three fast Ks to get a slow K, and three slow Ks to get a slow D. So, that's 5 + (3 - 1) + (2 - 1) = 9. (We subtract 1 twice as the last value for previous computation is the first value for the next computation, so that's already counted once.) From the ninth row onward, we can see the computed values of slow K and slow D and the corresponding timestamp of the historical_data object.
  • The slow K and slow D values are always between 0 and 100.
  • The rise or fall of the slow K and slow D plot is followed by the rise and fall in the corresponding prices for most of the time, particularly evident in the plot after 12:45 P.M. Hence, it's a leading indicator. In other words, it predicts the trend outcome in advance.
  • Since it's a leading indicator, it reacts to prices quickly. This often results in false signals, as can be seen in the plot between 12:30 P.M. to 12:45P.M. (To safeguard yourself from these scenarios, you can use more indicators in your strategy to get additional confirmation of trends or reversals.)

Volatility indicators – Bollinger Bands

Bollinger Bands are a lagging volatility indicator. Bollinger Bands consist of three lines, or bands—the middle band, the lower band, and the upper band. The gap between the bands widens when the price volatility is high and reduces when the price volatility is low.

Bollinger Bands are an indicator of overbought or oversold conditions. When the price is near the upper band or the lower band, this indicator predicts that a reversal will happen soon. The middle band acts as a support or resistance level. 

The upper band and lower band can also be interpreted as price targets. When the price bounces off of the upper band and crosses the middle band, the lower band becomes the price target, and vice versa.

The formulae for computing the Bollinger Bands are as follows.

Bollinger Bands define the typical price (TP) as the average of the high, low, and close of a candle. The TP is used for computing the middle band, lower band, and upper band:

The middle band is the SMA of the TP:

The upper band and lower band are an integer (F) number of the standard deviation above and below the middle band. The typical value of F is 2:

Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating the Bollinger Bands.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. pd (module)
  3. plot_candlesticks_chart (function)
  4. PlotType (enum)
  5. historical_data (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects. 

How to do it…

We execute the following steps for this recipe:

  1. Calculate the Bollinger Bands on historical_data. Assign it to upperband, middleband, and lowerband. Also, print it:
>>> upperband, middleband, lowerband = talib.BBANDS(
historical_data['close'],
timeperiod=5,
nbdevup=2,
nbdevdn=2,
matype=0)
>>> pd.DataFrame({
'Upperband': upperband,
'Middleband': middleband,
'Lowerband': lowerband
})

We get the following output:

      Upperband Middleband   Lowerband
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 468.138749 467.50 466.861251
... ... ... ...
116 470.071661 469.83 469.588339
117 470.080666 469.78 469.479334
118 470.020666 469.72 469.419334
119 469.959839 469.65 469.340161
120 469.660000 469.58 469.500000
  1. Plot upperband, middleband, and lowerband on historical_data:
>>> indicators = [
{
'name': 'Upperband',
'data': upperband,
'extra': {
'mode': 'lines',
'line': {
'width': 1
}
}
},
{
'name': 'Middleband',
'data': middleband,
'extra': {
'mode':'lines',
'line': {
'width': 1
}
}
},
{
'name': 'Lowerband',
'data': lowerband,
'extra': {
'mode': 'lines',
'line': {
'width': 1
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
caption='Volatility Indicator: '
'Bollinger Bands | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute')

We get the following output:

How it works…

The talib package provides a ready-to-use talib.BBANDS function. We use this in step 1 to compute the Bollinger Bands on historical_data. Along with the close series of historical_data, this function takes the following parameters:

  • timeperiod (int): The time period for calculating the SMA on the TP. The TP is the average of the high, low, and close prices. Here, we took the value as 5.

  • nbdevup (int): The number of unbiased standard deviations from the mean for the upper band. Here, we took the value as 2.

  • nbdevdn (int): The number of unbiased standard deviations from the mean for the lower band. Here, we took the value as 2.

  • matype (int): The moving average type. A value of 0 implies SMA and 1 implies EMA. Here, we took the value as 0.

The talib.BBANDS function returns three pandas.Series objects, which we assign to new attributes: upperband, middleband, and lowerband. These three objects are concatenated into a pandas.DataFrame object and printed in step 1. We plot upperband, middleband, and lowerband on historical_data in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the Bollinger Bands indicator values and chart:

  • The first four values in the output are NaN (the index starts from 0, so indices 0 to 3 are the first four values) because the talib.BBANDS function requires at least a time period number of entries to compute the Bollinger Bands, which is 5 in our case. From the fifth row onward, we can see all the computed values of all three bands and the corresponding timestamp of the historical_data object.
  • The rise or fall of the bands follow the rise and fall in the corresponding prices. Hence, Bollinger Bands are a lagging indicator. In other words, they don't predict the trend outcome in advance.
  • Around 12:45 P.M. in the plot, we see that the bands have become narrow. This is because of low volatility (slow rate of price change) around that time.
  • Just before 1 P.M. in the plot, we see that the gap between the bands has widened drastically. This is because of high volatility (rapid rate of price change) around that time.
  • Most of the time, when the price touches the upper band, it starts moving downward (the opposite direction). You can use these instances as sell signals for your strategy.
  • Most of the time, when the price touches the lower band, it starts moving upward (the opposite direction). You can use these instances as buy signals for your strategy.

Volatility indicators – average true range

Average true range (ATR) is a lagging volatility indicator. ATR is a measure of volatility. High ATR values indicate high volatility, and low values indicate low volatility.

The formula for computing ATR is not straightforward and is hence not mentioned here. If you are interested in the underlying math, please refer to the official documentation of TA-Lib on ATR at http://www.tadoc.org/indicator/ATR.htm. Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating ATR.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. pd (module)
  3. plot_candlesticks_chart (function)
  4. PlotType (enum)
  5. historical_data (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects.

How to do it…

We will execute the following steps for this recipe:

  1. Calculate the ATR on historical_data. Assign it to atr_14 and print it:
>>> atr_14 = talib.ATR(historical_data['high'], 
historical_data['low'],
historical_data['close'],
timeperiod=14)
>>> atr_14

We get the following output:

0           NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
10 NaN
11 NaN
12 NaN
13 NaN
14 0.575000
15 0.555357
16 0.562117
17 0.550538
18 0.529071
...
116 0.375902
117 0.359766
118 0.348354
119 0.330614
120 0.317713
  1. Plot atr_14, along with historical_data:
>>> indicators = [
{
'name': 'ATR (14)',
'data': atr_14,
'extra': {
'mode': 'lines',
'line': {
'width': 2,
'color': 'purple'
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
plot_indicators_separately=True,
caption='Volatility Indicator: '
'Average True Range | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute',
plot_height=700)

We get the following output:

How it works…

The talib package provides a ready-to-use talib.ATR function. We use this in step 1 to compute the ATR on historical_data and assign it to a new attribute, atr_14. Along with the high, low, and close series of historical_data, this function takes timeperiod as a parameter, which should be an int value. We use 14 as the parameter here. The rsi_14 object is a pandas.Series object. This is printed in step 1. We plot atr_14 on historical_data in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the ATR indicator values and chart:

  • The first 14 values in the output are NaN (the index starts from 0, so indices 0 to 13 are the first 14 values) because the talib.ATR function requires at least one more than the time period number of entries to compute the ATR, which is 14 in our case. From the 15th row onward, we can see all the computed values of the ATR and the corresponding timestamp of the historical_data object.
  • When there is high volatility (rapid rate of price change), the ATR starts increasing. This can be seen in the chart around 1 P.M.
  • When there is low volatility (slow rate of price change), the ATR starts decreasing. This can be seen around the end of the chart.

Volume indicators – on balance volume

On balance volume (OBV) is a leading volume indicator. The OBV is a cumulative total of the up and down volume. When the close is higher than the previous close, the volume is added to the running total, and when the close is lower than the previous close, the volume is subtracted from the running total.

To interpret the OBV, you can observe the movement of the OBV and the price. If the price moves before the OBV, then it is a non-confirmed move. A series of rising peaks, or falling troughs, in the OBV indicates a strong trend. If the OBV is flat, then the market is not trending.

The formulae for computing the OBV are as follows:

  • If close > close-1, then OBV = OBV-1 + volume
  • If close < close-1, then OBV = OBV-1 - volume
  • If close = close-1, then OBV = OBV-1

Although it is a good idea to know the mathematics of how this works, this recipe does not require you to understand or remember the given formula. We use a third-party Python package, talib, which provides a ready function for calculating the OBV.

Getting started

Make sure your Python namespace has the following objects:

  1. talib (package)
  2. pd (module)
  3. plot_candlesticks_chart (function)
  4. PlotType (enum)
  5. historical_data (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects.

How to do it…

We will execute the following steps for this recipe:

  1. Calculate the OBV on historical_data. Assign it to obv and print it:
>>> obv = talib.OBV(historical_data['close'], 
historical_data['volume'])
>>> obv

We get the following output:

0        5694.0
1 16546.0
2 20717.0
3 20717.0
4 211302.0
...
116 406508.0
117 406508.0
118 406508.0
119 398353.0
120 405326.0
  1. Plot obv, along with historical_data:
>>> indicators = [
{
'name': 'On Balance Volume',
'data': obv,
'extra': {
'mode': 'lines',
'line': {
'width': 2,
'color': 'purple'
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
plot_indicators_separately=True,
caption='Volume Indicator: '
'On Balance Volume | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute',
plot_height=700)

We get the following output:

How it works…

The talib package provides a ready-to-use talib.OBV function. We use this in step 1 to compute the OBV on historical_data and assign it to a new attribute, obv. This function takes the close and volume series of historical_data as parameters. The obv object is a pandas.Series object. This is printed in step 1. We plot obv, along with historical_data, in step 2 using the plot_candlesticks_chart function.

Observe the following points regarding the OBV indicator values and chart:

  • There are no NaN outputs in the table. From the first row itself, we can see all the computed values of the OBV and the corresponding timestamp of the historical_data object. One single data point is sufficient to calculate the OBV.
  • The values are always positive.
  • The rise or fall of the OBV plot is closely followed by the rise and fall of the corresponding prices for most of the time. Hence, it's a leading indicator. In other words, it predicts the trend outcome in advance. (Since it's a leading indicator, it reacts to prices quickly. This often results in false signals. To safeguard yourself from these scenarios, you can use more indicators in your strategy to get additional confirmation of trends or reversals.)

Volume indicators – volume-weighted average price

Volume-weighted average price (VWAP) is a lagging volume indicator. The VWAP is a weighted moving average that uses the volume as the weighting factor so that higher volume days have more weight. It is a non-cumulative moving average, so only data within the time period is used in the calculation.

Although this function is available in talib, we will show you how to compute an indicator manually here by creating its formula. This will help you create your own indicators at times when you may use customer technical indicators or not-so-popular indicators that are missing from talib.

The formula for calculating VWAP is as follows: 

Here, n is the time period and has to be defined by the user.

Getting started

Make sure your Python namespace has the following objects:

  1. pd (module)
  2. plot_candlesticks_chart (function)
  3. PlotType (enum)
  4. historical_data (a pandas DataFrame)

Refer to the Technical requirements section of this chapter to set up these objects.

How to do it…

We will execute the following steps for this recipe:

  1. Define a function for computing VWAP:
>>> def VWAP(hist_data_df):
"""
Returns VWAP computed over the given historical data
hist_data_df: A pandas DataFrame of historical data with
columns
'timestamp', 'high', 'low', 'close' and 'volume'
"""
hist_data_df['date'] =
hist_data_df['timestamp'].apply(lambda x: x.date())
unique_dates = sorted(set(hist_data_df['date']))
vwap = []

"""
Compute vwap for each day's data and append it to vwap
variable
"""
for i, date in enumerate(unique_dates):
day_df = hist_data_df.loc[hist_data_df['date'] == date]
typical_price_day_df = (day_df.high + day_df.low +
day_df.close)/3
vwap_day = list(((typical_price_day_df *
day_df.volume).cumsum()) /
day_df.volume.cumsum())
vwap += vwap_day

return pd.Series(vwap)
  1. Calculate VWAP on historical_data. Assign it to vwap and print it:
>>> vwap = VWAP(historical_data)
>>> vwap

We get the following output:

0      467.150000
1 467.259311
2 467.280925
3 467.299623
4 468.085910
...
116 468.965162
117 468.967599
118 468.969499
119 468.971309
120 468.972893
  1. Plot vwap along with historical_data:
>>> indicators = [
{
'name': 'VWAP',
'data': vwap,
'extra': {
'mode': 'lines',
'line': {
'width': 2,
'color': 'purple'
}
}
}
]

>>> plot_candlesticks_chart(data=historical_data,
plot_type=PlotType.JAPANESE,
indicators=indicators,
plot_indicators_separately=True,
caption='Volume Indicator: '
'Volume Weighted Average Price | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute',
plot_height=700)

We get the following output:

How it works…

We define a function that calculates VWAP in step 1 for the given historical data as a pandas.DataFrame object. It works as follows:

  1. Finds all the unique dates in the historical data
  2. Iterates over all the unique dates:
  • Extracts day_df, a pandas.DataFrame object with entries from historical_data that fall on the unique date
  • Calculates typical_price_day_df, the typical price, which is the average of the high, low, and close prices for the day
  • Calculates vwap_day, which is a list of the typical price-weighted averages of the volumes for all the entries in day_df
  1. Returns all the vwap_day values appended together as a pandas.Series object

We compute VWAP in step 2 on historical_data using the VWAP function and assign it to a new attribute, vwap. The vwap object is a pandas.Series object. We plot vwap along with historical_data in step 3 using the plot_candlesticks_chart function.

Observe the following points regarding the VWAP indicator values and chart:

  • There are no NaN outputs in the table. From the first row itself, we can see all the computed values of VWAP and the corresponding timestamp of the historical_data object. One single data point is sufficient to calculate VWAP.
  • The values are always positive.
  • The rise or fall of the VWAP plot follows the rise and fall in the corresponding prices. Hence, it's a lagging indicator. In other words, it doesn't predict the trend outcome in advance.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset