<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jason Ramchandani on Medium]]></title>
        <description><![CDATA[Stories by Jason Ramchandani on Medium]]></description>
        <link>https://medium.com/@jas0nram?source=rss-8eaefa21707f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MCJiOiwhn2Mzs_9Z.jpg</url>
            <title>Stories by Jason Ramchandani on Medium</title>
            <link>https://medium.com/@jas0nram?source=rss-8eaefa21707f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:11:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jas0nram/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to Equity Pair Trading]]></title>
            <link>https://medium.com/lseg-developer-community/introduction-to-equity-pair-trading-b61cf28db62a?source=rss-8eaefa21707f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b61cf28db62a</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Jason Ramchandani]]></dc:creator>
            <pubDate>Fri, 23 Jul 2021 09:20:37 GMT</pubDate>
            <atom:updated>2021-09-02T10:12:50.552Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Overview</strong></p><p>This article will cover the Equity Pair trading use case and go from a single pair example to an industrialised search process with commonly used statistical tests, combinatoric generators and computed in a brute force fashion using vectorization and parallelization where appropriate. Finally, we will use some filtering and visualization tools to eyeball the results and suggest potential next steps. <a href="https://github.com/Refinitiv-API-Samples/Article.EikonAPI.Python.EquityPairTrading/blob/master/EquityPairTrading.ipynb">Link to github source</a></p><p><strong>Sections</strong></p><p><a href="#Introduction">Introduction to Pair Trading</a></p><p><a href="#Single">Single Pair Example</a></p><p><a href="#Rigour">Introducing More Statistical Rigour</a></p><p><a href="#Industrialise">Industrializing Our Search Process</a></p><p><a href="#Calculation">Calculation Details — Vectorization or Parallisation</a></p><p><a href="#Filtering">Filtering our Universe Down</a></p><p><a href="#Visualize">Final Visual Check — Seaborn FacetGrid</a></p><p><a href="#Conclusion">Conclusion</a></p><p><strong>Pre-requisites:</strong></p><p><strong>Thomson Reuters Eikon / Refinitiv Workspace</strong> with access to <a href="https://refini.tv/3bvPev5">Eikon Data APIs</a> (Free Trial Available)</p><p>Python 2.x/3.x</p><p>Required Python Packages: <a href="https://pypi.org/project/eikon/">eikon</a>, <a href="https://pypi.org/project/pandas/">pandas</a>, <a href="https://pypi.org/project/numpy/">numpy</a>, <a href="https://pypi.org/project/matplotlib/">matplotlib</a>, <a href="https://pypi.org/project/statsmodels/">statsmodels</a>, <a href="https://pypi.org/project/swifter/">swifter</a>, <a href="https://pypi.org/project/seaborn/">seaborn</a></p><h4>Introduction to Pair Trading</h4><p>Pair trading is a time-honoured market-neutral type of statistical arbitrage trading strategy. It is market-neutral because once you have identified a suitable pair (two stocks for example) — you would be long one stock and short the other. This means that whatever the broader market does ie goes up or down — you are theoretically somewhat insulated. Another interesting characteristic of this strategy is its low capital outlay as the short side of the trade funds the long side of the trade — so this type of approach is very efficient from a capital as well as a risk point of view.</p><p>So how can we find these pairs? Well there are many approaches — some concentrate on finding companies in similar sectors or business areas or geographies or markets. Some focus on identifying groups of fundamental criteria.</p><p>Lets start by taking two well-known automakers — say Tesla and General Motors in the United States and see what we can find out about the price movement of these.</p><h4>Single Pair Example</h4><p>First lets import some of the packages we will be using.</p><pre>%matplotlib inline<br>import eikon as ek<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import statsmodels.tsa.stattools as ts <br>from statsmodels.tsa.stattools import adfuller<br>import itertools<br>import swifter<br>import seaborn as sns<br><br>ek.set_app_key(&#39;YOUR APP KEY HERE&#39;)</pre><pre>/Users/jasonram/anaconda3/lib/python3.7/site-packages/dask/dataframe/utils.py:13: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.<br>  import pandas.util.testing as tm</pre><p>First, lets load some timeseries data for both stocks using the ek.get_timeseries function.</p><pre>rics = [&#39;TSLA.O&#39;,&#39;GM&#39;]<br>s = &#39;2013-12-23&#39;<br>e = &#39;2019-12-08&#39;<br>i = &#39;daily&#39;<br>df = ek.get_timeseries(rics,  # RICs<br>              fields=[&#39;CLOSE&#39;],  # fields to be retrieved<br>              start_date=s,  # start time<br>              end_date=e,  # end time<br>              interval=i)<br>df</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*LF8UJKwLnYynTZZD5vf2ig.png" /></figure><p>Next we want to get rid of any non-complete (ie N/A) rows as thiis will not play well with some our routines downstream.</p><pre>df.dropna(inplace=True)<br>df</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*LF8UJKwLnYynTZZD5vf2ig.png" /></figure><p>Lets add both Spread and Ratio columns as we will want to chart these — particularly the Ratio — as this is the series we will be hoping to trade on and we also print a Pearson Correlation Coefficient.</p><pre>df[&#39;Spread&#39;] = df[&#39;TSLA.O&#39;] - df[&#39;GM&#39;]<br>df[&#39;Ratio&#39;] = df[&#39;TSLA.O&#39;] / df[&#39;GM&#39;]<br>mean = df[&#39;Ratio&#39;].mean()<br>corr = df[&#39;TSLA.O&#39;].corr(df[&#39;GM&#39;])<br>print(corr)<br>df</pre><pre>0.44026737012835365</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*xpj3HSyaRYGNq3CFU1hopw.png" /></figure><p>The code below charts our ratio between TSLA.O and GM. We add a mean value of the ratio — this is the mean to which we hope the ratio will revert to. Adding a mean and standard deviation thresholds onto the chart can give us interesting entry and exit signals over time.</p><pre>fig = plt.figure()<br>ax = plt.axes()<br><br>x = df.index.values<br>plt.plot(x, df[&#39;Ratio&#39;], label=&#39;Ratio&#39;)<br>plt.plot(x, (df[&#39;Ratio&#39;].values.mean().repeat(len(x))), label=&#39;Mean&#39;)<br>stdplus = df[&#39;Ratio&#39;].values.mean() + (1.5*df[&#39;Ratio&#39;].values.std())<br>stdminus = df[&#39;Ratio&#39;].values.mean() - (1.5*df[&#39;Ratio&#39;].values.std())<br>#plt.plot(x, (df[&#39;Ratio&#39;].values.mean().repeat(len(x))), label=&#39;SD1&#39;)<br>plt.plot(x, (stdplus.repeat(len(x))), label=&#39;SD+1.5&#39;)<br>plt.plot(x, (stdminus.repeat(len(x))), label=&#39;SD-1.5&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*ITEcaRGi7Ly5npv9yxBz3w.png" /></figure><p>From the above chart we can see that adding the mean and standard deviation thresholds onto the chart might give us interesting entry and exit signals over time. The lower bound of 1.5 times standard deviation seems to be a pretty reliable entry point for this pair — and has been tested on 5 occasions over the last decade — all with minimal drawdown and large reversion to mean in each case.</p><p>The upper bound of 1.5 times standard deviation seems to be a reasonable threshold till 2017 — but since then it has been breached on a number of occasions — so we may wish to expand the upper bound to 2 standard deviations or more.</p><p>Whilst interesting — this approach suffers from 2 drawbacks — firstly, its still a bit imprecise and secondly it relies on me knowing what the appropriate pair should be. Lets deal with the first of these drawbacks.</p><h4>Introduce More Statistical Rigour</h4><p>Lets consider some more rigorous statistical tests.</p><p>For this particular strategy we want to see a relatively high level of correlation between the two stock price series. Correlation is a measure of directional relatedness — ie if GM rises does Tesla rise. The range of correlation is from -1 to +1. Correlation in non-stationary timeseries may just be reflecting autoregression (AR processes) — so we need conduct some additional tests.</p><p>It is important that the ratio series is mean reverting. It is this property that we wish to identify &amp; exploit. To help us in this task we can test for stationarity of the series. We will use the Augmented Dickey Fuller (ADF) test to see if we can reject the null hypothesis that the Ratio timeseries has a unit root (ie the series is non-stationary).</p><p>Another statistical property we wish to be present is that the two stocks should be cointegrated. This is the co-movement of both time series (which could be non-stationary). We will use the Engle-Granger two-step cointegration test to see if we can reject the null hypothesis that the pair are NOT cointegrated. This is important as both stocks in the pair should display some quality of cointegratedness for this type of strategy to be exploitable. Thankfully the excellent statsmodels package provides this functionality for us.</p><pre>print(adfuller(df[&#39;Ratio&#39;])[0:5])</pre><pre>(-3.5915050452251873, 0.00592552532947228, 0, 1499, {&#39;1%&#39;: -3.4347199356122493, &#39;5%&#39;: -2.86347004827819, &#39;10%&#39;: -2.567797534300163})</pre><pre>result = ts.coint(df[&#39;TSLA.O&#39;], df[&#39;GM&#39;])<br>print(result)</pre><pre>(-3.6980090738968627, 0.018433668450996164, array([-3.90376106, -3.34020915, -3.04728056]))</pre><p>From the ADF output we can see that the critical value is -3.59 with a p-value of 0.005. The critical value is less than the t-values at the 1%,5% &amp; 10% confidence levels and the p-value is less than 0.05 (95% confidence level). So we can reject the null hypothesis.</p><p>From the cointegration output we can see that the critical value is -3.69 with a p-value of 0.018. The critical value is less than the t-values at the 5% &amp; 10% confidence levels, but not at the 1% level and the p-value of 0.018 is less than 0.05 (95% confidence interval). So we can reject the null hypothesis.</p><h4>Industrialising Our Search Process</h4><p>So we have seen how it works for one pair — lets try and deal with the second drawback and try to industrialise this search for potential pairs to a whole universe of stocks — say the FTSE 100 index — but it could of course be any universe or list of instruments. So lets get a list of constituents for our chosen index using the ek.get_data function. The get_data function can be passed a chain RIC or a list of RICs — here we pass a chain RIC for the FTSE 100.</p><pre>rics, err = ek.get_data(&#39;0#.FTSE&#39;,&#39;CF_Name&#39;)<br>rics</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*cZCSm_Cc77Rg5X5RHcXd1A.png" /></figure><p>Here we take our list of RIC codes for FTSE 100 index and then we add a start and end date parameter, select the daily interval and the ‘CLOSE’ field and get the underlying time series for each RIC in the list of instruments. We then build a larger dataframe by concatenating each Price series to the base dataframe, whilst renaming the column to the relevant RIC.</p><pre>instruments = rics[&#39;Instrument&#39;].astype(str).values.tolist()<br><br>s = &#39;2010-01-06&#39;<br>e = &#39;2019-12-08&#39;<br>inv = &#39;daily&#39;<br><br>data1 = pd.DataFrame()<br><br>for i in instruments:<br>    <br>    df1 = ek.get_timeseries(i,  # RICs<br>              fields=[&#39;CLOSE&#39;],  # fields to be retrieved<br>              start_date=s,  # start time<br>              end_date=e,  # end time<br>              interval=inv)<br>    df1.rename(columns = {&#39;CLOSE&#39;: i}, inplace = True)<br>    if len(data1):<br>        data1 = pd.concat([data1, df1], axis=1)<br>    else:<br>        data1 = df1</pre><p>So lets have a look at our larger base dataframe.</p><pre>data1</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*yokX2AaSFbNg7cRPIdIgkw.png" /></figure><p>We need to check our dataframe to see if the are any NAN values present as this will not play well with the statsmodels package we wish to use downstream.</p><pre>data2=data1.copy()</pre><p>Drop any rows that are entirely blank — I noticed a few of these being returned</p><pre>data2.dropna(how=&#39;all&#39;, inplace=True)</pre><p>Drop columns which have a nan in them</p><pre>nalist = data2.columns[data2.isna().any()].tolist()<br>nalist</pre><pre>[&#39;ICAG.L&#39;,<br> &#39;EVRE.L&#39;,<br> &#39;MNG.L&#39;,<br> &#39;AUTOA.L&#39;,<br> &#39;GVC.L&#39;,<br> &#39;JETJ.L&#39;,<br> &#39;CCH.L&#39;,<br> &#39;AVST.L&#39;,<br> &#39;POLYP.L&#39;,<br> &#39;GLEN.L&#39;,<br> &#39;AVV.L&#39;,<br> &#39;OCDO.L&#39;]</pre><pre>data2.drop(nalist, axis=1, inplace=True)<br>data2</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Ie8UR6-3uev_HxbCNV8hmA.png" /></figure><h4>Calculation details — Vectorization or Parallelization — decisions, decisions? Who cares with swifter!</h4><p>We now wish to derive a list of all combinations of RICs — we can do this using the excellent itertools.combinations combinatoric generator function — with no repeated elements.</p><p>Then for each of the RIC pairs/ratios in this list we want to calculate and store the output from the ADF test, Engle-Granger cointegration test and Pearsons correlation coefficient. As this is a somewhat brute force approach I tried to follow some of the performance advice I had seen — and finally opted for the syntactically compact apply method using a lambda function. This is supposed to be more efficient than simple looping, iterrows or itertuples.</p><p>Still not satisfied — I searched for some parallelisation or speedup potential and ran across the <strong>Switfer</strong> package. It seemed to offer a great deal — supercharging any vanilla df.apply function by either:</p><p><strong>“a) trying to vectorize the function where possible or, where vectorization is not possible:</strong></p><p><strong>b) automatically decide on the basis of speed whether to use Dask Parallel Processing or the vanilla Pandas apply</strong>”</p><p>Well I must say — what fantastic promise — and just one package to import and a single modifier to add — instead of df.apply I use df.swifter.apply. What is even better is we have a progress bar while we wait — super awesome. <em>I really ❤ python sometimes.</em> I trust you are digging the slackness here :)</p><p>After some power has been consumed and heat generated — we hopefully end up with some light in the shape of complete combinatoric calculations for over 4000 pairs.</p><pre>all_pairs = list(itertools.combinations(data2.columns,2)) #combinatoric generator no repeated elements, no reverses<br>coint_df = pd.DataFrame(all_pairs,columns =[&#39;RIC1&#39;,&#39;RIC2&#39;]) <br>coint_df[&#39;ADF&#39;] = coint_df.swifter.apply(lambda row: adfuller((data2[row.RIC1]/data2[row.RIC2])), axis=1)<br>coint_df[&#39;EG&#39;] = coint_df.swifter.apply(lambda row: ts.coint(data2[row.RIC1], data2[row.RIC2]), axis=1)<br>coint_df[&#39;PCorr&#39;] = coint_df.swifter.apply(lambda row: np.corrcoef(data2[row.RIC1],data2[row.RIC2]), axis =1)<br><br>coint_df</pre><pre>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Nj9fbBEJShynU2LQczjJdw.png" /></figure><p>We now wish to narrow this list down by selecting a subset that might display promising characteristics but first we need to unpack selected values from the returns of the statistical tests we ran previously.</p><p>Here again — we use the syntatically compact apply method with a lambda function to unpack our desired values — heck why not speed this up as well by adding some swifter super-awesomeness!</p><pre>coint_df[&#39;ADF_Crit&#39;] = coint_df.swifter.apply(lambda row: row.ADF[0], axis=1)<br>coint_df[&#39;ADF_t5&#39;] = coint_df.swifter.apply(lambda row: list(row.ADF[4].values())[1],axis=1)<br>coint_df[&#39;ADF_pVal&#39;] = coint_df.swifter.apply(lambda row: row.ADF[1], axis=1)<br>coint_df[&#39;EG_Crit&#39;] = coint_df.swifter.apply(lambda row: row.EG[0], axis=1)<br>coint_df[&#39;EG_t5&#39;] = coint_df.swifter.apply(lambda row: row.EG[2][1], axis=1)<br>coint_df[&#39;EG_pVal&#39;] = coint_df.swifter.apply(lambda row: row.EG[1], axis=1)<br>coint_df[&#39;PCorrVal&#39;] = coint_df.swifter.apply(lambda row: row.PCorr[0][1], axis=1)</pre><pre>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…<br><br><br><br><br><br><br>HBox(children=(FloatProgress(value=0.0, description=&#39;Pandas Apply&#39;, max=3916.0, style=ProgressStyle(descriptio…</pre><pre>coint_df</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*-LRfVX3guqcCa_lG_4bfyQ.png" /></figure><h4>Filtering our universe down to identify potentially attractive candidates</h4><p>Now we have unpacked all the relevant values we can simply filter the larger dataframe for pairs that satisfy our specific — in this case — additive, conditions below:</p><p>a) ADF Critical Value being less than t-test value at the 95% confidence level AND</p><p>b) ADF pVal being less than 0.02 AND</p><p>c) EG Critical Value being less than t-test value at the 95% confidence level AND</p><p>d) EG pVal being less than 0.02 AND</p><p>e) PCorrVal being greater than 0.4</p><p>This gives us a more manageable list of potential candidates. A point to note I have selected the threshold values intuitively — but you could widen or tighten these based on your requirements.</p><pre>low_coint = coint_df[(coint_df[&#39;ADF_Crit&#39;] &lt; coint_df[&#39;ADF_t5&#39;]) &amp; (coint_df[&#39;ADF_pVal&#39;] &lt; 0.03) &amp; <br>                    (coint_df[&#39;EG_Crit&#39;] &lt; coint_df[&#39;EG_t5&#39;]) &amp; (coint_df[&#39;EG_pVal&#39;] &lt; 0.03) &amp; (coint_df[&#39;PCorrVal&#39;] &gt; 0.4)]<br>low_coint.reset_index(drop=True)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*vqqJ-SNGzvVegfkDVNAqUg.png" /></figure><h4>Final visualisation check — Seaborn FacetGrid</h4><p>Now we have our promising list of pairs — lets move onto the final stage which for me is always visualisation. We will retrieve the ratio for each pair as a series and store to new dataframe then hand off this data to the excellent Seaborn facetgrid chart.</p><pre>pairlist = pd.DataFrame()<br>for row in low_coint.itertuples():<br>    pairlist[str(row.RIC1) + &#39;/&#39; + str(row.RIC2)] = data2[row.RIC1] /  data2[row.RIC2]<br><br>pairlist</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*xCALUmYngEyb0NYvpD0-ig.png" /></figure><pre>fig = plt.figure(figsize=(20,20))<br>for i,col in enumerate(pairlist.columns):<br>    ax=plt.subplot(10,5,i+1) <br>    pairlist[[col]].plot(ax=ax)<br>    <br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*QANMzEHJST1RKEQRyGb9yQ.png" /></figure><h4>Conclusion</h4><p>In this article — we have covered the basic idea behind pair-trading — which is a time-honoured market-neutral type of statistical arbitrage (stat-arb) strategy. We explained some of the salient points using a single pair as an example. Given the 2-fold weakness in this manual strategy — we needed to know what an appropriate pair might be — and the lack of a robust statistical selection process — we then embarked on a journey to industrialise our search process using brute force calculations of all relevant combinations of index constituents — in our case the FTSE 100.</p><p>Along the way we implemented iterative API calls to build a larger dataframe than a single call would allow for. We also implemented various statistical testing routines to try to add some robustness to our search and then used some simple filters to narrow down our universe to the most promising candidates. Along the way we met a new friend — Swifter — which offers great potential speedups via vectorisation or Dask parallelisation with basically no additional knowledge, code or effort. To be honest I already thought multiprocessing/multiprocess was fairly concise and straightforward — but Swifter really blew me away. I <strong>strongly</strong> recommend adding it to your toolkit for pandas intensive calculation workflows.</p><p>Finally — we graphed the filtered pair ratios <em>en-masse</em> so we could see the rough shapes of the ratios using the easy to use and efficient FacetGrid charting.</p><p>From the charts above we can see some very promising candidates which appear to have stable mean-reverting shapes. Annoyingly — also present are a number of shapes which although seemingly satisfying our statistical criterial, do not appear to be of an appropriate character. We would need to investigate this further which is beyond the scope of this article — suffice to say there are statistical exceptions to our basic rule filters which we may need to take account for or modify.</p><p>From here we could select appropriate pairs and then go to the next level of selecting appropriate +/- standard-deviation thresholds — by eye — but better still automating it all via algorithm. Again that is beyond the scope of this article.</p><p>For my eye — the most promising pairs from the list are INF.L/ULVR.L, UU.L/Land.L, WTB.L/LGEN.L, BP.L/RSA.L, PHNX.L/BAES.L, SPX.L/ICP.L. Of course — these are not in any way to be construed as recommendations or solicitations — just candidates worthy of further research and testing — again beyond the scope of this article.</p><p>I hope to have introduced the basic concepts of this type of strategy and provided you with a practical codebase to investigate further.</p><p><strong>Further Resources for Eikon Data API</strong></p><ul><li><a href="https://developers.refinitiv.com/eikon-data-apis">Overview</a></li><li><a href="https://developers.refinitiv.com/eikon-data-apis/quick-start">Quick Start</a></li><li><a href="https://developers.refinitiv.com/eikon-data-apis/docs">Documentation</a></li><li><a href="https://developers.refinitiv.com/eikon-data-apis/downloads">Downloads</a></li><li><a href="https://developers.refinitiv.com/eikon-data-apis/learning">Tutorials</a></li><li><a href="https://developers.refinitiv.com/eikon-data-apis/qa">Q&amp;A Forums</a></li></ul><p>For Content Navigation in Eikon — please use the Data Item Browser Application: Type ‘DIB’ into Eikon Search Bar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b61cf28db62a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/introduction-to-equity-pair-trading-b61cf28db62a">Introduction to Equity Pair Trading</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to News Sentiment Analysis with the Eikon Data API — A Python Example]]></title>
            <link>https://medium.com/@jas0nram/introduction-to-news-sentiment-analysis-with-the-eikon-data-api-a-python-example-9b048e18912d?source=rss-8eaefa21707f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b048e18912d</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quant]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[news-sentiment]]></category>
            <dc:creator><![CDATA[Jason Ramchandani]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 17:15:59 GMT</pubDate>
            <atom:updated>2019-08-30T11:17:55.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to News Sentiment Analysis with the Eikon Data API — A Python Example</h3><p>This article will demonstrate how we can conduct a simple sentiment analysis of news. In order to this I will use the Refinitiv <a href="https://developers.refinitiv.com/eikon-data-apis">Eikon Data APIs</a> that provide a broad and deep range of financial information. Natural Language Processing (NLP) is a big area of interest for those looking to gain insight and new sources of value from the vast quantities of unstructured data out there. The area is quite complex and there are many resources online that can help you familiarise yourself with this very interesting area. There are also many different packages that can help you as well as many different approaches to this problem. Whilst these are beyond the scope of this article — I will go through a simple implementation which will give you a swift enough introduction and practical codebase for further exploration and learning.</p><p>NLP is a field which enables computers to understand human language (voice or text). This is quite a big area of research and a little enquiry on your part will furnish you with the complexities of this problem set. Here we will be focussing on one application of this called <em>Sentiment Analysis</em>. In our case we will be taking news articles (unstructured text) for a particular company, <strong>Vodafone (RIC: VOD.L)</strong>, and we will attempt to grade this news to see how positive, negative or neutral it is. We will then try to see if this news has had an impact on the shareprice of <strong>VOD.L</strong>.</p><p>To do this really well is a non-trivial task, and most universities and financial companies will have departments and teams looking at this. We ourselves provide <a href="https://www.refinitiv.com/en/products/world-news-data">machine readable news</a> products with News Analytics (such as sentiment) over our <strong>Elektron</strong> platform in realtime at very low latency — these products are essentially consumed by <em>algorithmic applications</em> as opposed to <em>humans</em>.</p><p>We will try to do a similar thing as simply as possible to illustrate the key elements — our task is significantly eased by not having to do this in a low latency environment. We will be abstracting most of the complexities to do with the mechanics of actually analysing the text to various packages. You can then easily replace the modules such as the sentiment engine etc to improve your results as your understanding increases.</p><p>First, lets load the packages that we will need to use and set our app_id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*c0TJ1gENwiLs_1UU1ZEOng.png" /></figure><p>There are two API calls for news:</p><p><strong>get_news_headlines</strong> : returns a list of news headlines satisfying a query</p><p><strong>get_news_story</strong> : returns a HTML representation of the full news article</p><p>We will need to use both — thankfully they are really straightforward to use. We will need to use <strong>get_news_headlines</strong> API call to request a list of headlines. The first parameter for this call is a query. You don’t really need to know this query language as you can generate it using the <strong>News Monitor App</strong> (type <strong>NEWS</strong> into Eikon search bar) in <strong>Eikon</strong>.</p><p>You can see here I have just typed in 2 search terms, <strong>Vodafone</strong>, for the company, and, <strong>English</strong>, for the language I am interested in (in our example we will only be able to analyse English language text — though there are corpora, packages, methods you can employ to target other languages — though these are beyond the scope of this article). You can of course use any search terms you wish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*Hn2Bihz8Agg-M_59fzokTg.png" /></figure><p>After you have typed in what you want to search for — we can simply click in the search box and this will then generate the query text which we can then copy and paste into the API call below. It is easy for us to change logical operations such as <strong>AND</strong>, <strong>OR</strong>, <strong>NOT</strong> to suit our query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*m5VvXThPcPKLGYS9Kdv5-Q.png" /></figure><p>Next, we build 2 API calls to get 200 news headlines for VOD.L in English prior to 4th Dec 2018, concatenating our return frames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8mhvDGYT2hTKP1ls0TYjw.png" /></figure><p>I will just add 3 new columns which we will need to store some variables in later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*QLxV23Vd0TBRfY40KFCzsg.png" /></figure><p>So we have our frame with the most 200 news headline items. The headline is stored in the <strong>text</strong> column and the storyID which we will now use to pull down the actual articles themselves, is stored in the <strong>storyID</strong> column.</p><p>We will now iterate through the headline dataframe and pull down the news articles using the second of our news API calls, get_news_story. We simply pass the <strong>storyID</strong> to this API call and we are returned a HTML representation of the article — which allows you to render them nicely etc — however for our purposes we want to strip the HTML tags etc out and just be left with the plain text — as we don’t want to analyse HTML tags for sentiment. We will do this using the excellent <strong>BeautifulSoup</strong> package.</p><p>Once we have the text of these articles we can pass them to our sentiment engine which will give us a sentiment score for each article. So what is our sentiment engine? We will be using the simple <strong>TextBlob</strong> package to demo a rudimentary process to show you how things work. <strong>TextBlob</strong> is a higher level abstraction package that sits on top of <strong>NLTK</strong> (Natural Language Toolkit) which is a widely used package for this type of task.</p><p><strong>NLTK</strong> is quite a complex package which gives you a lot of control over the whole analytical process — but the cost of that is complexity and required knowledge of the steps involved. <strong>TextBlob</strong> shields us from this complexity, but we should at some stage understand what is going on under the hood. Thankfully there is plenty of information to guide us in this. We will be implementing the default <strong>PatternAnalyzer</strong> which is based on the popular <strong>Pattern</strong> library though there is also a <strong>NaiveBayesAnalyzer</strong> which is a <strong>NLTK</strong> classifier based on a movie review corpus.</p><p>All of this can be achieved in just a few lines of code. This is quite a dense codeblock — so I have commented the key steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuCkL6bLeolro8kySkp4Tg.png" /></figure><p>Looking at our dataframe we can now see 3 new columns we added on the right, <em>Polarity</em>, <em>Subjectivity</em> and <em>Score </em>are now populated<em>.</em> As we have seen <em>Polarity</em> is the actual sentiment polarity returned from <strong>TextBlob</strong> (ranging from -1(negative) to +1(positive), <em>Subjectivity</em> is a measure (ranging from 0 to 1) where 0 is very objective and 1 is very subjective, and <em>Score</em> is simply a Positive, Negative or Neutral rating based on the thresholds of the polarities.</p><p>We would now like to see what, if any, impact this news has had on the shareprice of <strong>VOD.L</strong>. There are many ways of doing this — but to make things simple, I would like to see what the average return is at various points in time <strong>AFTER</strong> the news has broken. I want to check if there are <em>aggregate differences</em> in the <em>average returns</em> from the Positive, Neutral and Negative buckets we created earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*OTLHmKRxAQ8lyWhlDDIfxQ.png" /></figure><p>We will need to create some new columns for the next part of this analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*QqCtgLxtI-B22sR2yuNICg.png" /></figure><p>OK so I now just need to get the timestamp of each news item, truncate it to minute data (ie remove second and microsecond components) and get the base shareprice of <strong>VOD.L</strong> at that time, and at several intervals after that time, in our case <em>t+2 mins, t+5 mins, t+10 mins, t+30 mins</em>, calculating the % change for each interval.</p><p>An important point to bear in mind here is that news can be generated at anytime — 24 hours a day — outside of normal market hours. So, for news generated outside normal market hours for <strong>VOD.L</strong> in our case, we would have to wait until the next market opening to conduct our calculations. Of course, there are a number of issues here concerning our ability to attribute price movement to our news item in isolation (basically we cannot). That said, there might be other ways of doing this — for example looking at <strong>GDRs/ADRs</strong> or surrogates etc — these are beyond the scope of this introductory article. In our example, these news items are simply discarded.</p><p>We will now loop through each news item in the dataframe, calculate (where possible) and store the derived performance numbers in the columns we created earlier: twoM…thirtyM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*VSrqi8MJvRd8hSdpT9TB2Q.png" /></figure><p>Fantastic — we have now completed the analytical part of our study. Finally, we just need to aggregate our results by <em>Score</em> bucket in order to draw some conclusions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fiQ0VrpyS_6S4IJt-8AUxA.png" /></figure><p><strong>Observations</strong></p><p>From our initial results — it would appear that there are indeed some small directional differences in returns between the positive and neutral groups over after news broke of all time frames observed. One might have expected some negative returns for the negative bucket but <em>n</em> was very low — so on this occasion we were unable to ascertain such effects. However, this is a pretty good basis for further investigation. So where could we go from here?</p><p>We have a relatively small <em>n</em> here (of the 200 news items, only 60 broke in market hours) so we might want to increase the size of the study.</p><p>We might also want to try to separate out more positive or negative news — ie change the threshold of the buckets to try to identify more prominent sentiment articles — maybe that could have more of an impact on performance.</p><p>In terms of capturing news impact — we have thrown a lot of news articles out as they happened outside of market hours — as it is more complex to ascertain impact — we might try to find a way of including some of this in our analysis — I mentioned looking at overseas listings <strong>GDR/ADRs</strong> or surrogates above. Alternatively, we could using <strong>EXACTLY</strong> the same process look at all news for an index future — say the <strong>S&amp;P500 emini</strong> — as this trades on Globex pretty much round the clock — so we would be throwing out a lot less of the news articles. Great I hear you cry — but would each news article be able to influence a whole index? Well if it’s a company with a large market cap then perhaps it might? Are index futures more sensitive to some types of articles than others? Is there a temporal element to this? These are all excellent questions. Or what about cryptocrurrencies? They trade 24/7? and so on.</p><p>We could also investigate what is going on with our sentiment engine. We might be able to generate more meaningful results by tinkering with the underlying processes and parameters or changing the whole sentiment engine. Using a different, more domain-specific corpora might help us to generate more relevant scores.</p><p>You will see there is plenty of scope to get much more involved here.</p><p>This article was intended as an introduction to this most interesting of areas. I hope to have de-mystified this area for you somewhat and shown how it is possible to get started with this type of complex analysis using only a few lines of code, a simple easy to use yet powerful API and some really fantastic packages, to generate some meaningful results.</p><p>To get a free one month trial of Eikon, please go <a href="https://www.refinitiv.com/en/products/eikon-trading-software/eikon-app-api-innovation/eikon-data-api">here</a>.</p><p>To get the source code for this article from github please go <a href="https://github.com/Refinitiv-API-Samples/Article.EikonAPI.Python.NewsSentimentAnalysis">here</a>.</p><p>For more information and resources about the Eikon Data API — including more use cases, quick start guides, more code samples, documentation, video tutorials and much more please go <a href="https://developers.refinitiv.com/eikon-apis/eikon-data-api">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b048e18912d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>