Generate Charts for fundamental trading analysis using RDP Historical Pricing data

Moragodkrit Chumsri
11 min readFeb 11, 2021

Technical Analysis for intraday trading is one of the basic approaches to help you choose the planning of ventures. Basically, users can use the intraday or end-of-day pricing data to generate charts such as the Candlestick. They can then review the stock price’ trend and make decisions using their own method or algorithm.

I would like to introduce you to the Refinitiv Data Platform (RDP) that basically provides simple web-based API access to a broad range of content provided by Refinitiv. It can retrieve data such as News, ESG, Symbology, Streaming Price, and Historical Pricing. Users can use the REST API provided by RDP to retrieve the intraday data from the Historical Pricing service and then pass the data to any libraries that provided functionality to generate Charts. To help API users access RDP content easier, Refinitiv also provides the Refinitiv Data Platform (RDP) Libraries that provide a set of uniform interfaces providing the developer access to the Refinitiv Data Platform. We are currently providing an RDP Library for Python and .NET users. A general user and data scientists can leverage the library’s functionality to retrieve data from the service, which basically provides the original response message from the RDP service in JSON tabular format. The RDP Library for Python will then convert the JSON tabular format to the pandas dataframe so that the user does not need to handle a JSON message and convert it manually. The user can use the dataframe with libraries such as the mathplotlib and mplfinance library to display the Charts.

In this example, I will show you how to use RDP Library for Python, request the intraday data from the Historical Pricing service, and then generate basic charts such as the Candle Stick and OHLC charts. Basically, the Japanese candlestick chart is commonly used to illustrate movements in a financial instrument’s price over time. It’s popular in finance, and some technical analysis strategies use them to make trading decisions, depending on the candles’ shape, color, and position.

Prerequisites

> pip install refinitiv.dataplatform
  • You must have RDP Account with permission to request data using Historical Pricing API. You can also login to the APIDocs page. Then you can search for the Historical Pricing and looking at section Reference for the document.
  • Ensure that you have the following additional python libraries.
configparser, matplotlib, mplfinance, seaborn

Getting Started using RDP API for python

I will create a configuration file to keep the RDP user info and read it using ConfigParser. This module provides a class that implements a basic configuration language that provides a structure similar to what’s found in Microsoft Windows INI files. We will start creating a configuration file name rdp_cofig.cfg. It will contain the rdpuser section, which use to keep app_key, username, and password.

Below is a sample configuration file you must create.

[rdpuser]
app_key = <Appkey/ClientId>
username = <RDP User>
password = <RDP Password>

Open the Platform Session

Next step, we will import refinitiv.dataplatform library and pass RDP user to function open_platform_session to open a session to the RDP server. RDP library will handle the authorization and manage the session for you.

RDP Version 1.0.0a7
Open Platform Session
RDP Sesssion State is now State.Open

Retrieve Time Series data from RDP

After the session state is Open, we will use the below get_historical_price_summaries interface to retrieve time series pricing Interday summaries data(i.e., bar data).

get_historical_price_summaries(universe, interval=None, start=None, end=None, adjustments=None, sessions=[], count=1, fields=[], on_response=None, closure=None)

Actually, the implementation of this function will send HTTP GET requests to the following RDP endpoint.

https://api.refinitiv.com/data/historical-pricing/v1/views/interday-summaries/Copy

And the following details are possible values for interval and adjustment arguments.

Supported intervals: Intervals.DAILY, Intervals.WEEKLY, Intervals.MONTHLY, Intervals.QUARTERLY, Intervals.YEARLY.

Supported value for adjustments: ‘unadjusted’, ‘exchangeCorrection’, ‘manualCorrection’, ‘CCH’, ‘CRE’, ‘RPO’, ‘RTS’, ‘qualifiers’

You can pass an array of these values to the function like the below sample codes.

adjustments=['unadjusted']
adjustments=['unadjusted','CCH','CRE','RPO','RTS']

Please find below details regarding the adjustments behavior; it’s the details from a reference section on the APIDocs page. Note that it can be changed in future releases. I would suggest you leave it to the default value.

The adjustments are a query parameter that tells the system whether to apply or not apply CORAX (Corporate Actions) events or exchange/manual corrections or price and volume adjustment according to trade/quote qualifier summarization actions to historical time series data.

Normally, the back-end should strictly serve what clients need. However, if the back-end cannot support them, the back-end can still return the form that the back-end supports with the proper adjustments in the response and status block (if applicable) instead of an error message.

Limitations: Adjustment behaviors listed in the limitation section may be changed or improved in the future.

  1. If any combination of correction types is specified (i.e., exchangeCorrection or manualCorrection), all correction types will be applied to data in applicable event types.
  2. If any CORAX combination is specified (i.e., CCH, CRE, RPO, and RTS), all CORAX will be applied to data in applicable event types.

Adjustments values for Interday-summaries and Intraday-summaries API

If unspecified, each back-end service will be controlled with the proper adjustments in the response so that the clients know which adjustment types are applied by default. In this case, the returned data will be applied with exchange and manual corrections and applied with CORAX adjustments.

If specified, the clients want to get some specific adjustment types applied or even unadjusted.

The supported values of adjustments:

  • exchangeCorrection — Apply exchange correction adjustment to historical pricing
  • manualCorrection — Apply manual correction adjustment to historical pricing, i.e., annotations made by content analysts
  • CCH — Apply Capital Change adjustment to historical Pricing due to Corporate Actions, e.g., stock split
  • CRE — Apply Currency Redenomination adjustment when there is a redenomination of the currency
  • RTS — Apply Reuters TimeSeries adjustment to adjust both historical price and volume
  • RPO — Apply Reuters Price Only adjustment to adjust historical price only, not volume
  • unadjusted — Not apply both exchange/manual correct and CORAX

Notes:

  1. Summaries data will always have exchangeCorrection and manualCorrection applied. If the request is explicitly asked for uncorrected data, a status block will be returned along with the corrected data saying, “Uncorrected summaries are currently not supported”.
  2. The unadjusted will be ignored when other values are specified.

Below is a sample code to retrieve Daily historical pricing for the RIC defined in the ricName variable, and I will set the start date from 2013 to nowaday. You need to set the interval to rdp.Intervals.DAILY to get intraday data. We will display the column’s name with the heads and tails of the dataframe to review the data.

Sample Output

Preparing data for plotting chart

Next steps, we will create a new dataframe object from the data returned by the interday-summaries endpoint. We need to map the columns from the original dataframe to Open, High, Low, Close(OHLC) data. So we will define column names to map the OHLC data from the following variables.

openColumns =>Open

highColumns => High

lowColumns => Low

closeColumns => Close

volumeColums => Volume

Sample Output

Visualizing Stock Data

Plot a simple Daily Closing Price line graph

We can create a simple line graph to compare open and close price using the following codes. You can change the size of the figure.figsize to adjust chart size.

Generate a Histogram of the Daily Closing Price

We can review daily closing prices over time to see the spread or volatility and the type of distribution using the histogram. We can use the distplot method from the seaborn library to plot the graph.

Using the mplfiance library to generate CandleStick and OHLC chart

Next step, we will generate a CandleStick and OHLC chart using the new version mplfinance library. We need to pass a dataframe that contains Open, High, Low, and Close data to the mplfinance.plot function and specify the name of the chart you want to plot.

Display shorter period.

tempPlot= ohlc_dataframe.dropna().astype({col: 'int64' for col in ohlc_dataframe.select_dtypes('Int64').columns}).loc['2021-01-01':str(datetime.date.today())]mpf.plot(tempPlot,type='candle',style='charles',volume=True)

From a candlestick chart(zoom the graph), a green candlestick indicates a day where the closing price was higher than the open(Gain), while a red candlestick indicates a day where the open was higher than the close (Loss). The wicks indicate the high and the low, and the body the open and close (hue is used to determine which end of the body is open and which the close). You can follow the instruction from the following example to change the color. You need to pass your own style to the plot function. And as I said previously, a user can use Candlestick charts for technical analysis and use them to make trading decisions, depending on the candles’ shape, color, and position. We will not cover a technical analysis in this example.

Plot OHLC chart

An OHLC chart is a type of bar chart that shows open, high, low, and closing prices for each period. OHLC charts are useful since they show the four major data points over a period, with the closing price being considered the most important by many traders. The chart type is useful because it can show increasing or decreasing momentum. When the open and close are far apart, it shows strong momentum, and when they open and close are close together, it shows indecision or weak momentum. The high and low show the full price range of the period, useful in assessing volatility. There several patterns traders watch for on OHLC charts [8].

To plot the OHLC chart, you can just change the type to ‘ohlc’. It’s quite easy when using mplfinance.

mpf.plot(dfPlot.loc['2020-09-01':str(datetime.date.today()),:],type='ohlc',style='charles',volume=True)
display(dfPlot)mpf.plot(dfPlot.loc['2021-01-01':str(datetime.date.today()),:],type='ohlc',style='charles',volume=True)

Adding plots to the basic mplfinance plot()

Sometimes you may want to plot additional data within the same figure as the basic OHLC or Candlestick plot. For example, you may want to add the results of a technical study or some additional market data.

This is done by passing information into the call to mplfinance.plot() using the addplot (“additional plot”) keyword. I will show you a sample of the additional plots by adding a line plot for the data from columns High and Low to the original OHLC chart.

dfSubPlot = dfPlot.loc['2020-12-01':str(datetime.date.today()),:]
apdict = mpf.make_addplot(dfSubPlot[['High','Low']])
mpf.plot(dfSubPlot,type='ohlc',style='charles',volume=True,addplot=apdict)

Add Simple Moving Average to the Chart

Next steps, we will add a moving average (MA) to the CandleStick chart. MA is widely used as the technical analysis indicator that helps smooth out price action by filtering out the “noise” from random short-term price fluctuations. It is a trend-following or lagging indicator because it is based on past prices. The two basic and commonly used moving averages are the simple moving average (SMA), the simple average of a security over a defined number of time periods, and the exponential moving average (EMA), giving greater weight to more recent prices. Note that this example will use only built-in MA provided by the mplfinance. The most common moving averages are to identify the trend direction and determine support and resistance levels.

Basically, mplfinance provides functionality for easily computing a moving average. The following codes creating a 20-day moving average from the price provided in the dataframe, and plotting it alongside the stock. Moving averages lag behind current price action because they are based on past prices; the longer the time period for the moving average, the greater the lag. Thus, a 200-day MA will have a much greater degree of lag than a 20-day MA because it contains prices for the past 200 days.

mpf.plot(dfPlot.loc[:str(datetime.date.today()),:],type='candle',style='charles',mav=(20),volume=True)

The length of the moving average to use depends on the trading objectives, with shorter moving averages used for short-term trading and longer-term moving averages more suited for long-term investors. The 50-day and 200-day MAs are widely followed by investors and traders, with breaks above and below this moving average considered important trading signals.

The following codes use to generated CandleStick charts with multiple periods of times for SMA (20-day,50-day,75-day, and 200-day).

mpf.plot(dfPlot.loc[:str(datetime.date.today()),:],type='candle',style='charles',mav=(20,60,75,200),volume=True)

Zoom the chart to display a shorter period.

You can also calculate the moving average from your own method or algorithm using the original data from the dataframe and then add a subplot to the CandleStick charts using add plot like the previous sample of OHLC charts.

Generate Renko Chart

Based on the investopedia page, a Renko chart is a type of chart developed by the Japanese that is built using price movement rather than both price and standardized time intervals like most charts are. It is thought to be named after the Japanese word for bricks, “renga,” since the chart looks like a bricks series. A new brick is created when the price moves a specified price amount, and each block is positioned at a 45-degree angle (up or down) to the prior brick. An up brick is typically colored white or green, while a down brick is typically colored black or red[7].

Renko charts filter out the noise and help traders more clearly see the trend since all smaller movements than the box size are filtered out.Renko charts typically only use closing prices based on the chart time frame chosen. For example, if using a weekly time frame, weekly closing prices will be used to construct the bricks[7].

mpf.plot(dfPlot,type='renko',style='charles',renko_params=dict(brick_size=4))Copy

Summary

This article explains RDP users’ alternate choices to retrieve such kind of the End of Day price or intraday data from the Refinitiv Data Platform. This article provides a sample code to use RDP Library for python to retrieve the RDP Historical Pricing service’s intraday data. And then show how to utilize the data with the 3rd party library such as the mplfinance to plot charts like the CandleStick, OHLC, and Renko chart for stock price technical analysis. Users can specify a different kind of interval and adjustment behavior using the RDP Library to retrieve more specific data and visualize the data on various charts. They can then use the charts to identify trading opportunities in price trends and patterns seen on charts.

Source Codes

You can download Jupyter Notebook from GitHub.

References

  1. Refinitiv Data Platform (RDP)
  2. mplfinance Library
  3. Candlestick chart, what is it?
  4. What Is a Moving Average Article.
  5. Seaborn Tutorial
  6. Matplotlib Examples
  7. Renko Chart Definition and Uses
  8. OHLC Chart

--

--

Moragodkrit Chumsri

Software Developer(APIs, Backend), Developer Advocate, Refinitiv