Generate Charts for fundamental trading analysis using RDP Historical Pricing data

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

Below is a sample configuration file you must create.

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

Open the Platform Session

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

Retrieve Time Series data from RDP

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

openColumns =>Open

highColumns => High

lowColumns => Low

closeColumns => Close

volumeColums => Volume

Sample Output

Visualizing Stock Data

Plot a simple Daily Closing Price line graph

Generate a Histogram of the Daily Closing Price

Using the mplfiance library to generate CandleStick and OHLC chart

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

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()

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

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

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

Source Codes

You can download Jupyter Notebook from GitHub.

References

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

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